(() => {
const bot = document.documentElement?.dataset?.bot;
if (!bot) {
console.error("BOT not injected (data-bot missing)");
return;
}
// White-label branding (set inline in the page
); falls back to ADPanel defaults.
const BRAND_NAME = (window.__BRANDING__ && window.__BRANDING__.appName) || 'ADPanel';
const BRAND_LOGO = (window.__BRANDING__ && window.__BRANDING__.logoUrl) || '/images/ADPanel.webp';
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, function (m) {
return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]);
});
}
// adpanel:planner-confirm-title — ONE dialog-text normalizer for every
// attacker-reachable string shown in a native confirm()/alert() dialog.
// Native dialogs render plain text, so the only hardening is collapsing
// whitespace/newlines and capping length: an authored file/plan name must
// not be able to restyle a security dialog. Shared by all dialog sites so
// the copies cannot drift (bot.js is one IIFE — duplicate declarations
// shadow file-wide).
function dialogText(value) {
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, 120);
}
let htmlEntityDecoder = null;
function decodeHtmlEntities(raw) {
const value = String(raw || '');
if (!value || !/[&](?:[a-z]+|#\d+|#x[0-9a-f]+);/i.test(value)) return value;
if (!htmlEntityDecoder) htmlEntityDecoder = document.createElement('textarea');
htmlEntityDecoder.innerHTML = value;
return htmlEntityDecoder.value;
}
const ANSI_SGR_RE = /\x1B\[[0-9:;]*m/g;
function skipAnsiOscSequence(str, idx) {
let i = idx;
while (i < str.length) {
const code = str.charCodeAt(i);
if (code === 0x07) return i + 1;
if (code === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2;
i += 1;
}
return str.length;
}
function skipAnsiEscTerminatedSequence(str, idx) {
let i = idx;
while (i < str.length) {
if (str.charCodeAt(i) === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2;
i += 1;
}
return str.length;
}
function skipAnsiCsiSequence(str, idx) {
let i = idx;
while (i < str.length) {
const code = str.charCodeAt(i);
if (code >= 0x40 && code <= 0x7e) {
return { next: i + 1, keep: str[i] === 'm' };
}
i += 1;
}
return { next: str.length, keep: false };
}
function sanitizeAnsiForConsole(input) {
const str = String(input || '');
if (!str) return '';
let out = '';
for (let i = 0; i < str.length;) {
const code = str.charCodeAt(i);
if (code === 0x1b || code === 0x9b) {
const start = i;
if (code === 0x9b) {
const parsed = skipAnsiCsiSequence(str, i + 1);
if (parsed.keep) out += str.slice(start, parsed.next);
i = parsed.next;
continue;
}
const next = str.charCodeAt(i + 1);
if (next === 0x5b) {
const parsed = skipAnsiCsiSequence(str, i + 2);
if (parsed.keep) out += str.slice(start, parsed.next);
i = parsed.next;
continue;
}
if (next === 0x5d) {
i = skipAnsiOscSequence(str, i + 2);
continue;
}
if (next === 0x50 || next === 0x58 || next === 0x5e || next === 0x5f) {
i = skipAnsiEscTerminatedSequence(str, i + 2);
continue;
}
if (next >= 0x40 && next <= 0x5f) {
i += 2;
continue;
}
i += 1;
continue;
}
if ((code < 32 || code === 127) && code !== 10 && code !== 13 && code !== 9) {
i += 1;
continue;
}
out += str[i];
i += 1;
}
return out;
}
function stripRenderableAnsi(text) {
return String(text || '').replace(ANSI_SGR_RE, '');
}
function visibleConsoleText(text) {
return stripRenderableAnsi(text).replace(/…+/g, '');
}
function stripDockerStreamFrames(raw) {
const value = String(raw || '');
if (value.length < 8) return value;
let out = '';
let usedFrames = false;
for (let i = 0; i < value.length;) {
const c0 = value.charCodeAt(i);
if (
(c0 === 1 || c0 === 2 || c0 === 3) &&
value.charCodeAt(i + 1) === 0 &&
value.charCodeAt(i + 2) === 0 &&
value.charCodeAt(i + 3) === 0 &&
i + 8 <= value.length
) {
const frameLen = (
((value.charCodeAt(i + 4) & 0xff) << 24) |
((value.charCodeAt(i + 5) & 0xff) << 16) |
((value.charCodeAt(i + 6) & 0xff) << 8) |
(value.charCodeAt(i + 7) & 0xff)
) >>> 0;
if (frameLen === 0) {
usedFrames = true;
i += 8;
continue;
}
if (i + 8 + frameLen <= value.length) {
out += value.slice(i + 8, i + 8 + frameLen);
i += 8 + frameLen;
usedFrames = true;
continue;
}
}
out += value[i];
i += 1;
}
return usedFrames ? out : value;
}
function normalizeAiServerNameCandidate(raw) {
let name = String(raw || '').trim();
if (!name) return '';
if (name.includes('..') || /[\/\\]/.test(name) || name.length > 120) return '';
name = name.replace(/\s+/g, '-').replace(/[^\w\-_.]/g, '').replace(/^-+|-+$/g, '');
return name;
}
function flashBar(barId) {
const fill = document.getElementById(barId);
if (!fill) return;
fill.classList.remove('complete');
fill.style.width = '0%';
void fill.offsetWidth;
fill.style.width = '70%';
setTimeout(() => { fill.style.width = '90%'; }, 150);
setTimeout(() => { fill.classList.add('complete'); }, 300);
setTimeout(() => { fill.classList.remove('complete'); fill.style.width = '0%'; }, 1100);
}
function flashFilesBar() { flashBar('filesFlashFill'); }
function flashEditorBar() { flashBar('editorFlashFill'); }
// Store progress bar helpers
let _storeBarTimer = null;
function storeBarStart(msg) {
const fill = document.getElementById('storeFlashFill');
if (!fill) return;
fill.classList.remove('complete');
fill.style.transition = 'none';
fill.style.width = '0%';
void fill.offsetWidth;
fill.style.transition = '';
fill.style.width = '30%';
setTimeout(() => { if (fill.style.width !== '0%') fill.style.width = '65%'; }, 400);
setTimeout(() => { if (fill.style.width !== '0%') fill.style.width = '85%'; }, 1200);
}
function storeBarDone(success) {
const fill = document.getElementById('storeFlashFill');
if (!fill) return;
fill.style.width = '100%';
if (!success) {
fill.style.background = 'linear-gradient(90deg,#ef4444,#b91c1c,#ef4444)';
}
setTimeout(() => {
fill.classList.add('complete');
setTimeout(() => {
fill.classList.remove('complete');
fill.style.width = '0%';
fill.style.background = '';
}, 600);
}, 200);
}
// Store toast helper
let _storeToastTimer = null;
function showStoreToast(msg, type = 'success', duration = 3000) {
const el = document.getElementById('storeToast');
if (!el) return;
clearTimeout(_storeToastTimer);
el.className = 'store-toast';
const icon = type === 'error' ? ''
: type === 'success' ? ''
: '';
el.innerHTML = icon + ' ' + escapeHtml(msg);
el.classList.add('show', type === 'error' ? 'toast-error' : type === 'success' ? 'toast-success' : '');
_storeToastTimer = setTimeout(() => {
el.classList.remove('show');
}, duration);
}
// Store confirm helper (replaces confirm()). The overlay is a singleton,
// so each call chains behind the previous one: while a dialog is open the
// next storeConfirm waits, and a single OK click can only ever resolve the
// one confirm whose handlers are attached. The old per-call handler
// attachment resolved EVERY pending confirm with one OK click — a
// double-click on a version row opened two confirms and both resolved on
// the same tap, driving two concurrent destructive installs.
let _storeConfirmTail = Promise.resolve();
function storeConfirm(msg) {
const run = () => new Promise(resolve => {
const overlay = document.getElementById('storeConfirmOverlay');
const msgEl = document.getElementById('storeConfirmMsg');
const okBtn = document.getElementById('storeConfirmOk');
const cancelBtn = document.getElementById('storeConfirmCancel');
if (!overlay || !msgEl || !okBtn || !cancelBtn) { resolve(window.confirm(msg)); return; }
msgEl.textContent = msg;
overlay.setAttribute('aria-hidden', 'false');
overlay.classList.add('show');
function cleanup(result) {
overlay.classList.remove('show');
overlay.setAttribute('aria-hidden', 'true');
okBtn.removeEventListener('click', onOk);
cancelBtn.removeEventListener('click', onCancel);
overlay.removeEventListener('click', onBg);
resolve(result);
}
function onOk() { cleanup(true); }
function onCancel() { cleanup(false); }
function onBg(e) { if (e.target === overlay) cleanup(false); }
okBtn.addEventListener('click', onOk);
cancelBtn.addEventListener('click', onCancel);
overlay.addEventListener('click', onBg);
});
const chained = _storeConfirmTail.then(run, run);
_storeConfirmTail = chained.then(() => { }, () => { });
return chained;
}
const sio = window.io;
let socket;
if (typeof sio !== "function") {
console.error("Socket.IO client not loaded. Console features will be disabled.");
socket = {
on: () => { },
off: () => { },
emit: () => { },
connected: false
};
} else {
try {
// Use websocket-only transport to bypass the polling→upgrade flow.
// With PM2 cluster mode (multiple workers on same port), polling
// requests can round-robin to a different worker than the one that
// created the session, causing 400 "Session ID Unknown". Websocket
// is a persistent TCP connection so it always stays on the same worker.
socket = sio({ transports: ['websocket'] });
} catch (err) {
console.error("Failed to initialize Socket.IO:", err);
socket = {
on: () => { },
off: () => { },
emit: () => { },
connected: false
};
}
}
const bootstrapUser = window.__ADPANEL_BOOTSTRAP__ && window.__ADPANEL_BOOTSTRAP__.currentUser
? window.__ADPANEL_BOOTSTRAP__.currentUser
: null;
const currentUser = bootstrapUser || null;
function getRequestedAssistantBotAction() {
const params = new URLSearchParams(window.location.search || "");
return String(params.get("assistantAction") || "").trim();
}
let assistantActionHandlers = null;
let assistantRequestedActionConsumed = false;
// Flip true only when the fetch-permissions bootstrap step has applied the
// real permission set; until then hasPerm() reads the all-false default.
let bootPermissionsApplied = false;
// adpanel:boot-perm-gate — Single pending slot for data-action clicks that
// land inside the boot-permission window. The bot.ejs inline page system
// activates a page visually (capture-phase listener) BEFORE bot.js's bubble
// handler runs, so silently dropping the gated click stranded the page on
// its static "Loading …" template forever. Deferral, not bypass: the slot
// holds the last click's handler and it runs only from the bootstrap's
// flush, after the real permission set has been applied.
let pendingBootGatedAction = null;
// Read+clear BEFORE invoking, so an action that (re-)enters the gate during
// its own flush can never find the slot still holding it; it also cannot
// linger as a would-be second flush — with bootPermissionsApplied already
// true, every later click takes the direct path and nothing re-queues.
function flushPendingBootGatedAction() {
const pending = pendingBootGatedAction;
pendingBootGatedAction = null;
if (typeof pending !== "function") return;
try {
pending();
} catch (err) {
// Outside runBootstrapStep on purpose: the flush is not a bootstrap
// step, so a deferred click's own failure must not be mislabeled as
// any bootstrap step's failure.
console.error("[bot-bootstrap] deferred boot-gated action failed:", err);
}
}
// adpanel:boot-perm-gate — bot.ejs's showConsoleView() bypasses the
// data-action gate (the Console dock item is wired by the inline-page
// script directly, and the modal-close/inline-teardown paths return to the
// console view without any data-action), so it announces itself with this
// DOM CustomEvent. Ending up on the console view means the user LEFT
// whatever inline page a deferred click was queued for — that queued
// action is stale and would otherwise flush onto the console view as a
// phantom modal (e.g. planner queued, then Console dock clicked, then
// permissions load → openPlannerModal over the console). Bound ONCE here
// at IIFE scope — never per modal open; and once the flush has already
// emptied the slot this is a no-op, so console views shown later in the
// session cannot affect anything.
const CONSOLE_VIEW_SHOWN_EVENT = "adpanel:console-view-shown";
document.addEventListener(CONSOLE_VIEW_SHOWN_EVENT, () => {
pendingBootGatedAction = null;
});
function clearRequestedAssistantBotAction() {
const url = new URL(window.location.href);
if (!url.searchParams.has("assistantAction")) return;
url.searchParams.delete("assistantAction");
const nextSearch = url.searchParams.toString();
const nextUrl = `${url.pathname}${nextSearch ? `?${nextSearch}` : ""}${url.hash || ""}`;
try {
window.history.replaceState({}, "", nextUrl);
} catch {
}
}
function runRequestedAssistantBotAction(actionHandlers) {
if (assistantRequestedActionConsumed) return;
const requestedAction = getRequestedAssistantBotAction();
if (!requestedAction) return;
const handler = actionHandlers?.[requestedAction];
if (typeof handler !== "function") return;
assistantRequestedActionConsumed = true;
window.setTimeout(() => {
try {
// A URL parameter is not a user interaction: side-effecting (power)
// actions must never auto-execute from a deep link. Arm them behind an
// explicit confirm dialog instead (CSRF-by-navigation protection).
if (ASSISTANT_POWER_ACTIONS.has(requestedAction)) {
requestAssistantPowerActionConfirm(requestedAction, handler);
return;
}
handler();
clearRequestedAssistantBotAction();
} catch (error) {
console.error("[assistant-bot-action] failed:", error);
}
}, 160);
}
// Actions requested via ?assistantAction= that change server or console
// state. They require an explicit user click after page load before firing.
const ASSISTANT_POWER_ACTIONS = new Set(["run", "stop", "kill", "send", "clear", "create-new"]);
const ASSISTANT_POWER_ACTION_LABELS = {
"run": {
title: "Start Server",
button: "Start Server",
description: "The AI assistant asked to start this server. Start it now?"
},
"stop": {
title: "Stop Server",
button: "Stop Server",
description: "The AI assistant asked to stop this server. Stop it now?"
},
"kill": {
title: "Force Kill Server",
button: "Force Kill",
description: "The AI assistant asked to force kill this server. This immediately terminates the server process. Kill it now?"
},
"send": {
title: "Send Console Command",
button: "Send Command",
description: "The AI assistant asked to send the command currently typed in the console input. Send it now?"
},
"clear": {
title: "Clear Console",
button: "Clear Console",
description: "The AI assistant asked to clear the console. Clear it now?"
},
"create-new": {
title: "Create File or Folder",
button: "Continue",
description: "The AI assistant asked to create a file or folder. Continue?"
}
};
let assistantPowerConfirmState = null;
function assistantPowerConfirmEscapeHandler(e) {
if (e.key !== "Escape") return;
if (!assistantPowerConfirmState) return;
dismissAssistantPowerConfirm();
}
function ensureAssistantPowerConfirmModal() {
let modal = document.getElementById("assistantPowerActionModal");
if (modal) return modal;
modal = document.createElement("div");
modal.id = "assistantPowerActionModal";
modal.className = "clear-console-modal";
modal.style.display = "none";
modal.setAttribute("aria-hidden", "true");
modal.innerHTML = `
`;
document.body.appendChild(modal);
modal.addEventListener("click", (e) => {
if (e.target === modal || e.target.classList.contains("clear-console-glass-layer")) {
dismissAssistantPowerConfirm();
}
});
document.getElementById("assistantPowerActionCancel").addEventListener("click", () => dismissAssistantPowerConfirm());
document.getElementById("assistantPowerActionConfirm").addEventListener("click", () => approveAssistantPowerConfirm());
document.addEventListener("keydown", assistantPowerConfirmEscapeHandler);
return modal;
}
// Modals that hide the dock while showing (same .show-class state the
// clear-console and EULA modals use). Chained actions can open one of them
// while this modal's 300 ms close fade is still pending (e.g. confirming
// ?assistantAction=clear opens the clear-console modal), and the dock
// (z-index 99999) would otherwise reappear on top of that still-open modal.
function isAnyDockHidingModalShowing() {
const ids = ["assistantPowerActionModal", "clearConsoleModal", "eulaModal"];
return ids.some((id) => {
const el = document.getElementById(id);
return !!(el && el.classList.contains("show"));
});
}
function closeAssistantPowerConfirmModal(modal) {
modal.classList.remove("show");
window.setTimeout(() => {
if (!modal.classList.contains("show")) {
modal.style.display = "none";
// Only hand the dock back when no other dock-hiding modal took it
// over; that modal's own close path restores the dock.
if (!isAnyDockHidingModalShowing()) {
toggleDock(true);
}
}
}, 300);
}
// Confirm was dismissed (Cancel button, backdrop or Escape): the pending
// action must never fire. The URL parameter is cleared so a reload does not
// re-prompt.
function dismissAssistantPowerConfirm() {
const state = assistantPowerConfirmState;
if (!state) return;
assistantPowerConfirmState = null;
closeAssistantPowerConfirmModal(state.modal);
clearRequestedAssistantBotAction();
}
// Explicit human click on the Confirm button: only now run the requested
// handler. Its own permission and power-state checks still apply.
function approveAssistantPowerConfirm() {
const state = assistantPowerConfirmState;
if (!state) return;
assistantPowerConfirmState = null;
closeAssistantPowerConfirmModal(state.modal);
clearRequestedAssistantBotAction();
try {
state.handler();
} catch (error) {
console.error("[assistant-bot-action] failed:", error);
}
}
function requestAssistantPowerActionConfirm(action, handler) {
if (assistantPowerConfirmState) return;
const labels = ASSISTANT_POWER_ACTION_LABELS[action] || {
title: "Confirm Action",
button: "Confirm",
description: `The AI assistant requested the "${action}" action. Run it now?`
};
const modal = ensureAssistantPowerConfirmModal();
const titleEl = document.getElementById("assistantPowerActionTitle");
const descEl = document.getElementById("assistantPowerActionDesc");
const confirmEl = document.getElementById("assistantPowerActionConfirm");
if (titleEl) titleEl.textContent = labels.title;
if (descEl) descEl.textContent = labels.description;
if (confirmEl) confirmEl.textContent = labels.button;
modal.style.display = "flex";
requestAnimationFrame(() => {
modal.classList.add("show");
toggleDock(false);
});
assistantPowerConfirmState = { action, handler, modal };
}
const sidebarToggle = document.getElementById('sidebarToggle');
const floatingSidebar = document.getElementById('floatingSidebar');
const profileCard = document.getElementById('profileCard');
const statusPopover = document.getElementById('statusPopover');
const statusInput = document.getElementById('statusInput');
const statusDuration = document.getElementById('statusDuration');
const saveStatus = document.getElementById('saveStatus');
const cancelStatus = document.getElementById('cancelStatus');
const profileStatusLabel = document.getElementById('profileStatusLabel');
const statusDot = document.querySelector('.status-dot');
let profileEmailEl = null;
const STATUS_KEY = 'adpanel-profile-status';
function syncCustomSelectOptions(selectId) {
const select = document.getElementById(selectId);
if (!select) return;
const wrapper = select.closest('.custom-select-wrapper');
if (!wrapper) return;
const customSelect = wrapper.querySelector('.custom-select') || wrapper.querySelector('.select-wrap');
const customOptions = wrapper.querySelector('.custom-options');
const currentSpan = customSelect?.querySelector('.current');
if (!customSelect || !customOptions || !currentSpan) return;
// Force close and apply disabled styling class if disabled
if (select.disabled) {
customSelect.classList.add('disabled');
customSelect.classList.remove('open');
customOptions.classList.remove('show');
} else {
customSelect.classList.remove('disabled');
}
// Clear old custom options
customOptions.innerHTML = '';
// Update current selected span text safely
if (select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
currentSpan.textContent = select.options[select.selectedIndex].textContent;
} else {
currentSpan.textContent = '';
}
// Build new options
Array.from(select.options).forEach(opt => {
// Do not add disabled placeholder options to the dropdown list
if (opt.disabled && !opt.value) return;
// adpanel:scheduler-action-perm-mirror — options marked hidden
// (opt.hidden) are permission-gated scheduler actions the user cannot
// submit; they must not surface in the custom dropdown either, or the
// dropdown would offer an action the create route 403s.
if (opt.hidden) return;
const div = document.createElement('div');
div.className = 'option';
div.dataset.value = opt.value;
div.textContent = opt.textContent;
if (opt.selected) div.classList.add('selected');
customOptions.appendChild(div);
});
}
function bindUiActions() {
function setupCustomSelect(wrapper) {
const select = wrapper.querySelector('select');
const customSelect = wrapper.querySelector('.custom-select') || wrapper.querySelector('.select-wrap');
const customOptions = wrapper.querySelector('.custom-options');
const currentSpan = customSelect?.querySelector('.current');
if (!select || !customSelect || !customOptions || !currentSpan) return;
if (customOptions.children.length === 0 && select.options.length > 0) {
Array.from(select.options).forEach(opt => {
const div = document.createElement('div');
div.className = 'option';
div.dataset.value = opt.value;
div.textContent = opt.textContent;
if (opt.selected) div.classList.add('selected');
customOptions.appendChild(div);
});
if (select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
currentSpan.textContent = select.options[select.selectedIndex].textContent;
}
}
customSelect.addEventListener('click', (e) => {
e.stopPropagation();
if (select.disabled) return; // Prevent clicks and drop-down if disabled
document.querySelectorAll('.custom-select, .select-wrap').forEach(el => {
if (el !== customSelect) {
el.classList.remove('open');
const otherWrapper = el.closest('.custom-select-wrapper');
if (otherWrapper) otherWrapper.querySelector('.custom-options')?.classList.remove('show');
}
});
customSelect.classList.toggle('open');
customOptions.classList.toggle('show');
});
customOptions.addEventListener('click', (e) => {
if (!e.target.classList.contains('option') && !e.target.classList.contains('custom-option')) return;
const value = e.target.dataset.value;
const text = e.target.textContent;
currentSpan.textContent = text;
wrapper.querySelectorAll('.option, .custom-option').forEach(el => el.classList.remove('selected'));
e.target.classList.add('selected');
select.value = value;
select.dispatchEvent(new Event('change'));
customSelect.classList.remove('open');
customOptions.classList.remove('show');
});
}
document.querySelectorAll('.custom-select-wrapper').forEach(setupCustomSelect);
document.addEventListener('click', (e) => {
if (!e.target.closest('.custom-select-wrapper')) {
document.querySelectorAll('.custom-select, .select-wrap').forEach(el => el.classList.remove('open'));
document.querySelectorAll('.custom-options').forEach(el => el.classList.remove('show'));
}
});
const actionHandlers = {
"open-files": () => openFilesModal(),
"open-task": () => openTaskModal(),
"open-store": () => openStoreModal(),
"open-activity": () => openActivityModal(),
"open-backups": () => openBackupsModal(),
"open-scheduler": () => openSchedulerModal(),
"open-planner": () => openPlannerModal(),
"open-resource-stats": () => openResourceStatsPopup(),
"open-ai-help": () => openAiHelpModal(),
"open-reinstall": () => reinstallController.open(),
"run": () => run(),
"stop": () => stop(),
"kill": () => killServer(),
"send": () => sendCommand(),
"clear": () => clearConsole(),
"create-new": () => createNew(),
"go-home": () => { window.location = "/"; },
// The taskbar Console button: a full navigation back to /server/
// (fresh page load, like the go-home handler). CSP sets
// script-src-attr 'none', so this must stay a real listener — an inline
// onclick attribute would be silently blocked by the browser.
"open-console": () => { window.location.href = `/server/${encodeURIComponent(bot)}`; },
};
document.querySelectorAll('[data-action]').forEach((el) => {
if (el.dataset.actionBound) return;
const action = actionHandlers[el.dataset.action];
if (!action) return;
el.dataset.actionBound = "1";
el.addEventListener('click', (e) => {
e.preventDefault();
if (
el.classList.contains('disabled') ||
el.getAttribute('aria-disabled') === 'true' ||
(typeof el.disabled === 'boolean' && el.disabled)
) return;
// adpanel:boot-perm-gate — hasPerm reads the all-false default until the
// fetch-permissions bootstrap step applies the real set, so a permitted
// user clicking a gated scene button in that window would read a false
// "no permission" denial. Fail closed: no data-action runs before the
// permission set that gates them has loaded. The page visual state is
// already switched by bot.ejs's capture handler at this point, so the
// click is DEFERRED into the single pending slot (last click wins) and
// flushed by the fetch-permissions step instead of being dropped —
// the flush is the only executor, so nothing runs early.
if (!bootPermissionsApplied) {
pendingBootGatedAction = action;
return;
}
action();
});
});
assistantActionHandlers = actionHandlers;
const listEl = document.getElementById("list");
if (listEl && !listEl.dataset.versionBound) {
listEl.dataset.versionBound = "1";
listEl.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-version]");
if (!btn) return;
e.preventDefault();
const version = btn.getAttribute("data-version") || "";
const kind = btn.getAttribute("data-kind") || "";
if (!version) return;
// Same re-entrancy guard as the store version rows: a double-click on
// a legacy runtime button must stay a single install attempt (the
// submit-slot guard is the backstop; this keeps it silent).
if (btn.dataset.installBusy === "1") return;
btn.dataset.installBusy = "1";
const pending = kind === "node" ? changeNodeVersion(version) : changeVersion(version);
pending
.catch((err) => showStoreToast(err?.message || err, 'error'))
.finally(() => { delete btn.dataset.installBusy; });
});
}
const breadcrumbsEl = document.getElementById("breadcrumbs");
if (breadcrumbsEl && !breadcrumbsEl.dataset.bound) {
breadcrumbsEl.dataset.bound = "1";
breadcrumbsEl.addEventListener("click", (e) => {
const link = e.target.closest("a[data-path]");
if (!link) return;
e.preventDefault();
const path = link.getAttribute("data-path") || "";
loadExplorer(path);
});
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", bindUiActions);
} else {
bindUiActions();
}
function applyStatus(statusObj) {
if (!statusObj || (statusObj.expiresAt && Date.now() > statusObj.expiresAt)) {
profileStatusLabel.textContent = 'Available';
if (statusDot) statusDot.style.background = '#22c55e';
localStorage.removeItem(STATUS_KEY);
return;
}
profileStatusLabel.textContent = statusObj.text || 'Available';
if (statusDot) statusDot.style.background = '#38bdf8';
}
function loadStatus() {
fetch('/api/me/status')
.then(res => res.json())
.then(data => {
if (data.ok && data.status) {
applyStatus(data.status);
} else {
applyStatus(null);
}
})
.catch(() => applyStatus(null));
}
function persistStatus(text, duration) {
let expiresAt = null;
if (duration !== 'never') {
const ms = parseInt(duration, 10);
if (!Number.isNaN(ms)) expiresAt = Date.now() + ms;
}
const payload = { text: text || 'Available', expiresAt };
fetch('/api/me/status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
.then(res => res.json())
.then(data => {
if (data.ok) {
applyStatus(payload);
}
})
.catch(err => console.error('Failed to save status:', err));
}
function setSidebar(open) {
if (!floatingSidebar || !sidebarToggle) return;
if (open) {
floatingSidebar.classList.add('open');
sidebarToggle.classList.add('active');
return;
}
floatingSidebar.classList.remove('open');
sidebarToggle.classList.remove('active');
if (statusPopover) statusPopover.classList.remove('show');
}
function toggleSidebar() {
const isOpen = floatingSidebar && floatingSidebar.classList.contains('open');
setSidebar(!isOpen);
}
setSidebar(true);
if (sidebarToggle) {
sidebarToggle.addEventListener('click', (e) => {
e.stopPropagation();
toggleSidebar();
});
}
if (profileCard) {
profileCard.addEventListener('click', (e) => {
e.stopPropagation();
if (!floatingSidebar || !floatingSidebar.classList.contains('open')) return;
if (statusPopover) {
const showing = statusPopover.classList.toggle('show');
if (showing && statusInput) statusInput.focus();
}
});
}
if (saveStatus) {
saveStatus.addEventListener('click', () => {
const text = statusInput ? statusInput.value.trim() : '';
const duration = statusDuration ? statusDuration.value : 'never';
persistStatus(text, duration);
if (statusPopover) statusPopover.classList.remove('show');
});
}
if (cancelStatus) {
cancelStatus.addEventListener('click', () => {
if (statusPopover) statusPopover.classList.remove('show');
});
}
document.addEventListener('click', (e) => {
if (statusPopover && statusPopover.classList.contains('show')) {
const clickInsidePopover = statusPopover.contains(e.target);
const clickOnProfile = profileCard && profileCard.contains(e.target);
if (!clickInsidePopover && !clickOnProfile) statusPopover.classList.remove('show');
}
});
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
setSidebar(false);
if (statusPopover) statusPopover.classList.remove('show');
}
});
loadStatus();
let REMOTE_MODE = false;
let NODE_ONLINE = true;
let SERVER_MISSING = false;
function setNodeOnline(isOnline) {
NODE_ONLINE = !!isOnline;
// The overlay must reflect BOTH conditions: a node that is offline, or a node
// that is online but reports the server as missing. Keying only on offline made
// the popup stick around after the node restarted.
updateOfflineState(!NODE_ONLINE || SERVER_MISSING);
}
let NODE_ID = null;
let NODE_API_BASE = `/api/nodes/server/${encodeURIComponent(bot)}`;
let NODE_MAX_UPLOAD_MB = 0;
let NODE_MAX_UPLOAD_BYTES = 0;
let logSource = null;
let activeRemoteLogUrl = '';
let remoteLogTransport = 'none';
let topoInfoPromise = null;
const CONSOLE_REQUEST_TIMEOUT_MS = 15_000;
const INITIAL_CONSOLE_HISTORY_LIMIT = 5000;
const REMOTE_LOG_SNAPSHOT_TAIL = 5000;
// Marker prefix the node embeds to carry a console command inline in the same
// log stream as its output (single source of truth for ordering). Keep in sync
// with consoleCommandMarkerPrefix in main.go / CONSOLE_COMMAND_MARKER_PREFIX in
// index.js. When seen in the live stream, render it as a plain "> "
// line (Pterodactyl-style) instead of raw output.
const CONSOLE_COMMAND_MARKER_PREFIX = 'ADPANELCMD>> ';
function extractConsoleCommandMarker(rawLine) {
const raw = String(rawLine || '');
const idx = raw.indexOf(CONSOLE_COMMAND_MARKER_PREFIX);
if (idx === -1) return null;
const command = raw.slice(idx + CONSOLE_COMMAND_MARKER_PREFIX.length).replace(/[\r\n]+/g, ' ').trim();
return command || null;
}
// Render a single live stream payload, converting an embedded command marker
// into a formatted "> " line (deduplicated against the optimistic
// local echo), otherwise appending it as normal output.
function appendLiveConsoleLine(rawLine, ts = Date.now()) {
if (isInstallingActive) return;
if (typeof rawLine === 'string' && rawLine.includes('[ADPanel Setup]')) return;
const lineTs = Number(ts) || Date.now();
if (lineTs > lastConsoleHistorySyncTs) {
lastConsoleHistorySyncTs = lineTs;
}
const markerCommand = extractConsoleCommandMarker(rawLine);
if (markerCommand) {
appendConsoleCommandLine(markerCommand, lineTs);
return;
}
appendToConsole(rawLine, { live: true });
}
function ensureSocketConsoleJoin() {
if (!socket || !socket.connected) return;
socket.emit("join", bot);
}
function enableRemoteSocketLogFallback() {
remoteLogTransport = 'socket';
closeRemoteLogEventSource();
ensureSocketConsoleJoin();
}
function closeRemoteLogEventSource() {
try {
if (logSource) {
logSource.close();
logSource = null;
}
} catch { }
activeRemoteLogUrl = '';
}
function getRemoteLogTailCount(preferredTail = null) {
const explicitTail = Number(preferredTail);
if (Number.isFinite(explicitTail) && explicitTail >= 0) {
return Math.max(0, Math.trunc(explicitTail));
}
return 0;
}
function buildRemoteLogsUrl(tailCount = null) {
const params = new URLSearchParams();
params.set('tail', String(getRemoteLogTailCount(tailCount)));
return `${NODE_API_BASE}/logs?${params.toString()}`;
}
let eventSourceWasDisconnected = false;
function attachLogStreamIfRemote(options = {}) {
const { forceReconnect = false, tail = null } = options || {};
if (!REMOTE_MODE || !hasConsoleReadAccess()) {
remoteLogTransport = 'none';
closeRemoteLogEventSource();
return;
}
const url = buildRemoteLogsUrl(tail);
if (!forceReconnect && remoteLogTransport === 'eventsource' && logSource && activeRemoteLogUrl) {
return;
}
remoteLogTransport = 'eventsource';
closeRemoteLogEventSource();
eventSourceWasDisconnected = false;
const es = new EventSource(url);
logSource = es;
activeRemoteLogUrl = url;
es.addEventListener('hello', () => {
if (eventSourceWasDisconnected) {
eventSourceWasDisconnected = false;
setTimeout(() => syncConsoleHistoryGap({ reason: 'eventsource_reconnect', limit: 300 }), 400);
}
});
es.onmessage = (ev) => {
if (logSource !== es) return;
eventSourceWasDisconnected = false;
try {
const j = JSON.parse(ev.data);
if (j && typeof j.line === 'string') {
const messageTs = Number(j.ts || j.time || j.timestamp || 0) || 0;
appendLiveConsoleLine(j.line, messageTs || Date.now());
}
} catch {
appendLiveConsoleLine(ev.data || "", Date.now());
}
};
es.onerror = () => {
if (logSource !== es) return;
eventSourceWasDisconnected = true;
if (es.readyState === EventSource.CLOSED) enableRemoteSocketLogFallback();
};
}
// Use 'pagehide' instead of 'beforeunload' so the page can enter the browser
// back/forward cache (bfcache). The live console/socket are torn down here and,
// if the page is later restored from bfcache, we reload (see pageshow handler)
// so every live connection re-establishes cleanly.
window.addEventListener('pagehide', () => {
closeRemoteLogEventSource();
});
window.addEventListener('pageshow', (event) => {
// event.persisted is true only when the page is restored from bfcache.
if (event.persisted) {
window.location.reload();
}
});
let tabHiddenAt = 0;
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
tabHiddenAt = Date.now();
} else if (document.visibilityState === 'visible') {
const hiddenDuration = tabHiddenAt > 0 ? (Date.now() - tabHiddenAt) : 0;
tabHiddenAt = 0;
if (hiddenDuration >= 2000 && powerState !== POWER_STATE.STOPPED) {
setTimeout(() => syncConsoleHistoryGap({ reason: 'tab_visible', limit: 250 }), 250);
}
}
});
// adpanel:planner-auth-overlay-owner — #offlineOverlay is written by two
// families: the node-status writers (every call below routes here, from
// setNodeOnline / applyPolledPowerState / fetchPowerSnapshot / the nodeStatus
// socket handler) and the auth-failure overlays (fetchPerms' 401/403/404 and
// the planner's showPlannerSessionExpired). An ACTIVE auth overlay must not
// be clobbered by node transitions in either direction: a node-online event
// used to strip .show and hide "Not authenticated" while the user was still
// logged out, and a node flap re-shows the overlay over an auth state the
// user cannot resolve by waiting. Ownership tag follows the
// progressWheelOwner model: every auth overlay claims its tag when shown
// ('planner-auth' from the planner, 'console-auth' from fetchPerms — the
// console scene's permission fetch) and node-status transitions respect it.
// The guard blocks on the auth FAMILY (AUTH_OVERLAY_OWNERS), never a single
// tag: the two auth writers may legitimately overwrite each other's tag
// (both render the same blocking "Not authenticated"-style state), and a
// single-tag equality would let the second writer's claim unblock
// node-status while the user is still unauthenticated. The auth overlay's
// only exit is its own "Back to Dashboard" redirect — a full page
// navigation that discards this state — so there is no in-page release
// path to miss.
let offlineOverlayOwner = null;
const AUTH_OVERLAY_OWNERS = new Set(['planner-auth', 'console-auth']);
function updateOfflineState(isOffline) {
const overlay = document.getElementById('offlineOverlay');
if (!overlay) return;
if (AUTH_OVERLAY_OWNERS.has(offlineOverlayOwner)) return;
if (isOffline) overlay.classList.add('show');
else overlay.classList.remove('show');
}
function finiteUploadNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function updateUploadLimitsFromInfo(info) {
if (!info || typeof info !== 'object') return;
const maxUploadBytes = finiteUploadNumber(info.maxUploadBytes);
const maxUploadMb = finiteUploadNumber(info.maxUploadMb ?? info.max_upload_mb);
if (maxUploadBytes && maxUploadBytes > 0) {
NODE_MAX_UPLOAD_BYTES = maxUploadBytes;
NODE_MAX_UPLOAD_MB = maxUploadBytes / (1024 * 1024);
} else if (maxUploadMb && maxUploadMb > 0) {
NODE_MAX_UPLOAD_MB = maxUploadMb;
NODE_MAX_UPLOAD_BYTES = maxUploadMb * 1024 * 1024;
}
}
async function topoInfo() {
try {
const r = await fetch(`${NODE_API_BASE}/info`, { signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS) });
if (r.status === 429 || r.status === 401 || r.status === 403) {
return null;
}
if (!r.ok) throw new Error('nodes info not ok');
const j = await r.json();
REMOTE_MODE = !!j.remote; NODE_ID = j.nodeId || null;
updateUploadLimitsFromInfo(j);
return j;
} catch (e) {
REMOTE_MODE = false; NODE_ID = null;
return null;
}
}
topoInfoPromise = topoInfo();
async function ensureUploadLimitsReady() {
if (topoInfoPromise) {
await topoInfoPromise.catch(() => null);
}
if (!NODE_MAX_UPLOAD_BYTES) {
await topoInfo().catch(() => null);
}
}
function validateUploadCandidate(file) {
const size = Math.max(0, finiteUploadNumber(file?.size) || 0);
const name = String(file?.name || 'file');
if (NODE_MAX_UPLOAD_BYTES > 0 && size > NODE_MAX_UPLOAD_BYTES) {
throw new Error(`"${name}" is ${formatBytes(size)}, above this node's max single-file upload size of ${formatBytes(NODE_MAX_UPLOAD_BYTES)}.`);
}
}
async function apiExplore(path = "") {
const url = REMOTE_MODE
? `${NODE_API_BASE}/entries?path=${encodeURIComponent(path)}`
: `/api/servers/${encodeURIComponent(bot)}/files/list?path=${encodeURIComponent(path)}`;
const r = await fetch(url);
if (!r.ok) throw new Error('explore failed');
return await r.json();
}
// Binary files cannot be represented in the text editor: opening one shows
// U+FFFD-mangled text that a save would write back over the original, so
// the open is refused and the existing download flow is offered (mirrors
// the over-10 MB confirm-and-download pattern).
function refuseBinaryEditorOpen(relPath) {
const name = String(relPath || '').split('/').pop() || 'file';
// adpanel:planner-confirm-title — display-only flatten; the download
// below keeps using the raw relPath.
const confirmName = dialogText(name);
if (confirm(`"${confirmName}" is a binary file and cannot be opened in the text editor.\n\nDownload instead?`)) {
apiDownloadFile(String(relPath || ''));
}
}
async function apiReadFile(relPath, request) {
if (!REMOTE_MODE) {
pendingEditorRead = { ...request, path: relPath };
socket.emit("readFile", { bot, path: relPath });
return null;
}
// Reads go through the panel's /files/read (not the nodes relay): it
// fetches the daemon's base64 encoding and validates UTF-8 strictly, so a
// binary file arrives as { binary: true } instead of lossy text.
const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/files/read?path=${encodeURIComponent(relPath)}`);
if (!r.ok) throw new Error('read file failed');
const j = await r.json();
if (request.generation !== editorOpenGeneration) return null;
if (j && j.binary) {
refuseBinaryEditorOpen(relPath);
return null;
}
return j && typeof j.content === 'string' ? j.content : '';
}
// Local-mode file operations go over Socket.IO and only report their real
// outcome through the server ack; without awaiting it a denied or failed
// save would look successful. Node-side writes/deletes can take up to 120s
// server-side, so the ack timeout has to exceed that. The editor's optional
// base hash is checked in the same daemon write, not a separate request.
const FS_SOCKET_ACK_TIMEOUT_MS = 125000;
function socketFsRequest(event, payload, failLabel) {
return new Promise((resolve, reject) => {
const fail = (msg) => reject(new Error(msg || `${failLabel} failed`));
if (!socket || typeof socket.timeout !== "function") {
return fail("Not connected to the panel server. Check your connection and try again.");
}
try {
socket.timeout(FS_SOCKET_ACK_TIMEOUT_MS).emit(event, payload, (err, res) => {
if (err) return fail(`${failLabel} timed out. Refresh the file list to check whether it completed.`);
if (res && res.ok) return resolve(res.msg || true);
// adpanel:editor-save-occ — carry the server's machine-readable
// code (file_changed_on_disk on a refused stale write) on the
// rejected Error so the editor can react to specific failures
// instead of string-matching the message.
const failure = new Error(res && res.msg ? res.msg : `${failLabel} failed`);
if (res && typeof res.code === "string" && res.code) failure.code = res.code;
reject(failure);
});
} catch (e) {
fail(`${failLabel} failed: ` + (e && e.message ? e.message : e));
}
});
}
// Socket.IO frames are capped by maxHttpBufferSize (1e6 bytes in index.js):
// a bigger emit kills the connection and the save hangs until the 125s ack
// timeout. Serialized saves above this frame-safe threshold go through the
// REST write route instead — its scoped 10 MB parser (FILE_WRITE_JSON_LIMIT)
// carries exactly the frames the socket transport cannot.
const SOCKET_FS_FRAME_LIMIT_BYTES = 900 * 1024;
function socketFsPayloadTooLarge(payload) {
return new TextEncoder().encode(JSON.stringify(payload)).length > SOCKET_FS_FRAME_LIMIT_BYTES;
}
async function apiWriteFile(relPath, content, expectedSha256) {
if (!REMOTE_MODE) {
const payload = { bot, path: relPath, content };
// adpanel:editor-save-occ — opt-in optimistic concurrency: ONLY the
// editor's save (performSave) passes the open-time base hash, and only
// when one exists (crypto.subtle unavailable → "" → legacy write).
// Every other caller omits it and keeps the legacy behavior.
if (expectedSha256) payload.expectedSha256 = expectedSha256;
if (!socketFsPayloadTooLarge(payload)) {
// Issue 4: the socket handler verifies the same session-bound (non
// one-time) fileWrite token as the REST PUT /files/write route and the
// remote relay below. ensureServerActionToken serves it from the
// 4-minute cache, so an editor save costs no extra round-trip.
const actionToken = await ensureServerActionToken('fileWrite');
return socketFsRequest("writeFile", { ...payload, actionToken }, "Save");
}
// Oversized save: the socket cannot carry it, so save through the same
// PUT /files/write route the AI tools use — it verifies the same
// fileWrite pair and enforces the same perms/mode split, suspension
// refusal and 413 limit messaging as the socket handler.
const r = await writeServerFileWithActionToken(bot, relPath, content, expectedSha256);
if (!r.ok) {
const j = await r.json().catch(() => null);
if (r.status === 507) throw new Error((j && j.message) || 'Disk space limit exceeded. Free up space or increase the storage limit.');
if (r.status === 413) throw new Error((j && (j.message || j.error)) || 'File exceeds the 10 MB editor limit — upload the file instead.');
// adpanel:editor-save-occ — a 409 from this route is unambiguously the
// staleness guard (the daemon's own 409 maps to a 403 in the write
// relay): tag the error so performSave can offer the reload confirm.
if (r.status === 409 && j && j.error === EDITOR_SAVE_CONFLICT_CODE) {
const conflict = new Error((j && (j.message || j.error)) || 'The file changed on disk since it was opened.');
conflict.code = EDITOR_SAVE_CONFLICT_CODE;
throw conflict;
}
throw new Error((j && (j.error || j.message)) || 'write file failed');
}
return true;
}
// Issue 4: the node relay verifies the same "PUT /api/servers/:name/files/write"
// pair (fileWrite) — attach it here too.
// adpanel:editor-save-occ — the remote relay (nodes.js POST /file) runs
// the SAME shared guard as the panel routes, so the base hash rides along
// here too: only when one exists (crypto.subtle unavailable → "" → legacy
// write, matching the server's opt-in gate). The hash base is the exact
// bytes this editor loaded — the REMOTE open read goes through the panel's
// /files/read (apiReadFile above), whose strict base64+UTF-8 decode is the
// same decode the guard's verify read re-runs, so an unchanged file
// hashes identically on both sides.
const savePayload = { path: relPath, content };
if (expectedSha256) savePayload.expectedSha256 = expectedSha256;
const r = await fetchWithServerActionToken(`${NODE_API_BASE}/file`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(savePayload)
}, 'fileWrite');
if (r.status === 507) {
const j = await r.json().catch(() => null);
throw new Error((j && j.message) || 'Disk space limit exceeded. Free up space or increase the storage limit.');
}
if (r.status === 413) {
const j = await r.json().catch(() => null);
throw new Error((j && (j.message || j.error)) || 'File exceeds the 10 MB editor limit — upload the file instead.');
}
if (!r.ok) {
const j = await r.json().catch(() => null);
// adpanel:editor-save-occ — a 409 from the relay is unambiguously the
// staleness guard (the write never happened): tag the error with the
// machine-readable code so performSave offers the same reload confirm
// it does for the local-mode paths.
if (r.status === 409 && j && j.error === EDITOR_SAVE_CONFLICT_CODE) {
const conflict = new Error((j && (j.message || j.error)) || 'The file changed on disk since it was opened.');
conflict.code = EDITOR_SAVE_CONFLICT_CODE;
throw conflict;
}
throw new Error((j && (j.error || j.message)) || 'write file failed');
}
return true;
}
async function apiDelete(relPath, isDir) {
if (!REMOTE_MODE) {
// Issue 4: one-time delete token, minted fresh per call — the socket
// handler verifies the same "DELETE /api/servers/:name/files/delete"
// pair as the REST delete route. Bulk delete re-enters here per entry
// on purpose: each entry consumes its own one-time token.
const actionToken = await ensureServerActionToken('fileDelete', { refresh: true });
return socketFsRequest("deleteFile", { bot, path: relPath, isDir, actionToken }, "Delete");
}
// Remote relay verifies the same one-time pair; refreshBefore mints a
// fresh token per call (fetchWithServerActionToken also retries once on
// ACTION_TOKEN_INVALID).
const r = await fetchWithServerActionToken(`${NODE_API_BASE}/delete`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: relPath, isDir: !!isDir })
}, 'fileDelete', { refreshBefore: true });
if (!r.ok) {
const j = await r.json().catch(() => null);
throw new Error((j && (j.error || j.message)) || 'delete failed');
}
return true;
}
async function apiRename(oldPath, newName) {
const url = REMOTE_MODE ? `${NODE_API_BASE}/rename` : '/rename';
const payload = REMOTE_MODE
? { path: oldPath, newName }
: { bot, oldPath, newName };
// Issue 4: both rename paths verify the same one-time fileRename pair the
// modern POST /files/rename route checks; refreshBefore mints fresh per call.
const r = await fetchWithServerActionToken(url, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}, 'fileRename', { refreshBefore: true });
if (!r.ok) {
const j = await r.json().catch(() => null);
const text = j && (j.error || j.message) ? (j.error || j.message) : await r.text().catch(() => '');
throw new Error(text || r.statusText);
}
return true;
}
async function apiExtract(relPath) {
const url = REMOTE_MODE ? `${NODE_API_BASE}/extract` : '/extract';
const payload = REMOTE_MODE ? { path: relPath } : { bot, path: relPath };
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
};
// Issue 4: the token is attached in BOTH modes now — the node relay
// verifies the same "POST /extract" pair the panel route always checked.
const r = await fetchWithServerActionToken(url, requestOptions, 'fileExtract');
const j = await r.json().catch(() => ({}));
if (r.status === 507 || (j && j.error === 'disk_limit_exceeded')) {
throw new Error(j.message || 'This server has exceeded its disk space limit. Delete files to free space before extracting.');
}
if (!r.ok || !j.ok) throw new Error(j?.message || j?.error || 'extract failed');
return j;
}
async function apiArchive(paths, destDir) {
const url = REMOTE_MODE ? `${NODE_API_BASE}/archive` : '/archive';
const payload = REMOTE_MODE ? { paths, destDir } : { bot, paths, destDir };
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
};
// Issue 4: the token is attached in BOTH modes now — the node relay
// verifies the same "POST /archive" pair the panel route always checked.
const r = await fetchWithServerActionToken(url, requestOptions, 'fileArchive');
const j = await r.json().catch(() => ({}));
if (r.status === 507 || (j && j.error === 'disk_limit_exceeded')) {
throw new Error(j.message || 'This server has exceeded its disk space limit. Delete files to free space before archiving.');
}
if (!r.ok || !j.ok) throw new Error((j && j.error) ? j.error : 'archive failed');
return j;
}
function apiDownloadFile(relPath) {
const url = REMOTE_MODE
? `${NODE_API_BASE}/download?path=${encodeURIComponent(relPath)}`
: `/api/servers/${encodeURIComponent(bot)}/files/download?path=${encodeURIComponent(relPath)}`;
const a = document.createElement('a');
a.href = url;
a.download = relPath.split('/').pop() || 'download';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
setTimeout(() => a.remove(), 500);
}
// Aligned with the daemon's editor read cap (maxEditorRead = 10 << 20 in
// main.go handleFSRead): both refuse with the same "size > limit" predicate,
// so nothing the daemon can serve is refused here and vice versa.
const FILE_SIZE_EDITOR_LIMIT = 10 * 1024 * 1024;
const EXPLORER_ARCHIVE_EXTENSION = /\.(?:zip|tar(?:\.(?:gz|bz2|xz))?|tgz|tbz2|txz|rar|7z)$/i;
const explorerEntryCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
function normalizeExplorerEntry(rawEntry) {
const rawMtime = Number(rawEntry?.mtime);
return {
name: String(rawEntry?.name ?? ''),
isDir: !!(rawEntry?.isDir || rawEntry?.type === "dir"),
size: rawEntry?.size,
mtime: Number.isFinite(rawMtime) && rawMtime > 0 ? rawMtime : null
};
}
// Format a Unix-seconds timestamp as "DD/MM/YYYY HH:MM" (24h clock), e.g.
// "20/06/2026 20:34". Returns "" when no valid timestamp is available.
function formatEntryDate(mtimeSeconds) {
if (!Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) return "";
const d = new Date(mtimeSeconds * 1000);
if (isNaN(d.getTime())) return "";
const pad = (n) => String(n).padStart(2, "0");
const year = d.getFullYear();
const month = pad(d.getMonth() + 1);
const day = pad(d.getDate());
let hours = d.getHours();
const minutes = pad(d.getMinutes());
const ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
hours = hours ? hours : 12;
return `${year}/${month}/${day} ${hours}:${minutes} ${ampm}`;
}
function compareExplorerEntries(a, b) {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
return explorerEntryCollator.compare(a.name, b.name);
}
let currentUserPreferences = {};
const CLEAR_CONSOLE_NO_ASK_STORAGE_KEY = `adpanel:clear-console-no-ask:${String(currentUser?.email || 'browser').toLowerCase()}`;
const FILE_BACKUPS_STORAGE_KEY = `adpanel:file-backups:${bot}`;
const fileBackupDrafts = new Map();
function loadClearConsoleNoAskFromStorage() {
try {
const raw = localStorage.getItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY);
return raw === '1' || raw === 'true';
} catch {
return false;
}
}
function saveClearConsoleNoAskToStorage(value) {
try {
if (value) localStorage.setItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY, '1');
else localStorage.removeItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY);
} catch { }
}
function mergeCurrentUserPreferences(preferences) {
const incoming = preferences && typeof preferences === 'object' ? preferences : {};
currentUserPreferences = { ...currentUserPreferences, ...incoming };
if (loadClearConsoleNoAskFromStorage()) {
currentUserPreferences.clear_console_no_ask = true;
}
}
mergeCurrentUserPreferences({});
function normalizeFileBackupPath(filePath) {
return String(filePath || '').replace(/\\/g, '/').trim();
}
function loadFileBackupDraftsFromStorage() {
fileBackupDrafts.clear();
try {
const raw = localStorage.getItem(FILE_BACKUPS_STORAGE_KEY);
if (!raw) return fileBackupDrafts;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return fileBackupDrafts;
for (const [path, value] of Object.entries(parsed)) {
const cleanPath = normalizeFileBackupPath(path);
if (!cleanPath) continue;
if (typeof value === 'string') {
fileBackupDrafts.set(cleanPath, value);
continue;
}
if (value && typeof value === 'object' && typeof value.content === 'string') {
fileBackupDrafts.set(cleanPath, value.content);
}
}
} catch (err) {
console.warn('[FileBackups] Failed to load draft backups from storage:', err);
try { localStorage.removeItem(FILE_BACKUPS_STORAGE_KEY); } catch { }
}
return fileBackupDrafts;
}
async function loadMeIntoProfileEmail() {
if (!profileEmailEl) profileEmailEl = document.getElementById('profileEmail');
if (currentUser && typeof currentUser === 'object') {
const email = String(currentUser.email || '').trim();
if (email && profileEmailEl) profileEmailEl.textContent = email;
if (currentUser.preferences && typeof currentUser.preferences === 'object') {
mergeCurrentUserPreferences(currentUser.preferences);
}
if (email) return;
}
try {
const res = await fetch('/api/me', { credentials: 'include' });
if (!res.ok) return;
const data = await res.json().catch(() => null);
if (data && data.user) {
const email = data.user.email;
if (email && profileEmailEl) profileEmailEl.textContent = email;
if (data.user.preferences) mergeCurrentUserPreferences(data.user.preferences);
}
} catch (err) {
console.warn('Fetch error in /api/me:', err);
}
}
// An upload stall produces no progress events at all, so the upload uses an
// INACTIVITY watchdog (reset on every progress tick and on send) instead of
// xhr.timeout, which is a total-time cap and would kill legitimate large
// uploads on slow links. Trade-off: a server that finalizes an already
// fully-sent body silently for longer than this window (no response bytes)
// is treated as stalled.
const UPLOAD_STALL_TIMEOUT_MS = 45000;
// Upload-batch cancel state. The sequential queue keeps one XHR in flight at
// a time, so a single module-level abort target suffices; the flag is also
// checked between files so a cancel landing in the gap between two files
// still stops the remaining ones.
let uploadBatchActive = false;
let uploadCancelRequested = false;
let uploadAbortCurrent = null;
function requestUploadCancel() {
if (!uploadBatchActive) return;
uploadCancelRequested = true;
const abort = uploadAbortCurrent;
if (abort) { try { abort(); } catch (_) { } }
}
function apiUploadWithProgress(file, currentPath, onProgress, baseMsg) {
return new Promise((resolve, reject) => {
// `settled` guards double-handling: onload/onerror/onabort and the stall
// watchdog can race, but the promise must settle exactly once, and the
// watchdog timer must be cleared on every settle path (no leaked timers).
let settled = false, stallTimer = null;
const clearStallWatchdog = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null; } };
const fail = (err) => { if (settled) return; settled = true; clearStallWatchdog(); uploadAbortCurrent = null; reject(err); };
const succeed = () => { if (settled) return; settled = true; clearStallWatchdog(); uploadAbortCurrent = null; resolve(); };
const cancelError = () => { const e = new Error('Upload canceled'); e.uploadCanceled = true; return e; };
const stallError = () => { const e = new Error(`Upload stalled: no progress for ${UPLOAD_STALL_TIMEOUT_MS / 1000}s. The connection may have dropped.`); e.uploadStalled = true; return e; };
(async () => {
try {
await ensureUploadLimitsReady();
validateUploadCandidate(file);
const fd = new FormData();
if (!REMOTE_MODE) { fd.append('bot', bot); }
fd.append('path', currentPath || '');
fd.append('filename', file.name);
fd.append('file', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', REMOTE_MODE ? `${NODE_API_BASE}/upload` : '/upload');
// Both upload routes verify the same minted token (action
// "POST /upload", resource {serverName}): local /upload and the
// remote node-proxy /api/nodes/server/:name/upload, so attach it in
// remote mode too.
const uploadToken = await ensureServerActionToken('fileUpload', { refresh: true });
if (uploadToken) {
xhr.setRequestHeader('x-action-token', uploadToken);
}
// Inactivity watchdog: reset on send and on every progress tick; if
// no events arrive within the window the connection is presumed
// dead. The stall error is recorded BEFORE abort so onabort cannot
// mask it, then abort actually closes the socket.
const onStall = () => {
stallTimer = null;
if (settled) return;
fail(stallError());
try { xhr.abort(); } catch (_) { }
};
const resetStallWatchdog = () => {
if (stallTimer) clearTimeout(stallTimer);
stallTimer = setTimeout(onStall, UPLOAD_STALL_TIMEOUT_MS);
};
xhr.upload.onprogress = (e) => { resetStallWatchdog(); if (e.lengthComputable) { const pct = Math.round((e.loaded / e.total) * 100); onProgress(pct, `${baseMsg} (${pct}%)`); } else onProgress(6, `${baseMsg}...`); };
// Response-side bytes count as activity too (covers the server's
// finalize window after the request body is fully sent).
xhr.onprogress = resetStallWatchdog;
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try { const j = JSON.parse(xhr.responseText || "{}"); onProgress(100, j && j.msg ? j.msg : "Finalizing..."); } catch { }
succeed();
} else if (xhr.status === 413) {
try {
const j = JSON.parse(xhr.responseText || "{}");
fail(new Error(j.message || `File too large. Maximum upload size for this node is ${j.limit_mb ? j.limit_mb + ' MB' : 'exceeded'}.`));
return;
} catch { }
fail(new Error('File too large for this node. Increase the upload limit in node settings.'));
} else if (xhr.status === 507) {
try {
const j = JSON.parse(xhr.responseText || "{}");
if (j.error === 'disk_limit_exceeded') {
fail(new Error(j.message || 'Disk space limit exceeded. Free up space or increase the storage limit.'));
return;
}
} catch { }
fail(new Error('Disk space limit exceeded'));
} else {
if (xhr.status === 409 || xhr.status === 503) {
try {
const body = JSON.parse(xhr.responseText || '{}');
if (typeof body?.message === 'string' && body.message) {
fail(new Error(body.message));
return;
}
} catch { }
}
fail(new Error(xhr.responseText || xhr.statusText || ('status ' + xhr.status)));
}
};
xhr.onerror = () => fail(new Error('Network error'));
// Abort is a distinct outcome (user cancel or watchdog): different
// message than the network-error text, but it still releases the
// queue slot via fail()'s cleanup.
xhr.onabort = () => fail(cancelError());
// A cancel requested while the limits/token awaits above were in
// flight must not send the request at all.
if (uploadCancelRequested) { fail(cancelError()); return; }
resetStallWatchdog();
uploadAbortCurrent = () => xhr.abort();
xhr.send(fd);
} catch (error) {
fail(error);
}
})();
});
}
async function apiCreate(type, name, currentPath) {
const url = REMOTE_MODE ? `${NODE_API_BASE}/create` : '/create';
const payload = REMOTE_MODE
? { type, name, path: currentPath || '' }
: { bot, type, name, path: currentPath || '' };
// Issue 4: the local legacy POST /create verifies the same session-bound
// fileMkdir pair as the modern mkdir route (identical files_create gate
// and {serverName} binding). The remote /create relay verifies the same
// pair via requireNodeFileActionToken, so one mint covers both.
const r = await fetchWithServerActionToken(url, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}, 'fileMkdir');
if (r.status === 507) {
const j = await r.json().catch(() => null);
throw new Error((j && j.message) || 'Disk space limit exceeded. Free up space or increase the storage limit.');
}
if (!r.ok) {
const j = await r.json().catch(() => null);
const text = j && (j.error || j.message) ? (j.error || j.message) : await r.text().catch(() => '');
throw new Error(text || r.statusText);
}
return true;
}
function normalizeServerPowerAction(value) {
const action = String(value || '').trim().toLowerCase();
if (!action) return '';
if (action === 'run') return 'start';
if (action === 'shutdown') return 'stop';
return action;
}
function createServerActionError(code, message, extra = {}) {
const err = new Error(message || 'Server action failed.');
err.code = code || 'server_action_failed';
Object.assign(err, extra);
return err;
}
function buildServerActionError(action, serverName, payload = null, status = null) {
const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot) || 'server';
const info = payload && typeof payload === 'object' ? payload : {};
const errorCode = String(info.error || '').trim().toLowerCase();
const detail = String(info.detail || info.message || '').trim();
if (errorCode === 'permission denied') {
return createServerActionError('permission_denied', `You do not have permission to ${action} ${target}.`, {
action,
serverName: target,
permission: info.permission || null,
status
});
}
if (errorCode === 'no access to server') {
return createServerActionError('access_denied', `You do not have access to ${target}.`, {
action,
serverName: target,
status
});
}
if (errorCode === 'server not found') {
return createServerActionError('server_not_found', `${target} was not found.`, {
action,
serverName: target,
status
});
}
if (errorCode === 'not_remote') {
return createServerActionError('not_remote', `${target} is not attached to a node.`, {
action,
serverName: target,
status
});
}
if (errorCode === 'minecraft_eula_required') {
return createServerActionError('minecraft_eula_required', `Minecraft EULA acceptance is required before ${target} can start.`, {
action,
serverName: target,
status
});
}
if (status === 403) {
return createServerActionError('permission_denied', `You do not have permission to ${action} ${target}.`, {
action,
serverName: target,
permission: info.permission || null,
status
});
}
return createServerActionError(errorCode || 'server_action_failed', detail || info.error || `Request failed${status ? ` (HTTP ${status})` : '.'}`, {
action,
serverName: target,
status
});
}
function socketRequest(eventName, payload, timeoutMs = 12000) {
return new Promise((resolve, reject) => {
if (!socket?.connected || typeof socket.timeout !== 'function') {
reject(createServerActionError('socket_unavailable', 'Realtime connection unavailable.'));
return;
}
try {
socket.timeout(timeoutMs).emit(eventName, payload, (err, response) => {
if (err) {
reject(createServerActionError('timeout', 'No reply from the panel.'));
return;
}
resolve(response || {});
});
} catch (err) {
reject(err instanceof Error ? err : createServerActionError('socket_emit_failed', String(err || 'Socket request failed.')));
}
});
}
async function requestSocketServerAction(serverName, action, hostPort = null) {
const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot);
const normalizedAction = normalizeServerPowerAction(action);
if (!target) throw createServerActionError('missing_server', 'No server selected.');
if (!normalizedAction) throw createServerActionError('invalid_action', 'Invalid server action.');
let ack;
try {
ack = await socketRequest('action', {
bot: target,
cmd: normalizedAction === 'start' ? 'run' : normalizedAction,
...(hostPort != null ? { port: hostPort } : {})
}, 25_000);
} catch (err) {
if (err?.code !== 'timeout') throw err;
throw createServerActionError('server_action_result_unconfirmed', 'The panel did not confirm the power action. Check the server state before retrying.', {
action: normalizedAction, serverName: target,
});
}
if (ack?.ok !== true) {
if (ack && (ack.code === 'minecraft_eula_required' || ack.error === 'minecraft_eula_required')) {
maybeShowEulaPopup();
}
throw buildServerActionError(normalizedAction, target, ack);
}
return { confirmed: true, via: 'socket' };
}
async function requestHttpServerAction(serverName, action, hostPort = null) {
const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot);
const normalizedAction = normalizeServerPowerAction(action);
if (!target) throw createServerActionError('missing_server', 'No server selected.');
if (!normalizedAction) throw createServerActionError('invalid_action', 'Invalid server action.');
const response = await fetch(`/api/nodes/server/${encodeURIComponent(target)}/action`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
cmd: normalizedAction,
...(hostPort != null ? { hostPort } : {})
}),
signal: AbortSignal.timeout(normalizedAction === 'start' ? 250_000 : 25_000)
}).catch(() => null);
const data = response ? await response.json().catch(() => null) : null;
if (!response || (response.ok && !data)) {
throw createServerActionError('server_action_result_unconfirmed', 'The panel did not confirm the power action. Check the server state before retrying.', {
action: normalizedAction, serverName: target, status: response?.status ?? null,
});
}
if (data?.code === 'minecraft_eula_required' || data?.error === 'minecraft_eula_required') {
maybeShowEulaPopup();
throw buildServerActionError(normalizedAction, target, data, response.status);
}
if (response.status === 400 && data?.error === 'not_remote') {
return requestSocketServerAction(target, normalizedAction, hostPort);
}
if (!response.ok || data?.ok === false) {
throw buildServerActionError(normalizedAction, target, data, response.status);
}
return { confirmed: true, via: 'http' };
}
async function apiAction(data) {
const target = normalizeAiServerNameCandidate(data && data.bot) || normalizeAiServerNameCandidate(bot);
const action = normalizeServerPowerAction(data && data.cmd);
const rawHostPort = data && (data.hostPort ?? data.port);
const hostPort = rawHostPort == null || rawHostPort === '' ? null : Number(rawHostPort);
if (REMOTE_MODE) {
await requestHttpServerAction(target, action, Number.isFinite(hostPort) ? hostPort : null);
return true;
}
await requestSocketServerAction(target, action, Number.isFinite(hostPort) ? hostPort : null);
return true;
}
async function apiCommand(command, sentAt = Date.now(), requestId = "") {
const trimmed = String(command || '').trim();
if (!trimmed) throw new Error('empty_command');
const commandRequestId = String(requestId || '').trim();
const commandPayload = commandRequestId
? { bot, command: trimmed, requestId: commandRequestId }
: { bot, command: trimmed };
if (!REMOTE_MODE || (socket && socket.connected)) {
const ack = await socketRequest('command', commandPayload, 25_000);
if (ack?.ok !== true) {
const msg = String((ack && (ack.error || ack.detail)) || 'command_failed');
throw new Error(msg);
}
scheduleConsoleHistoryResync(trimmed, sentAt);
return true;
}
const r = await fetch(`${NODE_API_BASE}/command`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(commandRequestId ? { command: trimmed, requestId: commandRequestId } : { command: trimmed }),
signal: AbortSignal.timeout(25_000)
});
const payload = await r.json().catch(() => null);
if (!r.ok || payload?.ok !== true) {
const message = String((payload && (payload.detail || payload.error)) || 'Command delivery was not confirmed');
throw new Error(message);
}
scheduleConsoleHistoryResync(trimmed, sentAt);
return true;
}
let IS_ADMIN = false;
let AGENT_ACCESS = false;
let SERVER_ACTION_TOKENS = {};
let serverActionTokensLoadedAt = 0;
const SERVER_ACTION_TOKEN_REFRESH_MS = 4 * 60 * 1000;
const INVALID_ACTION_TOKEN_ERROR = 'invalid or missing action token';
const ONE_TIME_SERVER_ACTION_TOKENS = new Set(['fileDelete', 'fileRename', 'changeTemplate', 'applyVersion', 'reinstallServer', 'backupRestore', 'backupDelete']);
let PERMS = {
files_read: false, files_delete: false, files_rename: false, files_archive: false, console_read: false, console_write: false,
server_stop: false, server_start: false, files_upload: false, files_create: false,
activity_logs: false, backups_view: false, backups_create: false, backups_delete: false,
scheduler_access: false, scheduler_create: false, scheduler_delete: false, store_access: false,
server_reinstall: false, planner_access: false, agent_settings: false
};
function hasPerm(k) { return IS_ADMIN || !!PERMS[k]; }
window.hasPerm = hasPerm;
function hasConsoleReadAccess() { return hasPerm('console_read'); }
function hasAgentAccess() { return document.body.dataset.agentEnabled === 'true' && (IS_ADMIN || AGENT_ACCESS); }
function getServerActionToken(tokenKey) {
return String(SERVER_ACTION_TOKENS?.[tokenKey] || '').trim();
}
function shouldRefreshServerActionToken(tokenKey) {
if (!tokenKey) return false;
if (ONE_TIME_SERVER_ACTION_TOKENS.has(tokenKey)) return true;
if (!serverActionTokensLoadedAt) return true;
return (Date.now() - serverActionTokensLoadedAt) >= SERVER_ACTION_TOKEN_REFRESH_MS;
}
async function readJsonResponseSafe(response) {
try {
return await response.json();
} catch {
return {};
}
}
function isInvalidActionTokenErrorPayload(payload) {
return String(payload?.error || '').trim().toLowerCase() === INVALID_ACTION_TOKEN_ERROR;
}
async function ensureServerActionToken(tokenKey, opts = {}) {
const { refresh = false } = opts;
if (!tokenKey) return '';
const existingToken = getServerActionToken(tokenKey);
if (!refresh && existingToken && !shouldRefreshServerActionToken(tokenKey)) {
return existingToken;
}
const refreshed = await fetchPerms({ preserveCurrentState: true });
if (refreshed && refreshed.actionTokens && typeof refreshed.actionTokens === 'object') {
return String(refreshed.actionTokens[tokenKey] || '').trim();
}
return getServerActionToken(tokenKey);
}
async function fetchWithServerActionToken(url, options = {}, tokenKey, opts = {}) {
// adpanel:scheduler-fetch-bound — the inner fetch stays unbounded unless
// the caller opts in with opts.timeoutMs: several token-gated ops here
// (extract, archive, backup create/restore, reinstall) answer only after
// a potentially minutes-long daemon job, so no global cap may exist. The
// bound applies PER ATTEMPT, so the 403-token retry below gets a fresh
// window.
const { refreshBefore = false, retryOnInvalidToken = true, timeoutMs } = opts;
const runRequest = async (refreshToken) => {
const headers = new Headers(options.headers || {});
const token = await ensureServerActionToken(tokenKey, { refresh: refreshToken });
if (token) headers.set('x-action-token', token);
return timeoutMs
? fetchWithTimeout(url, { ...options, headers }, timeoutMs)
: fetch(url, { ...options, headers });
};
let response = await runRequest(refreshBefore);
if (retryOnInvalidToken && response.status === 403) {
const errData = await readJsonResponseSafe(response.clone());
if (isInvalidActionTokenErrorPayload(errData)) {
response = await runRequest(true);
}
}
if (response.ok && ONE_TIME_SERVER_ACTION_TOKENS.has(tokenKey)) {
delete SERVER_ACTION_TOKENS[tokenKey];
}
return response;
}
async function writeServerFileWithActionToken(serverName, relPath, content, expectedSha256) {
// adpanel:editor-save-occ — the optional 4th arg is the editor's open-time
// base hash, passed ONLY by the oversized editor-save fallback in
// apiWriteFile. The AI write and the backup-restore callers never pass it
// → their wire body is unchanged (the route's guard is opt-in).
const body = { path: relPath, content };
if (expectedSha256) body.expectedSha256 = expectedSha256;
return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/write`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}, 'fileWrite');
}
async function createServerFolderWithActionToken(serverName, relPath) {
return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/mkdir`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: relPath })
}, 'fileMkdir');
}
async function deleteServerPathWithActionToken(serverName, relPath, isDir = false) {
return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/delete`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: relPath, isDir: isDir ? '1' : '0' })
}, 'fileDelete', { refreshBefore: true });
}
async function changeServerTemplateWithActionToken(serverName, templateId) {
return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/template`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template: templateId })
}, 'changeTemplate', { refreshBefore: true });
}
async function applyServerVersionWithActionToken(serverName, payload) {
return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/versions/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload || {})
}, 'applyVersion', { refreshBefore: true });
}
const consoleEl = document.getElementById("console");
const consoleLoadingSpinner = document.getElementById('consoleLoadingSpinner');
const consoleInstallingOverlay = document.getElementById('consoleInstallingOverlay');
const consoleInstallingFill = document.getElementById('consoleInstallingFill');
let consoleContentEl = document.getElementById('consoleContent');
if (!consoleContentEl && consoleEl) {
consoleContentEl = document.createElement('div');
consoleContentEl.id = 'consoleContent';
consoleEl.appendChild(consoleContentEl);
}
let isInstallingActive = false;
let installProgress = 0;
let installProgressTimer = null;
let installStartTime = 0;
let installStage = 'queued';
function setInstallingProgress(pct) {
installProgress = Math.max(0, Math.min(100, pct));
if (consoleInstallingFill) {
consoleInstallingFill.style.width = `${installProgress}%`;
}
}
function startInstallingOverlay(initialStage = 'queued', opts = {}) {
if (isInstallingActive) return;
isInstallingActive = true;
installStage = initialStage || 'queued';
const now = Date.now();
const createdTs = Number(opts && opts.createdAt) || 0;
if (createdTs > 0 && (now - createdTs) < 300000) {
installStartTime = createdTs;
} else {
installStartTime = now;
}
document.body.classList.add('server-is-installing');
window.__ADPANEL_IS_INSTALLING__ = true;
document.querySelectorAll('.modal-overlay.show, .activity-modal.show, .scheduler-modal.show, .planner-modal.show, .ai-help-modal.show').forEach(m => {
m.classList.remove('show');
// adpanel:install-modal-teardown — showModalElement leaves inline
// display:flex + aria-hidden="false" behind; stripping only .show left
// an invisible hit-testable full-screen layer (popup mode) and stale
// aria state, so the teardown clears both. aria is only corrected on
// elements that already carry the attribute — openers that manage it
// set it false again on reopen.
m.style.removeProperty('display');
if (m.hasAttribute('aria-hidden')) m.setAttribute('aria-hidden', 'true');
});
if (consoleInstallingOverlay) {
consoleInstallingOverlay.classList.add('active');
}
if (consoleLoadingSpinner) {
consoleLoadingSpinner.classList.add('hidden');
}
if (consoleContentEl) {
consoleContentEl.classList.remove('console-revealed');
}
// Estimate initial progress from elapsed time
const initialElapsed = Math.max(0, (now - installStartTime) / 1000);
let startPct = 8;
if (initialElapsed > 0) {
if (initialElapsed < 3) startPct = 8 + (initialElapsed / 3) * 12;
else if (initialElapsed < 15) startPct = 20 + ((initialElapsed - 3) / 12) * 35;
else if (initialElapsed < 35) startPct = 55 + ((initialElapsed - 15) / 20) * 25;
else if (initialElapsed < 60) startPct = 80 + ((initialElapsed - 35) / 25) * 12;
else startPct = Math.min(94, 92 + (1 - Math.exp(-(initialElapsed - 60) / 40)) * 4);
}
setInstallingProgress(startPct);
if (installProgressTimer) clearInterval(installProgressTimer);
installProgressTimer = setInterval(() => {
if (!isInstallingActive) return;
const elapsedSec = (Date.now() - installStartTime) / 1000;
let target = installProgress;
if (elapsedSec < 3) {
target = 8 + (elapsedSec / 3) * 12; // 8% -> 20%
} else if (elapsedSec < 15) {
target = 20 + ((elapsedSec - 3) / 12) * 35; // 20% -> 55%
} else if (elapsedSec < 35) {
target = 55 + ((elapsedSec - 15) / 20) * 25; // 55% -> 80%
} else if (elapsedSec < 60) {
target = 80 + ((elapsedSec - 35) / 25) * 12; // 80% -> 92%
} else {
target = Math.min(96, 92 + (1 - Math.exp(-(elapsedSec - 60) / 40)) * 4);
}
const step = Math.max(0.3, (target - installProgress) * 0.25);
setInstallingProgress(Math.min(target, installProgress + step));
}, 200);
updatePowerControlsInteractivity();
}
function finishInstallingOverlay(callback) {
if (!isInstallingActive && !consoleInstallingOverlay?.classList.contains('active')) {
if (typeof callback === 'function') callback();
return;
}
isInstallingActive = false;
if (installProgressTimer) {
clearInterval(installProgressTimer);
installProgressTimer = null;
}
setInstallingProgress(100);
setTimeout(() => {
if (consoleInstallingOverlay) {
consoleInstallingOverlay.classList.remove('active');
}
setTimeout(() => {
setInstallingProgress(0);
document.body.classList.remove('server-is-installing');
window.__ADPANEL_IS_INSTALLING__ = false;
resetConsoleBuffer();
revealConsoleContent();
fetchPerms({ preserveCurrentState: true })
.catch(() => {})
.finally(() => {
// Once installation mode has completely disappeared, prompt EULA
if (pendingEulaPopup) {
maybeShowEulaPopup();
} else {
checkMinecraftEulaOnLoad();
}
});
hydrateInitialConsoleHistory(INITIAL_CONSOLE_HISTORY_LIMIT).then(() => {
attachLogStreamIfRemote({ tail: 0, forceReconnect: true });
}).catch(() => {
attachLogStreamIfRemote({ tail: 0, forceReconnect: true });
});
setTimeout(() => {
syncConsoleHistoryGap({ reason: 'post_install_sync', limit: 500 });
}, 1200);
setTimeout(() => {
syncConsoleHistoryGap({ reason: 'post_install_sync_2', limit: 500 });
}, 3000);
updatePowerControlsInteractivity();
if (typeof callback === 'function') callback();
}, 150);
}, 200);
}
function showConsoleSpinner() {
if (isInstallingActive || document.body.classList.contains('server-is-installing') || window.__ADPANEL_IS_INSTALLING__) return;
if (consoleLoadingSpinner) {
consoleLoadingSpinner.classList.remove('hidden');
}
}
function revealConsoleContent() {
if (isInstallingActive || document.body.classList.contains('server-is-installing') || window.__ADPANEL_IS_INSTALLING__) return;
if (consoleContentEl) {
consoleContentEl.classList.add('console-revealed');
}
if (consoleLoadingSpinner) {
consoleLoadingSpinner.classList.add('hidden');
}
}
function hideConsoleSpinner() {
if (isInstallingActive || document.body.classList.contains('server-is-installing') || window.__ADPANEL_IS_INSTALLING__) return;
revealConsoleContent();
}
const cmdRow = document.getElementById("cmdRow");
const cmdInput = document.getElementById("cmdInput");
const sendBtn = document.getElementById("sendBtn");
const entriesEl = document.getElementById("entries");
const breadcrumbs = document.getElementById("breadcrumbs");
const filesModal = document.getElementById("filesModal");
const filesModalClose = document.getElementById("filesModalClose");
const fileUploadModal = document.getElementById("fileUploadModal");
const uploadLabel = document.getElementById("uploadLabel");
const newBtn = document.getElementById("newBtn");
const selectAllToggle = document.getElementById("selectAllToggle");
const bulkDeleteBtn = document.getElementById("bulkDeleteBtn");
const bulkArchiveBtn = document.getElementById("bulkArchiveBtn");
const fmActions = document.getElementById("fmActions");
const fmDefaultActions = document.getElementById("fmDefaultActions");
const fmSelectionActions = document.getElementById("fmSelectionActions");
const fmDownloadBtn = document.getElementById("fmDownloadBtn");
const fmRenameBtn = document.getElementById("fmRenameBtn");
const fmUnarchiveBtn = document.getElementById("fmUnarchiveBtn");
const fmArchiveBtn = document.getElementById("fmArchiveBtn");
const fmDeleteBtn = document.getElementById("fmDeleteBtn");
const taskModal = document.getElementById("taskModal");
const taskModalClose = document.getElementById("taskModalClose");
const taskStartupSelect = document.getElementById("taskStartupSelect");
const statusLabel = document.getElementById("statusLabel");
const editorModalClose = document.getElementById("editorModalClose");
const editorPath = document.getElementById("editorPath");
const codeShell = document.getElementById("codeShell");
let editorOriginalContent = "";
// adpanel:editor-save-occ — the machine-readable code the panel answers a
// refused stale editor save with (server home: services/node-fs-relay.js,
// FS_WRITE_STALE_CONFLICT_ERROR — the wire string is the client contract).
const EDITOR_SAVE_CONFLICT_CODE = 'file_changed_on_disk';
// adpanel:editor-save-occ — sha256 of the exact content this editor loaded
// (the RAW server text, before normalizeInput folds CRLF: the server
// compares against the on-disk bytes). Sent as expectedSha256 on editor
// saves so the panel can refuse a write that would clobber newer disk
// content. Empty string = no guard (the save omits the field — opt-in);
// set on open via Web Crypto, cleared on close, re-based to the saved
// content after a successful save.
let editorBaseSha256 = "";
const lineGutter = document.getElementById("lineGutter");
const textArea = document.getElementById("textArea");
const editorSave = document.getElementById("editorSave");
const editorDiscard = document.getElementById("editorDiscard");
const editorModal = document.getElementById("editorModal");
let editorDocumentGeneration = 0;
let editorSaving = false;
const monacoContainer = document.getElementById("monacoContainer");
const aceContainer = document.getElementById("aceContainer");
let aceEditor = null;
let useAceFallback = null;
let monacoEditor = null;
let monacoLoaderPromise = null;
let monacoFindWidgetObserver = null;
const progressWheel = document.getElementById("progressWheel");
const progressFill = document.getElementById("progressFill");
const progressPopup = document.getElementById("progressPopup");
const popupPercent = document.getElementById("popupPercent");
const popupBar = document.getElementById("popupBar");
const popupMsg = document.getElementById("popupMsg");
const popupTime = document.getElementById("popupTime");
const popupClose = document.getElementById("popupClose");
const popupFileList = document.getElementById("popupFileList");
const dropOverlay = document.getElementById("dropOverlay");
const dropTitle = document.getElementById("dropTitle");
const dropSubtitle = document.getElementById("dropSubtitle");
const filesBtn = document.getElementById("filesBtn");
const taskBtn = document.getElementById("taskBtn");
const runBtn = document.getElementById("runBtn");
const stopBtn = document.getElementById("stopBtn");
const miniRunBtn = document.getElementById("miniRunBtn");
const miniStopBtn = document.getElementById("miniStopBtn");
const miniKillBtn = document.getElementById("miniKillBtn");
const storeBtn = document.getElementById("storeBtn");
let monacoIdleSuggestTimer = null;
const storeModal = document.getElementById("storeModal");
const storeModalClose = document.getElementById("storeModalClose");
const storeContent = document.getElementById("storeContent");
const storeTabs = document.getElementById("storeTabs");
const storeTabVersions = document.getElementById("storeTabVersions");
const storeTabPlugins = document.getElementById("storeTabPlugins");
const storeSubtitle = document.getElementById("storeSubtitle");
const storePrefModal = document.getElementById("storePrefModal");
const storePrefOptions = document.getElementById("storePrefOptions");
const storePrefClose = document.getElementById("storePrefClose");
const dockFiles = document.getElementById("dockFiles");
const dockTask = document.getElementById("dockTask");
const dockRun = document.getElementById("dockRun");
const dockStop = document.getElementById("dockStop");
const dockNew = document.getElementById("dockNew");
const dockStore = document.getElementById("dockStore");
const mrPluginModal = document.getElementById("mrPluginModal");
const mrPluginModalClose = document.getElementById("mrPluginModalClose");
const mrPluginCancel = document.getElementById("mrPluginCancel");
const mrPluginName = document.getElementById("mrPluginName");
const mrPluginModalTitle = document.getElementById("mrPluginModalTitle");
const mrPlatformGrid = document.getElementById("mrPlatformGrid");
const mrVersionGrid = document.getElementById("mrVersionGrid");
const mrPluginInstallBtn = document.getElementById("mrPluginInstallBtn");
let currentEditorPath = "";
// True while a history entry pushed by openEditorModal is still on the
// stack; lets every close path pop exactly once (and never double-push).
let editorHistoryPushed = false;
let selectedEntries = new Set();
let serverInfo = null;
let SERVER_NODE_ID = null;
let currentStoreTab = 'versions';
let storeProvidersCache = null;
let storeCurrentProvider = null;
// Generation counter for the Store panel: every view that takes over
// storeContent (providers grid, a provider's version list, the
// Plugins/Mods tab) claims the panel first, and async writers re-check
// their claim after every await. Without this, a slow provider fetch
// (e.g. a live Paper resolve of ~200 version metadatas) would paint its
// version list over whichever view the user opened while it was in
// flight — including installs targeting a list the user never opened.
let storeViewSeq = 0;
function claimStorePanel() {
return ++storeViewSeq;
}
let papermcVersionsCache = null;
const STORE_PREF_STORAGE_KEY = 'store-preference-map';
const STORE_PREF_OPTIONS = [
{
id: 'discord-bot',
title: 'Node.js & Bots',
description: 'Show Node.js runtimes and container versions optimized for Discord or generic bots.',
logo: '/images/nodejs.webp'
},
{
id: 'minecraft',
title: 'Minecraft Servers',
description: 'Choose Minecraft cores and browse plugins/mods like Paper, Spigot, or Purpur.',
logo: '/images/minecraft-logo.webp'
},
{
id: 'fivem',
title: 'FiveM',
description: 'Install Linux FXServer artifacts using the recommended, optional, or a custom build.',
logo: '/images/FiveM-Logo.webp'
}
];
let pendingStoreOpen = false;
const JUMP_THRESHOLD = 56; // ~2 lines at 20px font × 1.4 line-height
const MR_PLUGIN_LOADERS = ["paper", "purpur", "spigot", "bukkit", "velocity", "waterfall", "folia"];
const MR_MOD_LOADERS = ["fabric", "forge", "neoforge", "quilt"];
const MR_VALID_LOADERS = Array.from(new Set([...MR_PLUGIN_LOADERS, ...MR_MOD_LOADERS]));
let mrPluginsState = {
offset: 0,
limit: 24,
query: "",
loading: false,
more: true,
// Which Modrinth facet the Plugins/Mods tab is browsing; the search
// facet, the platform list, and the install destination all follow it.
projectType: "plugin",
// Set when a fresh search was requested while another load was in
// flight; the in-flight load supersedes itself and re-runs the search.
pendingReset: false
};
// Generation counter for Modrinth loads: bumped whenever a fresh search
// supersedes an in-flight one, so stale responses are discarded instead of
// rendering results for a type or query the user already left behind.
let mrPluginsLoadSeq = 0;
// The Plugins/Mods search debounce lives at module level (not per-render)
// so re-rendering the tab cancels a pending timer instead of letting it
// re-inject a query the user already cleared or superseded.
let mrPluginsSearchTimer = null;
let mrAllProjectVersions = [];
let mrCurrentProjectId = null;
// Project type of the project currently open in the install modal —
// decides whether the jar lands in plugins/ or mods/.
let mrCurrentProjectType = "plugin";
let mrSelectedPlatform = null;
let mrSelectedMcVersion = null;
const POWER_STATE = Object.freeze({
UNKNOWN: "unknown",
STOPPED: "stopped",
RUNNING: "running",
STARTING: "starting",
STOPPING: "stopping",
INSTALLING: "installing"
});
const POWER_STATE_LABEL = Object.freeze({
[POWER_STATE.UNKNOWN]: "idle",
[POWER_STATE.STOPPED]: "stopped",
[POWER_STATE.RUNNING]: "running",
[POWER_STATE.STARTING]: "running",
[POWER_STATE.STOPPING]: "stopped",
[POWER_STATE.INSTALLING]: "installing"
});
const POWER_POLL_IDLE_MS = 6000;
const POWER_POLL_TRANSITION_MS = 2000;
const POWER_TRANSITION_TIMEOUT_MS = 30000;
const powerRunControls = Array.from(document.querySelectorAll('[data-action="run"]'));
const powerStopControls = Array.from(document.querySelectorAll('[data-action="stop"]'));
const powerKillControls = Array.from(document.querySelectorAll('[data-action="kill"]'));
let powerState = POWER_STATE.UNKNOWN;
let powerTransition = null;
let powerTransitionSince = 0;
let powerNodeOnline = true;
let powerPollTimer = null;
let powerPollInFlight = false;
let killRequestInFlight = false;
function normalizePowerState(raw) {
const v = String(raw || "").trim().toLowerCase();
if (!v) return POWER_STATE.UNKNOWN;
if (v.includes("install") || v.includes("pull") || v.includes("setup") || v.includes("building") || v.includes("creating") || v.includes("queued") || v.includes("download") || v.includes("extract") || v.includes("prepar")) return POWER_STATE.INSTALLING;
if (v.includes("starting")) return POWER_STATE.STARTING;
if (v.includes("stopping")) return POWER_STATE.STOPPING;
if (v.includes("running") || v.includes("online") || v.includes("up") || v.includes("healthy")) return POWER_STATE.RUNNING;
if (v.includes("stopped") || v.includes("offline") || v.includes("down") || v.includes("exit") || v.includes("dead")) return POWER_STATE.STOPPED;
return POWER_STATE.UNKNOWN;
}
function isTransitionPowerState(state) {
return state === POWER_STATE.STARTING || state === POWER_STATE.STOPPING || state === POWER_STATE.INSTALLING;
}
function setPowerControlDisabled(el, disabled) {
if (!el) return;
el.classList.toggle("disabled", disabled);
el.setAttribute("aria-disabled", disabled ? "true" : "false");
if (typeof el.disabled === "boolean") {
el.disabled = disabled;
}
}
function canRunNow() {
return hasPerm("server_start") && powerNodeOnline && powerState === POWER_STATE.STOPPED && !isInstallingActive;
}
function canStopNow() {
return hasPerm("server_stop") && powerNodeOnline && powerState === POWER_STATE.RUNNING && !isInstallingActive;
}
function canKillNow() {
return !killRequestInFlight && hasPerm("server_stop") && powerNodeOnline && !isInstallingActive &&
(powerState === POWER_STATE.RUNNING || powerState === POWER_STATE.STARTING || powerState === POWER_STATE.STOPPING);
}
function isPowerActionAllowed(action) {
if (action === "run") return canRunNow();
if (action === "stop") return canStopNow();
if (action === "kill") return canKillNow();
return false;
}
function updatePowerStatusLabel() {
if (!statusLabel) return;
statusLabel.textContent = POWER_STATE_LABEL[powerState] || "idle";
}
function updatePowerControlsInteractivity() {
const enableRun = canRunNow();
const enableStop = canStopNow();
powerRunControls.forEach((el) => setPowerControlDisabled(el, !enableRun));
powerStopControls.forEach((el) => setPowerControlDisabled(el, !enableStop));
const enableKill = canKillNow();
powerKillControls.forEach((el) => setPowerControlDisabled(el, !enableKill));
}
function setPowerState(nextState, opts = {}) {
const normalized = normalizePowerState(nextState);
const now = Date.now();
if (normalized === POWER_STATE.STARTING || normalized === POWER_STATE.STOPPING) {
if (powerTransition !== normalized) {
powerTransition = normalized;
powerTransitionSince = now;
}
} else if (normalized === POWER_STATE.RUNNING || normalized === POWER_STATE.STOPPED) {
powerTransition = null;
powerTransitionSince = 0;
} else if (!opts.keepTransition) {
powerTransition = null;
powerTransitionSince = 0;
}
if (powerState !== normalized || opts.force) {
powerState = normalized;
updatePowerStatusLabel();
}
updatePowerControlsInteractivity();
}
function applyPolledPowerState(rawState, nodeOnline, extra = {}) {
powerNodeOnline = nodeOnline !== false;
updateOfflineState(!powerNodeOnline);
const polled = normalizePowerState(rawState);
const now = Date.now();
if (polled === POWER_STATE.INSTALLING) {
if (!isInstallingActive) {
startInstallingOverlay('installing');
}
setPowerState(POWER_STATE.INSTALLING, { force: true });
return;
}
if (extra && extra.eulaRequired && !isServerInInstallMode() && polled !== POWER_STATE.RUNNING && polled !== POWER_STATE.STARTING) {
maybeShowEulaPopup();
}
if (isInstallingActive) {
// Prevent premature dismissal on transient unknown/stopped during the first 6 seconds
if (polled === POWER_STATE.UNKNOWN || (polled === POWER_STATE.STOPPED && (now - installStartTime) < 6000)) {
return;
}
finishInstallingOverlay();
}
if (polled === POWER_STATE.UNKNOWN && !powerTransition) {
if (powerState === POWER_STATE.RUNNING || powerState === POWER_STATE.STOPPED) {
updatePowerControlsInteractivity();
return;
}
const seeded = normalizePowerState(serverInfo && serverInfo.status ? serverInfo.status : "");
if (seeded === POWER_STATE.RUNNING || seeded === POWER_STATE.STOPPED) {
setPowerState(seeded, { force: true });
return;
}
}
if (powerTransition === POWER_STATE.STARTING) {
if (polled === POWER_STATE.RUNNING) {
setPowerState(POWER_STATE.RUNNING, { force: true });
return;
}
if (polled === POWER_STATE.STOPPED && now - powerTransitionSince > 5000) {
setPowerState(POWER_STATE.STOPPED, { force: true });
return;
}
if (now - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS) {
setPowerState(polled === POWER_STATE.UNKNOWN ? POWER_STATE.STOPPED : polled, { force: true });
return;
}
setPowerState(POWER_STATE.STARTING, { force: true, keepTransition: true });
return;
}
if (powerTransition === POWER_STATE.STOPPING) {
if (polled === POWER_STATE.STOPPED) {
setPowerState(POWER_STATE.STOPPED, { force: true });
return;
}
if (now - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS) {
setPowerState(polled === POWER_STATE.UNKNOWN ? POWER_STATE.RUNNING : polled, { force: true });
return;
}
setPowerState(POWER_STATE.STOPPING, { force: true, keepTransition: true });
return;
}
setPowerState(polled, { force: true });
}
async function fetchPowerSnapshot() {
const r = await fetch(`/api/server/${encodeURIComponent(bot)}/node-status`, {
cache: "no-store", signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS)
});
if (!r.ok) {
if (r.status === 404 || r.status === 502 || r.status === 503 || r.status === 504) {
updateOfflineState(true);
}
throw new Error(`power-status-${r.status}`);
}
const j = await r.json();
const isInst = Boolean(j && (j.isInstalling || j.status === 'installing' || (j.setupStatus && j.setupStatus !== 'ready' && j.setupStatus !== 'failed')));
const isNodeOnline = j && typeof j.nodeOnline !== "undefined" ? j.nodeOnline !== false : true;
updateOfflineState(!isNodeOnline);
return {
state: isInst ? POWER_STATE.INSTALLING : ((j && (j.status || j.state)) || ""),
isInstalling: isInst,
setupStatus: j && j.setupStatus,
createdAt: j && j.createdAt,
nodeOnline: isNodeOnline,
eulaRequired: Boolean(j && j.eulaRequired)
};
}
function nextPowerPollDelay() {
return isTransitionPowerState(powerState) ? POWER_POLL_TRANSITION_MS : POWER_POLL_IDLE_MS;
}
function schedulePowerStatePoll(delayMs = nextPowerPollDelay()) {
if (powerPollTimer) clearTimeout(powerPollTimer);
powerPollTimer = setTimeout(() => {
refreshPowerState().catch(() => { });
}, delayMs);
}
async function refreshPowerState(opts = {}) {
const { force = false } = opts;
if (powerPollInFlight && !force) return;
powerPollInFlight = true;
try {
const snapshot = await fetchPowerSnapshot();
applyPolledPowerState(snapshot.state, snapshot.nodeOnline, { eulaRequired: snapshot.eulaRequired });
} catch {
if (powerTransition && (Date.now() - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS)) {
powerTransition = null;
powerTransitionSince = 0;
}
updatePowerControlsInteractivity();
} finally {
powerPollInFlight = false;
schedulePowerStatePoll();
}
}
function startPowerStatePolling() {
schedulePowerStatePoll(120);
}
function stopPowerStatePolling() {
if (powerPollTimer) {
clearTimeout(powerPollTimer);
powerPollTimer = null;
}
}
// NOTE: Console output (stdout text) must never drive powerState. Bot owners
// control their server's stdout, so phrase-matching console lines (e.g.
// "[ADPanel] server started") is spoofable. powerState is derived only from
// authoritative sources: the structured nodeStatus socket event and the
// periodic /api/server/:bot/node-status poll (applyPolledPowerState).
updatePowerControlsInteractivity();
window.addEventListener('load', () => {
ensureJumpBtn();
updateJumpBtnVisibility();
});
window.addEventListener('pagehide', stopPowerStatePolling);
window.addEventListener('resize', updateJumpBtnVisibility);
async function fetchPerms(opts = {}) {
const { preserveCurrentState = false } = opts;
try {
// adpanel:scheduler-fetch-bound — this GET runs INSIDE the bounded
// scheduler create/delete flows (ensureServerActionToken's refreshBefore
// arm): a stalled permissions response would otherwise wedge the
// in-flight guards on an unbounded fetch. Bound it like every other
// boot/scheduler fetch (fetchWithTimeout, 15s — generous for a small
// JSON GET); the abort lands in the catch below, whose null the three
// callers already tolerate (ensureServerActionToken falls back to the
// cached token, the bootstrap step logs and moves on).
const r = await fetchWithTimeout(`/api/servers/${encodeURIComponent(bot)}/permissions`, { cache: 'no-store' }, 15000);
if (!r.ok) {
const status = r.status;
if (status === 401 || status === 403 || status === 404) {
const offlineOverlay = document.getElementById('offlineOverlay');
const offlineText = document.querySelector('#offlineOverlay .offline-text');
if (offlineOverlay && offlineText) {
offlineText.textContent = status === 401 ? "Not authenticated" : (status === 404 ? "Don't panic! This is due to an offline node or a dangling server." : "No Access");
offlineOverlay.classList.add('show');
// adpanel:auth-overlay-ownership — claim the shared overlay with
// the console-side tag ('-auth', mirroring the planner's
// 'planner-auth') so the node-status writers (updateOfflineState)
// can neither hide this overlay on a node-online transition while
// the user is still unauthenticated, nor re-purpose it on a node
// flap — the dangling-server half of the 404 text is not resolved
// by the node coming back either. Claiming on every status this
// one write site shows (401/403/404) keeps it a single writer.
// Released only by the overlay's own "Back to Dashboard" redirect
// — a full page navigation; fetchPerms' success path never hides
// the overlay and no caller of fetchPerms does either, so there
// is no in-page release path to wire.
offlineOverlayOwner = 'console-auth';
}
}
throw new Error('perm fetch failed');
}
const j = await r.json();
IS_ADMIN = !!j.isAdmin;
AGENT_ACCESS = !!j.agent_access;
SERVER_ACTION_TOKENS = (j && j.actionTokens && typeof j.actionTokens === 'object') ? { ...j.actionTokens } : {};
serverActionTokensLoadedAt = Date.now();
if (j && j.perms && typeof j.perms === 'object') {
PERMS = Object.assign(PERMS, j.perms);
}
if (profileEmailEl && j) {
const emailFromApi =
(j.user && j.user.email) ? j.user.email :
(j.email || null);
if (emailFromApi) {
profileEmailEl.textContent = emailFromApi;
}
}
return j;
} catch (e) {
if (!preserveCurrentState) {
IS_ADMIN = false;
AGENT_ACCESS = false;
SERVER_ACTION_TOKENS = {};
serverActionTokensLoadedAt = 0;
PERMS = {
files_read: false, files_delete: false, files_rename: false, files_archive: false, console_read: false, console_write: false,
server_stop: false, server_start: false, files_upload: false, files_create: false,
activity_logs: false, backups_view: false, backups_create: false, backups_delete: false,
scheduler_access: false, scheduler_create: false, scheduler_delete: false, store_access: false,
server_reinstall: false, planner_access: false, agent_settings: false
};
}
return null;
}
}
const CONSOLE_COMMAND_HISTORY_LIMIT = 32;
const CONSOLE_COMMAND_ECHO_HISTORY_LIMIT = 80;
const RECENT_SUBMITTED_COMMAND_TTL_MS = 2 * 60 * 1000;
const recentSubmittedConsoleCommands = new Map();
// adpanel:console-command-history - raw commands may contain credentials;
// browser storage is shared by everyone who signs in from this profile.
try {
localStorage.removeItem(`adpanel:${bot}:command_history`);
localStorage.removeItem(`adpanel:${bot}:command_echo_history`);
localStorage.removeItem(`adpanel:${bot}:console_history_reset_at`);
} catch { }
let consoleCommandHistory = [];
let consoleCommandHistoryIndex = -1;
let consoleCommandEchoHistory = [];
let consoleHistoryResetAt = 0;
function normalizeConsoleCommandText(value) {
return visibleConsoleText(String(value || ''))
.replace(/[\r\n]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function normalizeConsoleCommandKey(value) {
let text = normalizeConsoleCommandText(value);
if (
text.length >= 2 &&
((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))
) {
text = text.slice(1, -1).trim();
}
return text;
}
function firstConsoleCommandToken(value) {
const text = normalizeConsoleCommandKey(value);
if (!text) return '';
if (text.startsWith('"') || text.startsWith("'")) {
const quote = text[0];
const end = text.indexOf(quote, 1);
return end > 1 ? text.slice(1, end).trim() : '';
}
return text.split(/\s+/, 1)[0] || '';
}
function pruneRecentSubmittedConsoleCommands(now = Date.now()) {
for (const [key, ts] of recentSubmittedConsoleCommands.entries()) {
if ((now - ts) > RECENT_SUBMITTED_COMMAND_TTL_MS) {
recentSubmittedConsoleCommands.delete(key);
}
}
}
function rememberSubmittedConsoleCommand(commandText, sentAt = Date.now()) {
const key = normalizeConsoleCommandKey(commandText);
if (!key) return;
pruneRecentSubmittedConsoleCommands(sentAt);
recentSubmittedConsoleCommands.set(key, sentAt);
if (recentSubmittedConsoleCommands.size > 80) {
const oldest = recentSubmittedConsoleCommands.keys().next().value;
if (oldest) recentSubmittedConsoleCommands.delete(oldest);
}
}
function knownConsoleCommandSets() {
pruneRecentSubmittedConsoleCommands();
const exact = new Set();
const first = new Set();
const duplicated = new Set();
const commands = [];
const addCommand = (value) => {
const key = normalizeConsoleCommandKey(value);
if (!key) return;
exact.add(key);
commands.push(key);
const token = firstConsoleCommandToken(key);
if (token) first.add(token);
const duplicate = duplicatedFirstConsoleCommandEcho(key);
if (duplicate) duplicated.add(duplicate);
};
for (const key of recentSubmittedConsoleCommands.keys()) {
addCommand(key);
}
if (Array.isArray(consoleCommandHistory)) {
for (const entry of consoleCommandHistory) {
addCommand(entry);
}
}
if (Array.isArray(consoleCommandEchoHistory)) {
for (const entry of consoleCommandEchoHistory) {
addCommand(entry && entry.command);
}
}
return { exact, first, duplicated, commands };
}
function isKnownConsoleCommandText(value, sets = knownConsoleCommandSets(), allowFirstToken = false) {
const key = normalizeConsoleCommandKey(value);
if (!key) return false;
return sets.exact.has(key) || (allowFirstToken && sets.first.has(key));
}
function duplicatedFirstConsoleCommandEcho(value) {
const command = normalizeConsoleCommandKey(value);
if (!command) return '';
const chars = Array.from(command);
return chars.length ? chars[0] + command : '';
}
function isPrefixedConsoleCommandEchoArtifact(value, commandValue) {
const text = normalizeConsoleCommandKey(value);
const command = normalizeConsoleCommandKey(commandValue);
if (!text || !command || text === command) return false;
if (!text.endsWith(command)) return false;
const prefix = text.slice(0, text.length - command.length);
return !!prefix && command.startsWith(prefix);
}
function isRecentDuplicatedConsoleCommandEcho(value) {
const key = normalizeConsoleCommandKey(value);
if (!key) return false;
const now = Date.now();
pruneRecentSubmittedConsoleCommands(now);
for (const [command, ts] of recentSubmittedConsoleCommands.entries()) {
if ((now - Number(ts || 0)) > 15000) continue;
const cmdKey = normalizeConsoleCommandKey(command);
if (!cmdKey) continue;
if (key === duplicatedFirstConsoleCommandEcho(cmdKey)) return true;
if (key.length > cmdKey.length && key.endsWith(cmdKey)) {
const prefix = key.slice(0, key.length - cmdKey.length);
if (cmdKey.startsWith(prefix) || prefix.startsWith(cmdKey.slice(0, 1))) return true;
}
const firstChar = cmdKey[0];
if (firstChar && key.length > cmdKey.length) {
for (let n = 2; n <= 5; n++) {
if (key === firstChar.repeat(n) + cmdKey.slice(1)) return true;
if (key === firstChar.repeat(n) + cmdKey) return true;
}
}
}
return false;
}
function shouldDropConsoleCommandArtifact(visibleLine) {
const text = normalizeConsoleCommandText(visibleLine);
if (!text) return false;
if (isRecentDuplicatedConsoleCommandEcho(text)) return true;
return false;
}
function clientClean(raw) {
if (!raw) return "";
let s = decodeHtmlEntities(raw);
s = stripDockerStreamFrames(s);
s = s.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
s = sanitizeAnsiForConsole(s);
s = s.replace(/…+/g, "");
s = s.replace(/^\s*(?:stdout|stderr)\s*:\s*/gmi, "");
const out = [];
for (let line of s.split("\n")) {
line = line.replace(/…+/g, "");
line = line.replace(/^((?:\x1B\[[0-9:;]*m)*)(?:\s*>\.{2,}\s*)/, '$1');
line = line.replace(/\s+$/, "");
const visible = visibleConsoleText(line);
const t = visible.trim();
if (!t) continue;
if (/^[\s>.=…-]+$/.test(t)) continue;
if (/^\[ADPanel\]\s+Connected\s*$/i.test(t)) continue;
if (/^>\s*$/.test(t)) continue;
if (/^>\s*\.{2,}\s*$/.test(t)) continue;
if (/^>\s+[^@\s]+@[^\s]+\s+\S+/i.test(t)) continue;
if (/^>\s+(?:node|npm|pnpm|yarn)\b/i.test(t)) continue;
if (t.includes("Usage: docker")) continue;
if (t.includes("Run 'docker COMMAND --help'")) continue;
if (t.includes("For more help on how to use Docker")) continue;
if (/^\s*Container started\s*$/i.test(t)) continue;
if (/^[0-9a-f]{64}(?:\s*Container started)?\s*$/i.test(t)) continue;
if (/^\s*\[?waiting\]?\s+/i.test(t)) continue;
if (/container\s+".*"\s+not\s+found\s+yet/i.test(t)) continue;
if (/Error response from daemon:\s*No such container/i.test(t)) continue;
if (/^\s*\[init\]\s/i.test(t)) continue;
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z,?version=.*$/i.test(t)) continue;
if (shouldDropConsoleCommandArtifact(t)) continue;
out.push(line);
}
let joined = out.join("\n");
joined = joined
.replace(/([^\n])(?=20\d{2}-\d{2}-\d{2}T)/g, "$1\n");
joined = joined.replace(/\n{2,}/g, "\n");
if (joined && !joined.endsWith("\n")) joined += "\n";
return joined;
}
let ansiUp = null;
function getAnsiUp() {
if (!ansiUp) {
if (typeof AnsiUp !== 'undefined') {
ansiUp = new AnsiUp();
ansiUp.use_classes = false;
} else {
// Fail closed: never hand back an identity transform, which would let
// unescaped bot output reach innerHTML. ansiToHtml() detects this case
// first and routes to its text-only escape fallback instead.
throw new Error('AnsiUp vendor script is not loaded');
}
}
return ansiUp;
}
function ansiToHtml(text) {
if (!text) return "";
// Fail closed: if AnsiUp (/vendor/ansi_up.min.js) failed to load, never let
// raw bot output reach innerHTML verbatim. Re-run the same clientClean
// preprocessing used at ingest (strips OSC/DCS/non-SGR escape sequences)
// and HTML-escape the remaining plain text instead.
if (typeof AnsiUp === 'undefined') {
const cleaned = clientClean(text);
return cleaned ? escapeHtml(cleaned) : "";
}
// Strip all ANSI color codes EXCEPT the sent command color (38;5;75m) and reset code (0m)
let result = text.replace(/\x1b\[(?!(?:38;5;75|0)m)[0-9;]*m/g, '');
// Process remaining codes (only light blue for sent commands + reset) with ansi_up
result = getAnsiUp().ansi_to_html(result);
result = result.replace(
/(https?:\/\/[^\s<>"']+)/gi,
'$1'
);
// Format ADaemon log lines with the custom badge
// Supports ADAEMON>>, ADAEMON>>, %adaemon%, [ADaemon], [ADPanel]
result = result.replace(
/(^|\n)(?:ADAEMON>>|ADAEMON>>|%adaemon%|\[ADaemon\]:?|\[ADPanel\]:?)\s*(.*?)(?=\n|$)/gi,
(match, lead, msg) => {
return `${lead}ADaemon${msg}`;
}
);
// Format Minecraft server log lines with the ADaemon badge as well: the raw
// "[HH:MM:SS LEVEL]:" prefix is stripped so server output matches the
// daemon's starting-log styling.
result = result.replace(
/(^|\n)\[\d{1,2}:\d{2}:\d{2}\]\s*\[(?:INFO|WARN|ERROR|FATAL|DEBUG|TRACE)\]:?\s*(.*?)(?=\n|$)/gi,
(match, lead, msg) => {
return `${lead}ADaemon${msg}`;
}
);
// Format Sent command lines with the custom badge
// Supports ADPANELCMD>>, ADPANELCMD>>
result = result.replace(
/(^|\n)(?:ADPANELCMD>>|ADPANELCMD>>)\s*(.*?)(?=\n|$)/gi,
(match, lead, cmd) => {
return `${lead}Sent${cmd}`;
}
);
return result;
}
let userPinnedBottom = true;
let suppressAutoScroll = false;
const COMMAND_SUBMIT_DEDUPE_MS = 0;
let commandSendInFlight = false; // kept for legacy compat; queue is the real gate
let lastSubmittedCommand = "";
let lastSubmittedAt = 0;
let lastCommandRequestId = "";
// FIFO queue: input clears instantly, commands fire sequentially without blocking the UI
const commandQueue = [];
let commandQueueRunning = false;
let pendingConsoleHistoryResyncTimer = null;
let lastConsoleLiveAt = 0;
function applyConsoleHistoryReset(resetAt = Date.now(), options = {}) {
const ts = Number(resetAt || Date.now()) || Date.now();
consoleHistoryResetAt = Math.max(consoleHistoryResetAt, ts);
consoleCommandEchoHistory = consoleCommandEchoHistory
.filter((entry) => (Number(entry && entry.ts) || 0) >= consoleHistoryResetAt);
recentSubmittedConsoleCommands.clear();
if (options.resetBuffer === true) resetConsoleBuffer();
}
function resetLocalConsoleHistorySession() {
applyConsoleHistoryReset(Date.now(), { resetBuffer: true });
try {
closeRemoteLogEventSource();
attachLogStreamIfRemote({ tail: 0, forceReconnect: true });
} catch { }
return true;
}
function rememberConsoleCommandEcho(commandText, sentAt = Date.now()) {
const command = normalizeConsoleCommandKey(commandText);
if (!command) return;
rememberSubmittedConsoleCommand(command, sentAt);
const ts = Number(sentAt) || Date.now();
consoleCommandEchoHistory = [
{ command, ts },
...consoleCommandEchoHistory.filter((entry) => {
const c = normalizeConsoleCommandKey(entry && entry.command);
const t = Number(entry && entry.ts) || 0;
return c !== command || Math.abs(t - ts) > 1500;
})
].slice(0, CONSOLE_COMMAND_ECHO_HISTORY_LIMIT);
}
// Stable ordering for console history entries: prefer the server-assigned
// monotonic sequence (seq); fall back to timestamp only when seq is absent.
// This mirrors the server ordering and prevents commands/output from being
// jumbled by clock skew between the panel and the node.
function consoleHistoryEntryComparator(a, b) {
const sa = Number(a && a.seq) || 0;
const sb = Number(b && b.seq) || 0;
if (sa && sb && sa !== sb) return sa - sb;
const ta = Number(a && a.ts) || 0;
const tb = Number(b && b.ts) || 0;
if (ta !== tb) return ta - tb;
return sa - sb;
}
function mergeLocalConsoleCommandEchoHistory(lines, limit = 80) {
const remote = Array.isArray(lines) ? lines.slice() : [];
return remote
.sort(consoleHistoryEntryComparator)
.slice(-Math.max(1, Number(limit) || 80));
}
function rememberConsoleCommandForInput(commandText) {
const command = String(commandText || '').trim();
if (!command) return;
consoleCommandHistory = [
command,
...consoleCommandHistory.filter((entry) => entry !== command)
].slice(0, CONSOLE_COMMAND_HISTORY_LIMIT);
consoleCommandHistoryIndex = -1;
}
function recallConsoleCommand(direction) {
if (!cmdInput || !consoleCommandHistory.length) return;
if (direction < 0) {
consoleCommandHistoryIndex = Math.min(consoleCommandHistoryIndex + 1, consoleCommandHistory.length - 1);
} else {
consoleCommandHistoryIndex = Math.max(consoleCommandHistoryIndex - 1, -1);
}
cmdInput.value = consoleCommandHistory[consoleCommandHistoryIndex] || '';
const cursor = cmdInput.value.length;
try { cmdInput.setSelectionRange(cursor, cursor); } catch { }
}
function isNearBottom(el) {
return (el.scrollHeight - el.scrollTop - el.clientHeight) < JUMP_THRESHOLD;
}
function canScroll(el) {
return el && (el.scrollHeight - el.clientHeight) > 2;
}
let jumpBtn = null;
function ensureJumpBtn() {
if (jumpBtn) return jumpBtn;
try {
if (getComputedStyle(consoleEl).position === 'static') {
consoleEl.style.position = 'relative';
}
} catch { }
jumpBtn = document.createElement('button');
jumpBtn.type = 'button';
jumpBtn.className = 'jump-btn';
jumpBtn.setAttribute('aria-label', 'Jump to bottom');
jumpBtn.innerHTML = '';
// Append to positioned parent (.adpanel-console-body) if available,
// so the button stays fixed at the bottom-right corner of the visible console area
const jumpBtnContainer = consoleEl.closest('.adpanel-console-body') || consoleEl;
jumpBtnContainer.appendChild(jumpBtn);
jumpBtn.addEventListener('click', () => {
scrollConsoleToBottom(true);
suppressAutoScroll = false;
userPinnedBottom = true;
jumpBtn.classList.remove('show');
});
return jumpBtn;
}
function updateJumpBtnVisibility() {
const btn = ensureJumpBtn();
const show = canScroll(consoleEl) && !isNearBottom(consoleEl);
btn.classList.toggle('show', show);
}
function scrollConsoleToBottom(smooth = true) {
try {
if (smooth) {
const start = consoleEl.scrollTop;
const end = consoleEl.scrollHeight - consoleEl.clientHeight;
const distance = end - start;
const duration = Math.min(600, Math.max(200, Math.abs(distance) * 0.5));
let startTime = null;
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
function animateScroll(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easeOutCubic(progress);
consoleEl.scrollTop = start + (distance * easedProgress);
if (progress < 1) {
requestAnimationFrame(animateScroll);
}
}
requestAnimationFrame(animateScroll);
} else {
consoleEl.scrollTop = consoleEl.scrollHeight;
}
} catch { }
}
const MAX_CONSOLE_CHARS = 400_000;
const RECENT_CONSOLE_DEDUPE_MS = 250;
const MAX_RECENT_CONSOLE_LINES = 600;
const MAX_CONSOLE_FINGERPRINT_CHARS = 4096;
let _pendingConsoleText = "";
let _flushRaf = 0;
let _consoleRawChunks = [];
let _consoleRawChars = 0;
let lastConsoleAppendText = "";
let lastConsoleAppendAt = 0;
let lastConsoleHistorySyncTs = 0;
let lastHydratedConsoleOutputCount = 0;
const seenConsoleHistoryEntries = new Set();
const recentConsoleLineFingerprints = new Map();
// Local clear watermark, expressed in the same clock as history entry `ts`
// values: the highest entry timestamp that had been rendered when the user
// last cleared the console. History gap-syncs must never re-render entries
// at or below it, otherwise a tab-visibility change, socket reconnect, or
// EventSource reconnect would resurrect the lines the user just cleared.
// In-memory only: a fresh page load intentionally re-hydrates the
// server-side history.
let consoleClearWatermarkTs = 0;
let consoleBufferGeneration = 0;
function makeConsoleDedupeKey(source, line) {
const s = String(source || 'output');
const l = String(line || '').trim();
return `${s}:${l}`;
}
function consoleDedupeFingerprint(text) {
return String(text || '')
.replace(ANSI_SGR_RE, '')
.replace(/\s+$/g, '')
.trim();
}
function pruneRecentConsoleLineFingerprints(now = Date.now()) {
for (const [key, ts] of recentConsoleLineFingerprints.entries()) {
if ((now - ts) > RECENT_CONSOLE_DEDUPE_MS) {
recentConsoleLineFingerprints.delete(key);
}
}
}
function rememberRecentConsoleChunk(cleaned, now = Date.now()) {
const lines = String(cleaned || '').slice(-MAX_CONSOLE_CHARS).split('\n');
pruneRecentConsoleLineFingerprints(now);
for (const line of lines) {
if (line.length > MAX_CONSOLE_FINGERPRINT_CHARS) continue;
const key = consoleDedupeFingerprint(line);
if (!key) continue;
recentConsoleLineFingerprints.delete(key);
recentConsoleLineFingerprints.set(key, now);
if (recentConsoleLineFingerprints.size > MAX_RECENT_CONSOLE_LINES) {
recentConsoleLineFingerprints.delete(recentConsoleLineFingerprints.keys().next().value);
}
}
}
function recentlySawConsoleLine(line, sinceTs = 0) {
const cleaned = clientClean(line);
const key = consoleDedupeFingerprint(cleaned);
if (!key) return false;
const seenAt = recentConsoleLineFingerprints.get(key) || 0;
return seenAt >= sinceTs && (Date.now() - seenAt) <= RECENT_CONSOLE_DEDUPE_MS;
}
function getConsoleRecentLines(maxLines = 60) {
if (!_consoleRawChunks || !_consoleRawChunks.length) {
if (_pendingConsoleText) {
return _pendingConsoleText.split('\n').filter(l => l.trim());
}
return [];
}
const combined = _consoleRawChunks.slice(-20).join('') + (_pendingConsoleText || '');
const all = combined.split('\n').map(l => l.trim()).filter(Boolean);
return all.slice(-maxLines);
}
function findHistoryOverlapIndex(consoleTailLines, incomingLines) {
if (!incomingLines || !incomingLines.length) return -1;
if (!consoleTailLines || !consoleTailLines.length) return -1;
const maxK = Math.min(consoleTailLines.length, 15, incomingLines.length);
for (let k = maxK; k >= 1; k--) {
const probe = consoleTailLines.slice(consoleTailLines.length - k);
for (let i = incomingLines.length - k; i >= 0; i--) {
let match = true;
for (let j = 0; j < k; j++) {
const consoleLine = consoleDedupeFingerprint(probe[j]);
const incomingLine = consoleDedupeFingerprint(incomingLines[i + j]);
if (!consoleLine || !incomingLine || consoleLine !== incomingLine) {
match = false;
break;
}
}
if (match) {
return i + k - 1;
}
}
}
return -1;
}
function resetConsoleBuffer() {
consoleBufferGeneration += 1;
if (_flushRaf) {
cancelAnimationFrame(_flushRaf);
_flushRaf = 0;
}
if (pendingConsoleHistoryResyncTimer) {
clearTimeout(pendingConsoleHistoryResyncTimer);
pendingConsoleHistoryResyncTimer = null;
}
// Capture the clear watermark BEFORE lastConsoleHistorySyncTs is zeroed.
// Every line the user has seen (initial hydrate, live stream, earlier
// gap-syncs) advanced lastConsoleHistorySyncTs, so it bounds — in the
// server's entry-timestamp clock — everything the clear must keep hidden.
// Using that clock instead of Date.now() keeps the comparison valid even
// when a remote node's clock is skewed relative to the panel's.
if ((Number(lastConsoleHistorySyncTs) || 0) > consoleClearWatermarkTs) {
consoleClearWatermarkTs = Number(lastConsoleHistorySyncTs) || 0;
}
_pendingConsoleText = "";
_consoleRawChunks = [];
_consoleRawChars = 0;
lastConsoleAppendText = "";
lastConsoleAppendAt = 0;
lastConsoleHistorySyncTs = 0;
lastConsoleLiveAt = 0;
// seenConsoleHistoryEntries is intentionally NOT cleared: its keys embed
// the entry timestamp, so keeping it across a clear can only suppress
// exact re-fetches of already-seen history lines, never genuinely new
// output. Clearing it is what allowed gap-syncs to resurrect cleared
// lines as "unknown" entries.
recentConsoleLineFingerprints.clear();
if (consoleContentEl) {
consoleContentEl.innerHTML = '';
}
updateJumpBtnVisibility();
}
function formatConsoleClock(ts = Date.now()) {
const d = new Date(ts);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
function appendCommandEcho(commandText, sentAt = Date.now()) {
const safe = String(commandText || '').replace(/[\r\n]+/g, ' ').trim();
if (!safe) return;
rememberConsoleCommandEcho(safe, sentAt);
appendConsoleCommandLine(safe);
}
// Pterodactyl/Wings-style command echo. The command is rendered on its own
// line in a distinct color so it visually leads its output, with NO panel
// wall-clock (the old "[HH:MM:SS CMD]" format mixed the panel clock with the
// server's own log clock, e.g. 21:09 next to 18:08). Ordering is purely by
// position in the node stream, so it stays put across refreshes.
//
// CRITICAL: command lines must NOT go through clientClean()/appendToConsole(),
// because that pipeline strips a leading "> " and drops bare known-command
// lines as "echo artifacts" - which previously made the command disappear
// entirely. appendConsoleCommandLine() writes a pre-styled, already-clean line
// straight into the render buffer, bypassing those filters.
function formatConsoleHistoryCommand(commandText) {
const safe = String(commandText || '').replace(/[\r\n]+/g, ' ').trim();
if (!safe) return '';
return `ADPANELCMD>> ${safe}\n`;
}
function appendConsoleCommandLine(commandText, ts = Date.now()) {
const styled = formatConsoleHistoryCommand(commandText);
if (!styled) return;
const now = Date.now();
rememberConsoleCommandRendered(commandText, ts);
lastConsoleLiveAt = now;
queueConsoleText(styled);
}
// Dedicated dedup for rendered command lines. We CANNOT reuse
// recentlySawConsoleLine()/rememberRecentConsoleChunk() here because those run
// clientClean(), which strips the leading "> " and drops bare commands as
// artifacts - producing an empty fingerprint that never matches.
//
// Dedup is keyed on the command text PLUS a coarse time bucket of the source
// timestamp. This is important: a command that is genuinely sent again (e.g.
// running "pl" three times) carries a different source timestamp each time and
// MUST render each time, while the SAME single keypress arriving from two
// channels (inline EventSource marker + socket "console:command", or a history
// resync) shares the same timestamp bucket and collapses to one line.
const recentRenderedConsoleCommands = new Map();
function makeRenderedCommandKey(commandText, ts) {
const cmdKey = normalizeConsoleCommandKey(commandText);
if (!cmdKey) return '';
const numericTs = Number(ts) || 0;
const bucket = numericTs > 0 ? Math.round(numericTs / 1500) : 0;
return `${cmdKey}:${bucket}`;
}
function rememberConsoleCommandRendered(commandText, ts = 0) {
const key = makeRenderedCommandKey(commandText, ts);
if (!key) return;
const now = Date.now();
recentRenderedConsoleCommands.set(key, now);
if (recentRenderedConsoleCommands.size > 300) {
for (const [k, seenAt] of recentRenderedConsoleCommands.entries()) {
if ((now - seenAt) > 10000) recentRenderedConsoleCommands.delete(k);
}
}
}
function recentlyRenderedConsoleCommand(commandText, ts = 0) {
const key = makeRenderedCommandKey(commandText, ts);
if (!key) return false;
const seenAt = recentRenderedConsoleCommands.get(key) || 0;
return seenAt > 0 && (Date.now() - seenAt) <= 8000;
}
function createCommandRequestId() {
try {
if (window.crypto && typeof window.crypto.randomUUID === 'function') {
return window.crypto.randomUUID();
}
} catch { }
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
function setCommandSendingState(isSending) {
if (sendBtn) {
sendBtn.disabled = !!isSending;
sendBtn.classList.toggle('disabled', !!isSending);
sendBtn.setAttribute('aria-disabled', isSending ? 'true' : 'false');
}
}
function trimConsoleText(text, limit) {
const start = text.length - limit;
if (start <= 0) return text;
const newline = text.indexOf('\n', start - 1);
return text.slice(newline === -1 || newline === text.length - 1 ? start : newline + 1);
}
function queueConsoleText(text) {
if (text.length >= MAX_CONSOLE_CHARS) {
_pendingConsoleText = text.slice(-MAX_CONSOLE_CHARS);
} else {
const remaining = MAX_CONSOLE_CHARS - text.length;
if (_pendingConsoleText.length > remaining) {
_pendingConsoleText = trimConsoleText(_pendingConsoleText, Math.min(remaining, MAX_CONSOLE_CHARS * 0.75));
}
_pendingConsoleText += text;
}
if (!_flushRaf) _flushRaf = requestAnimationFrame(_flushConsole);
}
function _flushConsole() {
_flushRaf = 0;
if (!_pendingConsoleText) return;
const wasNearBottom = isNearBottom(consoleEl);
const rawChunk = _pendingConsoleText;
_pendingConsoleText = "";
_consoleRawChunks.push(rawChunk);
_consoleRawChars += rawChunk.length;
if (_consoleRawChars > MAX_CONSOLE_CHARS) {
const retained = trimConsoleText(_consoleRawChunks.join(''), Math.max(rawChunk.length, MAX_CONSOLE_CHARS * 0.75));
_consoleRawChunks = [retained];
_consoleRawChars = retained.length;
consoleContentEl.innerHTML = ansiToHtml(retained);
} else {
consoleContentEl.insertAdjacentHTML('beforeend', ansiToHtml(rawChunk));
}
hideConsoleSpinner();
if (!suppressAutoScroll && wasNearBottom) {
scrollConsoleToBottom(false);
}
updateJumpBtnVisibility();
}
function appendToConsole(rawChunk, options = {}) {
const cleaned = clientClean(rawChunk);
if (!cleaned) return;
if (options && options.live) {
lastConsoleLiveAt = Date.now();
}
const now = Date.now();
rememberRecentConsoleChunk(cleaned, now);
queueConsoleText(cleaned);
}
async function fetchConsoleHistory(limit = 80) {
const generation = consoleBufferGeneration;
const params = new URLSearchParams();
params.set('limit', String(limit));
params.set('includeCommands', '1');
const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history?${params.toString()}`, {
signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS)
});
const payload = await r.json().catch(() => ({}));
if (generation !== consoleBufferGeneration) return [];
if (!r.ok || !payload || payload.ok === false || !Array.isArray(payload.lines)) {
throw new Error((payload && (payload.error || payload.detail)) || `history_http_${r.status}`);
}
const resetAt = Number(payload.resetAt || 0) || 0;
if (resetAt > consoleHistoryResetAt) {
applyConsoleHistoryReset(resetAt, { resetBuffer: false });
}
return payload.lines
.slice()
.slice(-Math.max(1, Number(limit) || 80));
}
async function hydrateInitialConsoleHistory(limit = 5000) {
if (isInstallingActive) return 0;
if (!hasConsoleReadAccess()) {
hideConsoleSpinner();
return 0;
}
showConsoleSpinner();
let appendedCount = 0;
let outputCount = 0;
try {
const remoteLines = await fetchConsoleHistory(limit);
const lines = mergeLocalConsoleCommandEchoHistory(remoteLines, limit);
const historyChunks = [];
for (const item of lines) {
const ts = Number(item && item.ts) || 0;
const source = String(item && item.source || 'output');
const line = String(item && item.line || '');
if (!line || line.includes('[ADPanel Setup]')) continue;
// Honor the local clear watermark so a mid-session re-hydration
// (e.g. the post-install re-attach) cannot resurrect cleared lines.
if (consoleClearWatermarkTs && ts && ts <= consoleClearWatermarkTs) continue;
const historyLine = line.endsWith('\n') ? line : `${line}\n`;
if (source === 'command') {
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
historyChunks.length = 0;
}
appendConsoleCommandLine(line, ts || Date.now());
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
appendedCount += 1;
continue;
}
historyChunks.push(historyLine);
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
outputCount += 1;
appendedCount += 1;
}
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
}
lastHydratedConsoleOutputCount = outputCount;
return appendedCount;
} catch {
return 0;
} finally {
requestAnimationFrame(() => {
hideConsoleSpinner();
});
}
}
let consoleHistorySyncInFlight = false;
async function syncConsoleHistoryGap(options = {}) {
if (consoleHistorySyncInFlight || !hasConsoleReadAccess()) return 0;
if (powerState === POWER_STATE.STOPPED) return 0;
consoleHistorySyncInFlight = true;
const requestedLimit = Math.max(120, Math.min(5000, Number(options && options.limit) || 500));
try {
const remoteLines = await fetchConsoleHistory(requestedLimit);
if (!Array.isArray(remoteLines) || !remoteLines.length) return 0;
const incomingRawLines = remoteLines.map(item => String(item && item.line || ''));
const consoleTailLines = getConsoleRecentLines(60);
const overlapIdx = findHistoryOverlapIndex(consoleTailLines, incomingRawLines);
let linesToProcess = remoteLines;
if (overlapIdx >= 0) {
linesToProcess = remoteLines.slice(overlapIdx + 1);
}
if (!linesToProcess.length) {
return 0;
}
const historyChunks = [];
let addedCount = 0;
for (const item of linesToProcess) {
const ts = Number(item && item.ts) || 0;
const source = String(item && item.source || 'output');
const line = String(item && item.line || '');
if (!line || line.includes('[ADPanel Setup]')) continue;
// Local clear watermark: anything at or below the newest entry that
// had been rendered when the user last cleared stays hidden, no matter
// which trigger (tab_visible, socket_reconnect, eventsource_reconnect,
// node_reconnect, post_install_sync) re-fetched it. The seen-entry set
// below is a second net that also survives the clear.
if (consoleClearWatermarkTs && ts && ts <= consoleClearWatermarkTs) continue;
const dedupeKey = `${ts}:${source}:${line}`;
if (seenConsoleHistoryEntries.has(dedupeKey)) continue;
seenConsoleHistoryEntries.add(dedupeKey);
if (seenConsoleHistoryEntries.size > 1500) {
const first = seenConsoleHistoryEntries.values().next().value;
if (first) seenConsoleHistoryEntries.delete(first);
}
const historyLine = line.endsWith('\n') ? line : `${line}\n`;
if (source === 'command') {
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
historyChunks.length = 0;
}
if (recentlyRenderedConsoleCommand(line, ts)) {
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
continue;
}
appendConsoleCommandLine(line, ts || Date.now());
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
addedCount++;
continue;
}
if (recentlySawConsoleLine(historyLine, Math.max(0, (ts || Date.now()) - 5000))) {
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
continue;
}
historyChunks.push(historyLine);
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
addedCount++;
}
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
}
return addedCount;
} catch (err) {
console.debug("[console] Gap sync error:", err?.message || err);
return 0;
} finally {
consoleHistorySyncInFlight = false;
}
}
function scheduleConsoleHistoryResync(commandText, sentAt = Date.now()) {
if (!hasConsoleReadAccess()) return;
const baselineTs = sentAt - 250;
if (pendingConsoleHistoryResyncTimer) {
clearTimeout(pendingConsoleHistoryResyncTimer);
pendingConsoleHistoryResyncTimer = null;
}
pendingConsoleHistoryResyncTimer = window.setTimeout(async () => {
pendingConsoleHistoryResyncTimer = null;
if (remoteLogTransport === 'eventsource' && lastConsoleLiveAt >= sentAt) return;
try {
const lines = await fetchConsoleHistory(Math.max(160, Math.min(INITIAL_CONSOLE_HISTORY_LIMIT, 240)));
const historyChunks = [];
for (const item of lines) {
const ts = Number(item && item.ts) || 0;
const source = String(item && item.source || 'output');
const line = String(item && item.line || '');
if (!line) continue;
if (ts < baselineTs) continue;
// Local clear watermark: baselineTs is a client-clock bound, so a
// skewed node clock could still surface pre-clear lines here.
if (consoleClearWatermarkTs && ts && ts <= consoleClearWatermarkTs) continue;
const key = `${ts}:${source}:${line}`;
if (seenConsoleHistoryEntries.has(key)) continue;
seenConsoleHistoryEntries.add(key);
if (seenConsoleHistoryEntries.size > 1500) {
const first = seenConsoleHistoryEntries.values().next().value;
if (first) seenConsoleHistoryEntries.delete(first);
}
if (source === 'command') {
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
historyChunks.length = 0;
}
if (recentlyRenderedConsoleCommand(line, ts)) {
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
continue;
}
appendConsoleCommandLine(line, ts || Date.now());
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
continue;
}
const historyLine = line.endsWith('\n') ? line : `${line}\n`;
if (recentlySawConsoleLine(historyLine, Math.max(0, baselineTs - 5000))) {
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
continue;
}
historyChunks.push(historyLine);
if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts;
}
if (historyChunks.length) {
appendToConsole(historyChunks.join(''));
}
} catch { }
}, remoteLogTransport === 'eventsource' ? 1200 : 400);
}
consoleEl.addEventListener('scroll', () => {
userPinnedBottom = isNearBottom(consoleEl);
suppressAutoScroll = !userPinnedBottom;
updateJumpBtnVisibility();
});
function updateUrlUploaderButtonState() {
const btn = document.getElementById('urlUploaderBtn');
if (!btn) return;
const canSeeFiles = hasPerm('files_read');
const canUploadFiles = hasPerm('files_upload');
btn.classList.toggle('hidden', !canSeeFiles);
btn.classList.toggle('disabled', canSeeFiles && !canUploadFiles);
btn.disabled = canSeeFiles && !canUploadFiles;
btn.title = canUploadFiles
? 'Upload a file from a URL'
: 'File upload permission required';
}
function applyPermissionsToUI() {
if (!hasPerm('console_write')) {
if (cmdRow) cmdRow.classList.add('hidden');
}
const toggleDisabled = (selector, isDisabled) => {
document.querySelectorAll(selector).forEach(el => {
if (isDisabled) {
el.classList.add('disabled');
el.setAttribute('aria-disabled', 'true');
} else {
el.classList.remove('disabled');
el.removeAttribute('aria-disabled');
}
});
};
// Files access (taskbar button + bottom-dock item)
toggleDisabled('#filesBtn', !hasPerm('files_read'));
toggleDisabled('#dockFiles, #dockFilesBottom', !hasPerm('files_read'));
if (!hasPerm('files_upload')) {
if (uploadLabel) uploadLabel.classList.add('hidden');
if (fileUploadModal) fileUploadModal.classList.add('hidden');
}
updateUrlUploaderButtonState();
if (!hasPerm('files_create')) {
if (newBtn) newBtn.classList.add('hidden');
toggleDisabled('#dockNew', true);
if (editorSave) editorSave.classList.add('disabled');
}
toggleDisabled('#taskBtn', !hasPerm('server_start'));
toggleDisabled('#dockTask', !hasPerm('server_start'));
// Scheduler access (taskbar button + bottom-dock item)
toggleDisabled('#schedulerBtn', !hasPerm('scheduler_access'));
toggleDisabled('#dockScheduler, #dockSchedulerBottom', !hasPerm('scheduler_access'));
// Planner access (taskbar button + bottom-dock item)
toggleDisabled('#dockPlanner, #dockPlannerBottom', !hasPerm('planner_access'));
// Activity access (taskbar button + bottom-dock item, which has its own
// id since the duplicate dockActivity id was resolved)
toggleDisabled('#activityBtn', !hasPerm('activity_logs'));
toggleDisabled('#dockActivity, #dockActivityBottom', !hasPerm('activity_logs'));
// Store access (taskbar button + bottom-dock item)
toggleDisabled('#storeBtn', !hasPerm('store_access'));
toggleDisabled('#dockStore, #dockStoreBottom', !hasPerm('store_access'));
// Backups access (taskbar button + bottom-dock item)
toggleDisabled('#backupsBtn', !hasPerm('backups_view'));
toggleDisabled('#dockBackups, #dockBackupsBottom', !hasPerm('backups_view'));
// Agent access (taskbar button + bottom-dock item)
toggleDisabled('#aiHelpBtn', !hasAgentAccess());
toggleDisabled('#dockAiHelp, #dockAiHelpBottom', !hasAgentAccess());
// Reinstall access (taskbar button + bottom-dock item)
toggleDisabled('#reinstallBtn', !hasPerm('server_reinstall'));
toggleDisabled('#dockReinstall, #dockReinstallBottom', !hasPerm('server_reinstall'));
const aiHelpSettingsBtnEl = document.getElementById('aiHelpSettingsBtn');
if (aiHelpSettingsBtnEl) {
aiHelpSettingsBtnEl.classList.remove('hidden');
aiHelpSettingsBtnEl.removeAttribute('hidden');
aiHelpSettingsBtnEl.style.removeProperty('display');
aiHelpSettingsBtnEl.style.setProperty('display', 'flex', 'important');
}
updatePowerControlsInteractivity();
if (window.adpanelResizeLayout) {
window.adpanelResizeLayout();
}
}
let socketWasDisconnected = false;
socket.off("disconnect");
socket.on("disconnect", () => {
socketWasDisconnected = true;
});
socket.off("connect");
socket.on("connect", () => {
socket.emit("join", bot);
if (socketWasDisconnected) {
socketWasDisconnected = false;
if (powerState !== POWER_STATE.STOPPED) {
setTimeout(() => {
syncConsoleHistoryGap({ reason: 'socket_reconnect', limit: 350 });
}, 350);
}
}
});
socket.off("output");
socket.on("output", (data) => {
if (REMOTE_MODE && remoteLogTransport === 'eventsource') return;
if (!hasConsoleReadAccess()) return;
appendLiveConsoleLine(data, Date.now());
});
socket.off("console:reset");
socket.on("console:reset", (payload) => {
const target = String(payload && payload.server || '').trim().toLowerCase();
if (target && target !== String(bot || '').trim().toLowerCase()) return;
applyConsoleHistoryReset(Number(payload && payload.resetAt || Date.now()) || Date.now(), { resetBuffer: true });
});
socket.off("console:command");
socket.on("console:command", (payload) => {
const target = String(payload && payload.server || '').trim().toLowerCase();
if (target && target !== String(bot || '').trim().toLowerCase()) return;
// When the live console is on the EventSource transport, the command marker
// already arrives inline in that stream (appendLiveConsoleLine -> marker ->
// appendConsoleCommandLine). Handling the socket "console:command" event too
// would render the same command twice. Ignore it on EventSource, exactly
// like the "output" handler does, so there is a single source per transport.
if (REMOTE_MODE && remoteLogTransport === 'eventsource') return;
if (!hasConsoleReadAccess()) return;
const command = String(payload && payload.command || '').trim();
if (!command) return;
const ts = Number(payload && payload.ts) || Date.now();
rememberConsoleCommandEcho(command, ts);
if (recentlyRenderedConsoleCommand(command, ts)) return;
appendConsoleCommandLine(command, ts);
});
socket.off("eula:required");
socket.on("eula:required", (payload) => {
const target = String(payload && payload.server || '').trim().toLowerCase();
if (target && target !== String(bot || '').trim().toLowerCase()) return;
maybeShowEulaPopup();
});
let nodeWasOffline = false;
socket.off("nodeStatus");
socket.on("nodeStatus", (data) => {
if (!data || typeof data.nodeOnline === 'undefined') return;
const nodeOnline = data.nodeOnline !== false;
const transitioningFromOffline = (powerNodeOnline === false || nodeWasOffline) && nodeOnline;
if (!nodeOnline) {
nodeWasOffline = true;
}
powerNodeOnline = nodeOnline;
updatePowerControlsInteractivity();
setNodeOnline(nodeOnline);
// serverMissing means the node is reachable but the server no longer exists
// on it. Show the 404 overlay for that case too, but key it on a real signal
// (not a flapping connection failure) so it clears the moment the server is
// present again or is intentionally removed.
if (typeof data.serverMissing !== 'undefined') {
SERVER_MISSING = data.serverMissing === true;
}
updateOfflineState(!nodeOnline || SERVER_MISSING);
if (transitioningFromOffline) {
nodeWasOffline = false;
if (REMOTE_MODE && powerState !== POWER_STATE.STOPPED) {
attachLogStreamIfRemote({ forceReconnect: true });
}
if (powerState !== POWER_STATE.STOPPED) {
setTimeout(() => {
syncConsoleHistoryGap({ reason: 'node_reconnect', limit: 400 });
}, 400);
}
}
});
if (socket.connected) socket.emit("join", bot);
// Read-failure markers that servers used to send as if they were file content
// when a node read failed. Loading one into the editor and saving would
// overwrite the real file (server.properties etc.) with the placeholder, so
// they are never opened and never saved. Servers may also report the failure
// properly with an { error } field on the same event; both are handled here.
const EDITOR_ERROR_CONTENT_MARKERS = [
"/* ERROR: failed to load file */",
"/* ERROR: server not found on node */"
];
function isEditorErrorContent(content) {
return typeof content === "string" && EDITOR_ERROR_CONTENT_MARKERS.includes(content.trim());
}
let editorOpenGeneration = 0;
let pendingEditorRead = null;
socket.on("fileData", (d) => {
const request = pendingEditorRead;
if (!d || !request || d.path !== request.path || request.generation !== editorOpenGeneration) return;
pendingEditorRead = null;
if (d.error || isEditorErrorContent(d.content)) {
const reason = d.error ? String(d.error) : "failed to load file";
showStoreToast(`Could not load file: ${reason} — editor not opened.`, 'error', 6000);
return;
}
if (d.binary) {
refuseBinaryEditorOpen(d.path);
return;
}
openEditorModal(d.path, d.content, request);
});
async function loadServerInfo() {
if (!topoInfoPromise) topoInfoPromise = topoInfo();
const [topoRes, srvRes] = await Promise.allSettled([
topoInfoPromise.catch(() => null),
fetch(`/api/server-info/${encodeURIComponent(bot)}`, { signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS) })
.then(r => (r.ok ? r.json() : null))
.catch(() => null)
]);
const topo = topoRes.status === 'fulfilled' ? topoRes.value : null;
const srv = srvRes.status === 'fulfilled' ? srvRes.value : null;
REMOTE_MODE = !!(topo && topo.remote);
NODE_ID = (topo && topo.nodeId) || (srv && srv.nodeId) || null;
const topoInfoObj = (topo && topo.info) ? topo.info : {};
serverInfo = Object.assign({}, topoInfoObj, srv || {});
updateStoreVisibility();
}
function formatAddress(ip, port) {
if (!ip) return "";
const is6 = ip.includes(":") && !ip.includes(".");
const host = is6 ? `[${ip}]` : ip;
return port ? `${host}:${port}` : host;
}
function normalizeTemplate(t) {
const raw = (t ?? '').toString().trim().toLowerCase();
if (!raw) return '';
if (["discord", "discord-bot", "discord bot", "node", "nodejs", "python", "bot"].includes(raw)) return 'discord-bot';
if (["mc", "minecraft"].includes(raw)) return 'minecraft';
if (["fivem", "five-m", "five m", "fxserver", "cfx"].includes(raw)) return 'fivem';
return raw;
}
function templateDisplayName(t) {
const tpl = normalizeTemplate(t);
if (tpl === 'discord-bot') return 'Node.js';
if (tpl === 'minecraft') return 'Minecraft';
if (tpl === 'fivem') return 'FiveM';
return tpl || 'unknown';
}
function loadStorePreferenceMap() {
try {
const raw = localStorage.getItem(STORE_PREF_STORAGE_KEY) || '{}';
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? parsed : {};
} catch { return {}; }
}
function saveStorePreferenceMap(map) {
try { localStorage.setItem(STORE_PREF_STORAGE_KEY, JSON.stringify(map || {})); } catch { }
}
function getStorePreference() {
const map = loadStorePreferenceMap();
return map[bot] || null;
}
function setStorePreference(pref) {
const map = loadStorePreferenceMap();
if (pref) map[bot] = pref; else delete map[bot];
saveStorePreferenceMap(map);
}
async function persistStoreTemplateChoice(templateId) {
const tpl = normalizeTemplate(templateId);
if (!tpl) return false;
try {
const r = await changeServerTemplateWithActionToken(bot, tpl);
if (!r.ok) return false;
try { await loadServerInfo(); } catch { }
return true;
} catch (e) {
console.warn('Failed to persist template choice', e);
return false;
}
}
function resolveStoreTemplate() {
const tpl = serverInfo ? normalizeTemplate(serverInfo.template) : '';
if (tpl === 'discord-bot' || tpl === 'minecraft' || tpl === 'fivem') return { template: tpl, source: 'template' };
const saved = getStorePreference();
if (saved === 'discord-bot' || saved === 'minecraft' || saved === 'fivem') return { template: saved, source: 'preference' };
return { template: '', source: 'unknown' };
}
function storeTemplateQuery() {
const { template: tpl, source } = resolveStoreTemplate();
if (source === 'preference' && tpl) return `?template=${encodeURIComponent(tpl)}`;
return '';
}
function renderStorePreferenceOptions() {
if (!storePrefOptions) return;
storePrefOptions.innerHTML = '';
STORE_PREF_OPTIONS.forEach(opt => {
const card = document.createElement('button');
card.type = 'button';
card.className = 'store-pref-card';
card.dataset.storePref = opt.id;
card.innerHTML = `
${opt.title}
${opt.description}
`;
card.addEventListener('click', async () => {
setStorePreference(opt.id);
const saved = await persistStoreTemplateChoice(opt.id);
closeStorePrefModal();
updateStoreVisibility();
if (!saved) showStoreToast('Saved locally but failed to persist template for this server.', 'error');
if (pendingStoreOpen) {
pendingStoreOpen = false;
openStoreModal();
}
});
storePrefOptions.appendChild(card);
});
}
function openStorePrefModal() {
if (!storePrefModal) return;
renderStorePreferenceOptions();
showModalElement(storePrefModal);
}
function showModalElement(el, display = 'flex') {
if (!el) return;
el.classList.remove('closing');
el.style.display = display;
el.classList.add('show');
el.setAttribute('aria-hidden', 'false');
}
function afterModalPaint(callback) {
requestAnimationFrame(() => {
requestAnimationFrame(callback);
});
}
function animateClose(el, onComplete) {
if (!el) return;
if (el.classList.contains('closing')) return;
let done = false;
let fallbackTimer = null;
let handleAnimationEnd = null;
const finish = () => {
if (done) return;
done = true;
if (fallbackTimer) clearTimeout(fallbackTimer);
if (handleAnimationEnd) el.removeEventListener('animationend', handleAnimationEnd);
el.classList.remove('closing');
el.classList.remove('show');
el.style.display = 'none';
el.setAttribute('aria-hidden', 'true');
// Inline-page teardown. While body.adpanel-inline-mode is set, an open
// page is kept visible by the inline stylesheet's
// `body.adpanel-inline-mode #x.adpanel-page-active { display: flex !important; }`
// rule (bot.ejs). An inline `style.display = 'none'` LOSES to a
// stylesheet `!important`, so unless `adpanel-page-active` is also
// removed the page stays fully visible while already marked
// aria-hidden="true", and the Esc guards keyed on `.show` go dead for
// that scene. Only inline pages carry `adpanel-page-active`, so plain
// popup-mode modal closes skip this block entirely.
if (document.body.classList.contains('adpanel-inline-mode') && el.classList.contains('adpanel-page-active')) {
el.classList.remove('adpanel-page-active');
// Drop inline mode only when this was the last active page:
// showInlinePage keeps the body class while switching between pages.
if (!document.querySelector('.adpanel-page.adpanel-page-active')) {
document.body.classList.remove('adpanel-inline-mode');
// Mirror the inline script's setActiveDock(null) (bot.ejs): Esc
// closes via this path and cannot reach showConsoleView(), so the
// sidebar would otherwise keep highlighting the closed page. This
// cannot fight the inline script — showInlinePage re-adds
// adpanel-inline-mode on the next open and showConsoleView is
// idempotent (removes classes that are already gone).
document.querySelectorAll('.adpanel-taskbar-btn').forEach(btn => btn.classList.remove('is-active'));
const consoleDockBtn = document.getElementById('dockConsole');
if (consoleDockBtn) consoleDockBtn.classList.add('is-active');
// showConsoleView also hides the unified page header; without this
// the closed page's title would keep floating over the console view.
const inlinePageHeader = document.getElementById('adpanelPageHeader');
if (inlinePageHeader) inlinePageHeader.hidden = true;
// showConsoleView ends with adpanelResizeLayout(): resizeFigmaLayout
// (bot.ejs) branches on adpanel-inline-mode and writes explicit
// console/stats geometry, so dropping the body class alone leaves
// the console with stale inline-page sizing until the next resize.
if (window.adpanelResizeLayout) {
window.adpanelResizeLayout();
}
// adpanel:boot-perm-gate — this Esc/close teardown mirrors
// showConsoleView() (bot.ejs) but cannot reach it, so it must
// announce the console view too: the user LEFT the inline page a
// boot-window click was queued for, and the document-level listener
// next to the slot drops that stale queued action here exactly as
// it does for showConsoleView's own dispatch.
document.dispatchEvent(new CustomEvent(CONSOLE_VIEW_SHOWN_EVENT));
}
}
if (onComplete) onComplete();
};
el.classList.add('closing');
handleAnimationEnd = (event) => {
if (event.target === el) finish();
};
fallbackTimer = setTimeout(finish, 360);
el.addEventListener('animationend', handleAnimationEnd);
}
function closeStorePrefModal() {
if (!storePrefModal) return;
animateClose(storePrefModal, () => {
pendingStoreOpen = false;
});
}
function updateStoreVisibility() {
const btn = document.getElementById('storeBtn');
const dock = document.getElementById('dockStore');
const tabs = document.getElementById('storeTabs');
const { template: tpl } = resolveStoreTemplate();
const showForDiscord = (tpl === 'discord-bot');
const showForMinecraft = (tpl === 'minecraft');
const showForFivem = (tpl === 'fivem');
const hasExperience = !!tpl;
const showVersions = showForDiscord || showForMinecraft || showForFivem;
const showPlugins = showForMinecraft;
[btn, dock].forEach(el => { if (el) el.classList.remove('hidden'); });
if (tabs) tabs.classList.toggle('hidden', !hasExperience);
if (storeTabVersions) storeTabVersions.classList.toggle('hidden', !showVersions);
if (storeTabPlugins) storeTabPlugins.classList.toggle('hidden', !showPlugins);
if (storeSubtitle && !hasExperience) {
storeSubtitle.textContent = 'Pick what you want to browse: Node.js runtimes, Minecraft cores, or FiveM artifacts.';
}
const allowedTabs = new Set();
if (showVersions) allowedTabs.add('versions');
if (showPlugins) allowedTabs.add('plugins');
if (allowedTabs.size && !allowedTabs.has(currentStoreTab)) {
const fallbackTab = showVersions ? 'versions' : (showPlugins ? 'plugins' : currentStoreTab);
setActiveStoreTab(fallbackTab);
}
}
function setActiveStoreTab(tab) {
currentStoreTab = tab;
if (storeTabVersions) storeTabVersions.classList.toggle('active', tab === 'versions');
if (storeTabPlugins) storeTabPlugins.classList.toggle('active', tab === 'plugins');
if (storeSubtitle) {
const { template: tpl } = resolveStoreTemplate();
if (tab === 'versions') {
if (tpl === 'minecraft') {
storeSubtitle.textContent = 'Choose your core distribution and version.';
} else if (tpl === 'fivem') {
storeSubtitle.textContent = 'Choose the Linux FXServer artifact for this server.';
} else {
storeSubtitle.textContent = 'Choose the runtime/version for your bot container.';
}
} else if (tpl === 'minecraft') {
storeSubtitle.textContent = 'Browse and install plugins from Modrinth.';
} else {
storeSubtitle.textContent = '';
}
}
}
document.addEventListener('DOMContentLoaded', () => {
updateStoreVisibility();
});
async function openStoreModal() {
if (!storeModal) return;
if (!hasPerm('store_access')) { showStoreToast('You do not have permission to access the store', 'error'); return; }
const viewSeq = claimStorePanel();
if (!serverInfo) await loadServerInfo();
if (viewSeq !== storeViewSeq) return;
updateStoreVisibility();
const { template: tpl } = resolveStoreTemplate();
if (!tpl) {
pendingStoreOpen = true;
openStorePrefModal();
return;
}
showModalElement(storeModal);
setActiveStoreTab('versions');
storeContent.innerHTML = `
Loading providers...
`;
try {
const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions${storeTemplateQuery()}`);
if (viewSeq !== storeViewSeq) return;
if (!r.ok) {
storeContent.innerHTML = `
Failed to load providers (${r.status})
`;
return;
}
const data = await r.json();
if (viewSeq !== storeViewSeq) return;
const providers = Array.isArray(data.providers) ? data.providers : [];
if (!providers.length) {
storeContent.innerHTML = '
`;
}
}
function closeStoreModal() {
if (!storeModal) return;
// A version-list or providers fetch still in flight when the modal
// closes must not paint into the closing/closed panel.
claimStorePanel();
animateClose(storeModal, () => {
storeCurrentProvider = null;
});
}
function compareMcVersionsDesc(a, b) {
const pa = String(a).split('.').map(x => parseInt(x, 10) || 0);
const pb = String(b).split('.').map(x => parseInt(x, 10) || 0);
const len = Math.max(pa.length, pb.length);
for (let i = 0; i < len; i++) {
const va = typeof pa[i] === 'number' ? pa[i] : 0;
const vb = typeof pb[i] === 'number' ? pb[i] : 0;
if (va !== vb) return vb - va;
}
return 0;
}
async function fetchVanillaVersions({ includeSnapshots = false, limit = 200 } = {}) {
const MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json';
let manifest;
try {
const r = await fetch(MANIFEST);
if (!r.ok) throw new Error('manifest not ok');
manifest = await r.json();
} catch (e) {
return { versions: [] };
}
const latestReleaseId = manifest?.latest?.release || null;
const latestSnapshotId = manifest?.latest?.snapshot || null;
let list = Array.isArray(manifest?.versions) ? manifest.versions.slice() : [];
list = list.filter(v => includeSnapshots ? true : String(v.type) === 'release');
list.sort((a, b) => new Date(b.releaseTime || b.time || 0) - new Date(a.releaseTime || a.time || 0));
if (limit && Number.isFinite(limit)) list = list.slice(0, limit);
const results = [];
const concurrency = Math.min(8, Math.max(1, list.length));
let idx = 0;
async function worker() {
while (idx < list.length) {
const i = idx++;
const v = list[i];
try {
const res = await fetch(v.url);
if (!res.ok) continue;
const verMeta = await res.json();
const server = verMeta?.downloads?.server;
if (!server?.url) continue;
const mc = String(v.id);
const date = String(v.releaseTime || v.time || '').split('T')[0] || '';
const tags = [];
if (String(v.type) === 'snapshot') tags.push('snapshot'); else tags.push('release');
if (mc === latestReleaseId) tags.push('latest');
if (mc === latestSnapshotId) tags.push('latest-snapshot');
results.push({
id: mc,
name: mc,
label: `Vanilla ${mc}`,
mcVersion: mc,
releaseDate: date,
tags,
downloadUrl: server.url
});
} catch {
}
}
}
await Promise.all(Array.from({ length: concurrency }, worker));
try {
results.sort((a, b) => compareMcVersionsDesc(a.mcVersion, b.mcVersion));
} catch {
results.sort((a, b) => (b.releaseDate > a.releaseDate ? 1 : -1));
}
return { versions: results };
}
function fetchWithTimeout(url, opts = {}, ms = 8000) {
return fetch(url, { ...opts, signal: AbortSignal.timeout(ms) });
}
function compareSemverDesc(a, b) {
const pa = a.split('.').map(n => parseInt(n, 10) || 0);
const pb = b.split('.').map(n => parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const da = pa[i] ?? 0, db = pb[i] ?? 0;
if (da !== db) return db - da;
}
return 0;
}
function neoForgeToMcVersion(ver) {
const m = ver.match(/^(\d+)\.(\d+)\.(\d+)$/);
if (!m) return '';
const major = Number(m[1]);
const minor = Number(m[2]);
return `1.${major}.${minor}`;
}
async function addLastModifiedDates(list, urlFn, pool = 6, timeout = 5000) {
let idx = 0;
const workers = [];
async function worker() {
while (idx < list.length) {
const i = idx++;
const u = urlFn(list[i]);
try {
const r = await fetchWithTimeout(u, { method: 'HEAD' }, timeout);
const lm = r.headers.get('last-modified');
if (lm) list[i].releaseDate = new Date(lm).toISOString().slice(0, 10);
} catch (_) { }
}
}
for (let i = 0; i < pool; i++) workers.push(worker());
await Promise.all(workers);
}
// Shared loader for every PaperMC "Fill" v3 project (paper, velocity, waterfall,
// folia). All four share the same response shape:
// GET /projects/{project} -> { versions: { "26.2": ["26.2", ...], ... } }
// GET /projects/{project}/versions/{version}/builds
// -> [ { id, time, channel, downloads: { "server:default": { name, url } } }, ... ]
// Everything is proxied through /api/papermc/* so the required User-Agent is added
// server-side and no cross-origin/CSP handling is needed in the browser.
function extractFillDownload(build) {
const downloads = build && build.downloads;
if (!downloads) return null;
// v3 exposes the server jar under the "server:default" key.
const dl = downloads['server:default'] || downloads.application || downloads.server;
if (dl && dl.url) return dl;
if (Array.isArray(downloads)) {
const jar = downloads.find(d => d && d.url && /\.jar$/i.test(d.name || '')) || downloads.find(d => d && d.url);
if (jar) return jar;
}
return null;
}
async function fetchFillProjectVersions(project, opts = {}) {
const label = opts.label || project;
const useMcVersion = opts.mcVersion !== false;
const base = `/api/papermc/projects/${encodeURIComponent(project)}`;
let proj;
try {
const projRes = await fetch(base);
if (!projRes.ok) throw new Error(`Failed to load ${label} project`);
proj = await projRes.json().catch(() => ({}));
} catch (e) {
return { versions: [] };
}
// v3 groups versions by minor line: { "26.2": ["26.2", ...], "1.21": [...] }.
// Older/array responses are still tolerated for safety.
let versions = [];
const vobj = proj && proj.versions;
if (Array.isArray(vobj)) {
versions = vobj.map(String);
} else if (vobj && typeof vobj === 'object') {
for (const arr of Object.values(vobj)) {
if (Array.isArray(arr)) for (const v of arr) versions.push(String(v));
}
}
versions = Array.from(new Set(versions));
if (!versions.length) return { versions: [] };
versions.sort(compareMcVersionsDesc);
const results = [];
const concurrency = 8;
let idx = 0;
async function worker() {
while (idx < versions.length) {
const i = idx++;
const ver = versions[i];
try {
const buildsRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}/builds`);
if (!buildsRes.ok) continue;
const builds = await buildsRes.json().catch(() => []);
if (!Array.isArray(builds) || !builds.length) continue;
// Newest build first, then prefer a STABLE build so the store surfaces
// release jars over experimental ones.
builds.sort((a, b) => (Number(b && b.id) || 0) - (Number(a && a.id) || 0));
const stable = builds.find(b => String(b && b.channel).toUpperCase() === 'STABLE');
const build = stable || builds[0];
const dl = extractFillDownload(build);
if (!dl || !dl.url) continue;
const channel = String(build.channel || '').toLowerCase();
const entry = {
id: String(ver),
name: String(ver),
label: `${label} ${ver}`,
mcVersion: useMcVersion ? String(ver) : '',
releaseDate: (build && typeof build.time === 'string') ? build.time.split('T')[0] : '',
tags: [],
build: build.id,
downloadUrl: dl.url
};
const tags = entry.tags;
if (channel === 'stable' || channel === 'default') {
tags.push('stable');
} else if (channel === 'recommended') {
tags.push('stable', 'recommended');
} else if (channel) {
tags.push('unstable', channel);
} else {
tags.push('stable');
}
results.push(entry);
} catch (_) { }
}
}
const workers = [];
for (let i = 0; i < concurrency; i++) workers.push(worker());
await Promise.all(workers);
results.sort((a, b) => compareMcVersionsDesc(a.mcVersion || a.name, b.mcVersion || b.name));
if (results.length) {
const t = results[0].tags || (results[0].tags = []);
if (!t.includes('latest')) t.push('latest');
}
return { versions: results };
}
async function fetchPapermcVersions() {
if (papermcVersionsCache) return papermcVersionsCache;
papermcVersionsCache = await fetchFillProjectVersions('paper', { label: 'Paper' });
return papermcVersionsCache;
}
async function fetchVelocityVersions() {
// Velocity versions are proxy versions (e.g. 3.4.0), not Minecraft versions.
return await fetchFillProjectVersions('velocity', { label: 'Velocity', mcVersion: false });
}
async function fetchPurpurVersions() {
const base = '/api/purpurmc/purpur';
const dlBase = 'https://api.purpurmc.org/v2/purpur';
let proj;
try {
const res = await fetch(base);
if (!res.ok) throw new Error('Failed to load Purpur project');
proj = await res.json().catch(() => ({}));
} catch (e) {
return { versions: [] };
}
let versions = Array.isArray(proj.versions) ? proj.versions.slice() : [];
if (!versions.length) return { versions: [] };
versions.sort(compareMcVersionsDesc);
const results = [];
for (const ver of versions) {
try {
const latestRes = await fetch(`${base}/${encodeURIComponent(ver)}/latest`);
if (!latestRes.ok) continue;
const latest = await latestRes.json().catch(() => ({}));
const build = latest.build;
const time = latest.timestamp || latest.time || '';
const date = typeof time === 'string' ? time.split('T')[0] : '';
const downloadUrl = `${dlBase}/${encodeURIComponent(ver)}/${encodeURIComponent(build)}/download`;
const entry = {
id: String(ver),
name: String(ver),
label: `Purpur ${ver}`,
mcVersion: String(ver),
releaseDate: date,
tags: ['stable'],
build,
downloadUrl
};
results.push(entry);
} catch (e) { }
}
if (results.length) {
const t = results[0].tags || (results[0].tags = []);
if (!t.includes('latest')) t.push('latest');
}
return { versions: results };
}
async function fetchLeavesVersions() {
const base = 'https://api.github.com/repos/LeavesMC/Leaves/releases';
const pages = [1, 2, 3, 4, 5];
const perPage = 990;
const headers = { 'Accept': 'application/vnd.github+json' };
const chunks = await Promise.all(pages.map(async (p) => {
try {
const res = await fetch(`${base}?per_page=${perPage}&page=${p}`, { headers });
if (!res.ok) return [];
const arr = await res.json();
return Array.isArray(arr) ? arr : [];
} catch {
return [];
}
}));
const all = chunks.flat().filter(x => x && !x.draft && !x.prerelease);
all.sort((a, b) => {
const da = new Date(a.published_at || a.created_at || 0).getTime();
const db = new Date(b.published_at || b.created_at || 0).getTime();
return db - da;
});
const seen = new Set();
const out = [];
function extractMcVersionFromRelease(rel) {
const t = String(rel.tag_name || rel.name || '');
let m = t.match(/(\d+\.\d+(?:\.\d+)?)/);
if (m) return m[1];
if (Array.isArray(rel.assets)) {
for (const a of rel.assets) {
const s = String(a.name || a.browser_download_url || '');
const mm = s.match(/(\d+\.\d+(?:\.\d+)?)/);
if (mm) return mm[1];
}
}
return null;
}
function pickJarAsset(rel) {
if (!Array.isArray(rel.assets)) return { url: null, sha256: null };
let pref = rel.assets.find(a => /\.jar$/i.test(a?.name || '') &&
/leaves-\d+\.\d+(?:\.\d+)?\.jar$/i.test(a?.name || ''));
if (!pref) pref = rel.assets.find(a => /\.jar$/i.test(a?.name || ''));
if (!pref) return { url: null, sha256: null };
let sha = null;
if (typeof pref.digest === 'string' && pref.digest.startsWith('sha256:')) {
sha = pref.digest.split(':')[1];
}
return { url: pref.browser_download_url || null, sha256: sha };
}
for (const rel of all) {
const mc = extractMcVersionFromRelease(rel);
if (!mc) continue;
if (seen.has(mc)) continue;
const { url: downloadUrl, sha256 } = pickJarAsset(rel);
const releaseDate = String(rel.published_at || rel.created_at || '').split('T')[0] || '';
out.push({
id: mc,
name: mc,
label: `Leaves ${mc}`,
mcVersion: mc,
releaseDate,
tags: ['github'],
downloadUrl,
tag: rel.tag_name || '',
url: rel.html_url || '',
sha256: sha256 || null
});
seen.add(mc);
}
out.sort((a, b) => compareMcVersionsDesc(a.mcVersion, b.mcVersion));
if (out.length) {
const t = out[0].tags || (out[0].tags = []);
if (!t.includes('latest')) t.push('latest');
}
return { versions: out };
}
async function fetchNeoForgeVersions() {
const META_URL = 'https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml';
const res = await fetch(META_URL);
if (!res.ok) return { versions: [] };
const xml = await res.text();
const doc = new DOMParser().parseFromString(xml, 'application/xml');
const versions = [...doc.querySelectorAll('versioning > versions > version')]
.map(v => v.textContent.trim())
.filter(Boolean)
.sort(compareSemverDesc);
function toMcVersion(neoforgeVer) {
const m = neoforgeVer.match(/^(\d+)\.(\d+)\.(\d+)$/);
if (!m) return '';
const major = Number(m[1]);
const minor = Number(m[2]);
return `1.${major}.${minor}`;
}
async function fetchNode(url, opts = {}, timeoutMs = 3500) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const r = await fetch(url, { ...opts, signal: ctrl.signal, cache: "no-store" });
setNodeOnline(true);
return r;
} catch (e) {
setNodeOnline(false);
throw e;
} finally {
clearTimeout(t);
}
}
async function getLastModified(url) {
try {
const head = await fetch(url, { method: 'HEAD' });
const lm = head.headers.get('last-modified');
if (!lm) return '';
const d = new Date(lm);
if (isNaN(d.getTime())) return '';
return d.toISOString().slice(0, 10);
} catch {
return '';
}
}
const out = [];
for (const ver of versions) {
const mcVersion = toMcVersion(ver);
const base = `https://maven.neoforged.net/releases/net/neoforged/neoforge/${ver}/neoforge-${ver}`;
const installerUrl = `${base}-installer.jar`;
const universalUrl = `${base}-universal.jar`;
const releaseDate = await getLastModified(installerUrl);
out.push({
id: ver,
name: ver,
label: `NeoForge ${mcVersion || ver}`,
mcVersion: mcVersion || '',
releaseDate: releaseDate || '',
tags: ['stable'],
build: ver.split('.').pop() || '',
downloadUrl: installerUrl,
altDownloads: { installer: installerUrl, universal: universalUrl }
});
}
if (out[0] && !out[0].tags.includes('latest')) out[0].tags.push('latest');
return { versions: out };
function compareSemverDesc(a, b) {
const pa = a.split('.').map(n => parseInt(n, 10) || 0);
const pb = b.split('.').map(n => parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const da = pa[i] ?? 0, db = pb[i] ?? 0;
if (da !== db) return db - da;
}
return 0;
}
}
async function fetchSpigotVersions() {
const BASE = "https://api.github.com/repos/BaldGang/spigot-build/releases?per_page=1";
function compareDesc(a, b) {
const pa = String(a).split('.').map(n => parseInt(n, 10) || 0);
const pb = String(b).split('.').map(n => parseInt(n, 10) || 0);
const len = Math.max(pa.length, pb.length);
for (let i = 0; i < len; i++) {
const va = pa[i] ?? 0, vb = pb[i] ?? 0;
if (va !== vb) return vb - va;
}
return 0;
}
const cmp = (typeof compareMcVersionsDesc === "function") ? compareMcVersionsDesc : compareDesc;
try {
const res = await fetch(BASE, {
headers: { "Accept": "application/vnd.github+json" }
});
if (!res.ok) throw new Error(`GitHub API ${res.status}`);
const releases = await res.json();
if (!Array.isArray(releases) || releases.length === 0) {
return { versions: [] };
}
const rel = releases[0];
const assets = Array.isArray(rel.assets) ? rel.assets : [];
const byVersion = new Map();
for (const a of assets) {
const name = a?.name ?? "";
const m = name.match(/^spigot-(\d+\.\d+(?:\.\d+)?).jar$/i);
if (!m || !a.browser_download_url) continue;
const ver = m[1];
const rawDate = a.updated_at || a.created_at || rel.published_at || rel.created_at || "";
const dateOnly = String(rawDate).split("T")[0] || "";
const candidate = {
version: ver,
url: a.browser_download_url,
date: dateOnly,
_ts: Date.parse(a.updated_at || a.created_at || rel.published_at || rel.created_at || 0) || 0
};
const existing = byVersion.get(ver);
if (!existing || candidate._ts > existing._ts) {
byVersion.set(ver, candidate);
}
}
if (byVersion.size === 0) {
return { versions: [] };
}
const candidates = Array.from(byVersion.values())
.sort((x, y) => cmp(x.version, y.version));
const out = candidates.map((c) => ({
id: c.version,
name: c.version,
label: `SpigotMC ${c.version}`,
mcVersion: c.version,
releaseDate: c.date,
tags: ["stable"],
build: null,
downloadUrl: c.url
}));
out[0].tags = ["latest", "stable"];
return { versions: out };
} catch (e) {
console.error("fetchSpigotVersions failed:", e);
return { versions: [] };
}
}
async function fetchFoliaVersions() {
return await fetchFillProjectVersions('folia', { label: 'Folia' });
}
async function fetchWaterfallVersions() {
return await fetchFillProjectVersions('waterfall', { label: 'Waterfall' });
}
async function fetchStoreProviders() {
const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions${storeTemplateQuery()}`);
if (!res.ok) throw new Error('Failed to load providers');
const j = await res.json();
storeProvidersCache = j.providers || [];
return j;
}
async function fetchStoreVersions(providerId) {
const pid = (providerId || '').toString().toLowerCase();
// Cache-first: the panel prefetches every provider's versions daily into
// Store/{MinecraftVersions,RuntimeVersions}/ and serves them from this
// endpoint instantly. Only on a cache miss (empty list / error) do we fall
// back to resolving the versions live in the browser below.
try {
const cachedRes = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/${encodeURIComponent(providerId)}${storeTemplateQuery()}`);
if (cachedRes.ok) {
const cachedData = await cachedRes.json().catch(() => null);
if (cachedData && Array.isArray(cachedData.versions) && cachedData.versions.length) {
return cachedData;
}
}
} catch (_) { /* fall through to live fetch */ }
// Live fallback (client-side resolvers).
if (pid.includes('vanilla')) return await fetchVanillaVersions();
if (pid.includes('paper')) return await fetchPapermcVersions();
if (pid.includes('purpur')) return await fetchPurpurVersions();
if (pid.includes('velocity')) return await fetchVelocityVersions();
if (pid.includes('waterfall')) return await fetchWaterfallVersions();
if (pid.includes('folia')) return await fetchFoliaVersions();
if (pid.includes('leaves')) return await fetchLeavesVersions();
if (pid.includes('spigot')) return await fetchSpigotVersions();
const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/${encodeURIComponent(providerId)}${storeTemplateQuery()}`);
if (!res.ok) throw new Error('Failed to load provider versions');
return await res.json();
}
async function fetchPythonVersions() {
const list = document.getElementById("list");
const response = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/python${storeTemplateQuery()}`);
if (!response.ok) throw new Error('Failed to load Python versions');
const data = await response.json();
const versions = data.versions || [];
if (list) {
list.innerHTML = versions.map(v => `
${escapeHtml(v.label)}
`).join("");
}
return { versions };
}
async function loadNodeVersions() {
const list = document.getElementById("list");
const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/nodejs${storeTemplateQuery()}`);
if (!res.ok) throw new Error('Failed to load Node.js versions');
const data = await res.json();
const versions = data.versions || [];
if (list) {
list.innerHTML = versions.map(v => `
${escapeHtml(v.label)}
`).join("");
}
return { versions };
}
// One destructive store operation at a time on this page. The slot is held
// from before the confirm dialog until the whole operation (confirm + POST)
// settles, so no entry point — version row, FiveM custom field, legacy
// #list button, Modrinth install, assistant action — can race another into
// two concurrent POSTs whose every call refreshes its own one-time token
// and passes. The server-side 'reinstalling' claim on /versions/apply is
// the cross-tab/cross-worker backstop; this is the client-side first layer.
let _storeApplySlotBusy = false;
function acquireStoreApplySlot() {
if (_storeApplySlotBusy) return false;
_storeApplySlotBusy = true;
return true;
}
function releaseStoreApplySlot() {
_storeApplySlotBusy = false;
}
async function submitStoreApplyRequest(payload, opts = {}) {
const {
confirmMessage = '',
skipConfirm = false,
progressMessage = 'Applying version...',
successMessage = 'Version applied',
errorPrefix = 'Apply failed',
silentSuccess = false
} = opts;
if (!hasPerm('store_access')) throw new Error('Unauthorized');
// An upload batch owns the progress wheel while it runs: this operation's
// wheel would clobber it, and its close path could abort the batch. The
// typeof guards keep harnesses that evaluate this function without the
// upload state (tests/bot-store-confirm-guard.test.js) runnable.
const uploadBusy = (typeof uploadBatchActive === "boolean" && uploadBatchActive) ||
(typeof urlUploadInFlight === "boolean" && urlUploadInFlight);
if (uploadBusy) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
if (!acquireStoreApplySlot()) {
throw new Error('Another store install is already in progress — wait for it to finish before starting another one.');
}
try {
if (!skipConfirm && confirmMessage && !(await storeConfirm(confirmMessage))) return { cancelled: true };
storeBarStart(progressMessage);
const wheelEpoch = showProgressWheel(3, progressMessage);
try {
const response = await applyServerVersionWithActionToken(bot, payload);
const result = await response.json().catch(() => null);
if (response.status === 507 || (result && result.error === 'disk_limit_exceeded')) {
throw new Error((result && result.message) ? result.message : 'This server has exceeded its disk space limit.');
}
if (!response.ok || !result?.ok) {
throw new Error(result?.detail || result?.error || `HTTP ${response.status}`);
}
try { await loadServerInfo(); updateStoreVisibility(); } catch { }
storeBarDone(true);
if (!silentSuccess) showStoreToast(result.message || successMessage, 'success');
return result;
} catch (e) {
storeBarDone(false);
throw new Error(`${errorPrefix}: ${e?.message || e}`);
} finally {
scheduleProgressWheelHide(450, wheelEpoch);
}
} finally {
releaseStoreApplySlot();
}
}
async function changeNodeVersion(version, opts = {}) {
const payload = { providerId: 'nodejs', versionId: version };
const tpl = resolveStoreTemplate().template;
if (tpl) payload.template = tpl;
return submitStoreApplyRequest(payload, {
confirmMessage: 'Switching Node.js versions will delete all existing files on this server. Continue?',
skipConfirm: !!opts.skipConfirm,
progressMessage: `Applying Node.js ${version}...`,
successMessage: 'Node.js version changed',
errorPrefix: 'Failed to change Node.js version',
silentSuccess: !!opts.silentSuccess
});
}
async function changeVersion(version, opts = {}) {
const payload = { providerId: 'python', versionId: version };
const tpl = resolveStoreTemplate().template;
if (tpl) payload.template = tpl;
return submitStoreApplyRequest(payload, {
confirmMessage: 'Switching Python versions will delete all existing files on this server. Continue?',
skipConfirm: !!opts.skipConfirm,
progressMessage: `Applying Python ${version}...`,
successMessage: 'Python version changed',
errorPrefix: 'Failed to change Python version',
silentSuccess: !!opts.silentSuccess
});
}
async function renderStoreProvidersView(providersFromServer = null) {
if (!storeContent) return;
const viewSeq = claimStorePanel();
setActiveStoreTab('versions');
storeCurrentProvider = null;
storeContent.innerHTML = '
';
try {
const data = await fetchStoreVersions(provider.id || provider.provider || '');
// This view may have been superseded while the fetch was in flight
// (another provider opened, Versions/Plugins tab, modal closed).
// Discard instead of painting over — and installing on behalf of — a
// view the user opened later.
if (viewSeq !== storeViewSeq) return;
const versions = data.versions || [];
const providerKey = (provider.id || provider.provider || data.provider || '').toString().toLowerCase();
const isFivemProvider = providerKey === 'fivem';
const wrapper = document.createElement('div');
const header = document.createElement('div');
header.className = 'store-provider-header';
const left = document.createElement('div');
left.className = 'store-provider-header-main';
const logoWrap = document.createElement('div');
logoWrap.className = 'store-provider-logo';
if (provider.logo) {
const img = document.createElement('img');
img.src = provider.logo;
img.alt = provider.name || provider.id || '';
img.className = 'store-provider-header-logo';
logoWrap.appendChild(img);
} else {
const span = document.createElement('span');
span.className = 'store-provider-logo-placeholder';
span.textContent = (provider.name || provider.id || '?').slice(0, 2).toUpperCase();
logoWrap.appendChild(span);
}
const text = document.createElement('div');
const nameEl = document.createElement('div');
nameEl.className = 'store-provider-header-name';
nameEl.textContent = provider.name || data.displayName || provider.id;
const descEl = document.createElement('div');
descEl.className = 'store-provider-header-desc';
descEl.textContent = provider.description || data.description || '';
text.appendChild(nameEl);
text.appendChild(descEl);
left.appendChild(logoWrap);
left.appendChild(text);
const backBtn = document.createElement('button');
backBtn.type = 'button';
backBtn.className = 'store-back-btn';
backBtn.innerHTML = ' Back';
backBtn.addEventListener('click', () => renderStoreProvidersView());
header.appendChild(left);
if (!options.direct) header.appendChild(backBtn);
wrapper.appendChild(header);
const note = document.createElement('div');
note.className = 'store-note';
if (isFivemProvider) {
note.textContent = 'NOTE: This installation will delete your existing artifacts';
} else if ((provider.id || provider.provider || '').toString().toLowerCase() === 'python') {
note.textContent = 'WARNING: Switching Python runtimes will delete all existing files on this server.';
} else {
note.textContent = 'NOTE: Click on a version to install it into the server (ONE-TAP)';
}
wrapper.appendChild(note);
if (!versions.length) {
const empty = document.createElement('div');
empty.className = 'store-empty';
empty.textContent = 'No versions defined for this provider.';
wrapper.appendChild(empty);
} else {
const list = document.createElement('div');
list.className = 'store-version-list';
versions.forEach(v => {
const row = document.createElement('div');
row.className = 'store-version-row';
const meta = document.createElement('div');
meta.className = 'store-version-meta';
const vn = document.createElement('div');
vn.className = 'store-version-name';
vn.textContent = v.label || v.name || v.id;
const vs = document.createElement('div');
vs.className = 'store-version-sub';
const parts = [];
if (v.mcVersion) parts.push(`MC ${v.mcVersion}`);
if (v.artifactVersion) parts.push(v.artifactVersion);
if (v.releaseDate) parts.push(v.releaseDate);
if (!parts.length && v.name) parts.push(String(v.name));
const detail = parts.join(' • ');
vs.textContent = detail || (v.description || '');
meta.appendChild(vn);
meta.appendChild(vs);
const tags = document.createElement('div');
tags.className = 'store-version-tags';
(v.tags || []).forEach(tag => {
if (!tag) return;
const t = String(tag).toLowerCase();
const pill = document.createElement('span');
pill.className = 'pill ' + (t === 'latest' || t === 'recommended' ? 'pill-green' : 'pill-muted');
pill.textContent = t.toUpperCase();
tags.appendChild(pill);
});
row.appendChild(meta);
row.appendChild(tags);
row.addEventListener('click', async () => {
// Re-entrancy guard: this handler is async and the row is a plain
// div, so a double-click re-entered it while the first pass was
// still awaiting its confirm — the second pass then rode the same
// OK click into a second destructive install. The submit-slot
// guard inside submitStoreApplyRequest also stops that; this
// keeps the double-click on one row silent instead of surfacing
// the busy error.
if (row.dataset.installBusy === '1') return;
row.dataset.installBusy = '1';
try {
const id = v.id || v.name || v.version || '';
const label = v.label || v.name || id;
const downloadUrl = v.downloadUrl || v.url || null;
// Both paths await so the guard spans the whole operation
// (confirm dialog + POST), not just the synchronous part.
if (isFivemProvider) {
await applyVersion(provider.id || provider.provider || '', id, label, downloadUrl, { template: 'fivem' })
.catch((err) => showStoreToast(err?.message || err, 'error'));
return;
}
const { template: tpl } = resolveStoreTemplate();
if (tpl) {
const friendly = templateDisplayName(tpl);
const proceed = await storeConfirm(`Please note your server will switch to ${friendly} template, do you want to continue?`);
if (!proceed) return;
}
await applyVersion(provider.id || provider.provider || '', id, label, downloadUrl)
.catch((err) => showStoreToast(err?.message || err, 'error'));
} finally {
delete row.dataset.installBusy;
}
});
list.appendChild(row);
});
if (isFivemProvider) {
const customRow = document.createElement('div');
customRow.className = 'store-version-row store-custom-version-row';
customRow.innerHTML = `
Custom Version
Enter a build number or full artifact id.
`;
const input = customRow.querySelector('.store-custom-version-input');
const button = customRow.querySelector('.store-custom-version-btn');
const submitCustom = () => {
const version = (input?.value || '').trim();
if (!version) {
showStoreToast('Enter a FiveM artifact version first.', 'error');
return;
}
// Same re-entrancy guard as the version rows: a double-click on
// Install (or Enter while the confirm is open) must stay a single
// install attempt.
if (button.dataset.installBusy === '1') return;
button.dataset.installBusy = '1';
applyVersion(provider.id || provider.provider || '', version, `FiveM artifact ${version}`, null, { template: 'fivem' })
.catch((err) => showStoreToast(err?.message || err, 'error'))
.finally(() => { delete button.dataset.installBusy; });
};
button.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
submitCustom();
});
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
submitCustom();
}
});
list.appendChild(customRow);
}
wrapper.appendChild(list);
}
storeContent.innerHTML = '';
storeContent.appendChild(wrapper);
} catch (err) {
if (viewSeq !== storeViewSeq) return;
storeContent.innerHTML = `
Failed to load versions: ${escapeHtml(err.message || err)}
`;
}
}
function renderPluginsPlaceholder() {
if (!storeContent) return;
claimStorePanel();
setActiveStoreTab('plugins');
storeContent.innerHTML = '
Plugins management UI will live here.
';
}
function renderPluginsUI() {
if (!storeContent) return;
// Claim the panel so an in-flight provider-versions fetch cannot paint
// its list over the Plugins/Mods tab when it lands.
claimStorePanel();
setActiveStoreTab('plugins');
storeContent.innerHTML = `
`;
const searchInput = document.getElementById("mrPluginSearch");
const reloadBtn = document.getElementById("mrPluginReload");
const loadMoreBtn = document.getElementById("mrPluginLoadMore");
// Kill any pending search debounce from a previous rendering of this
// tab: the input it was going to search for no longer exists.
if (mrPluginsSearchTimer) {
clearTimeout(mrPluginsSearchTimer);
mrPluginsSearchTimer = null;
}
mrPluginsState.offset = 0;
mrPluginsState.more = true;
mrPluginsState.query = "";
// Deliberately NOT forcing loading=false here: if a load from a previous
// rendering of this tab is still in flight, loadModrinthPlugins below
// supersedes it (bumping the generation so its stale response is
// discarded) and re-runs once it unwinds.
searchInput.addEventListener("input", () => {
const q = searchInput.value.trim();
if (mrPluginsSearchTimer) clearTimeout(mrPluginsSearchTimer);
mrPluginsSearchTimer = setTimeout(() => {
mrPluginsSearchTimer = null;
mrPluginsState.query = q;
loadModrinthPlugins(true);
}, 400);
});
reloadBtn.addEventListener("click", () => {
if (mrPluginsSearchTimer) {
clearTimeout(mrPluginsSearchTimer);
mrPluginsSearchTimer = null;
}
searchInput.value = "";
mrPluginsState.query = "";
loadModrinthPlugins(true);
});
loadMoreBtn.addEventListener("click", () => {
loadModrinthPlugins(false);
});
const pluginTypeBtn = document.getElementById("mrTypePlugin");
const modTypeBtn = document.getElementById("mrTypeMod");
const setStoreProjectType = (projectType) => {
if (mrPluginsState.projectType === projectType) return;
if (mrPluginsSearchTimer) {
clearTimeout(mrPluginsSearchTimer);
mrPluginsSearchTimer = null;
}
mrPluginsState.projectType = projectType;
const activeBtn = projectType === "mod" ? modTypeBtn : pluginTypeBtn;
const inactiveBtn = projectType === "mod" ? pluginTypeBtn : modTypeBtn;
if (activeBtn) activeBtn.classList.add("active");
if (inactiveBtn) inactiveBtn.classList.remove("active");
searchInput.placeholder = projectType === "mod" ? "Search mods on Modrinth..." : "Search plugins on Modrinth...";
searchInput.value = "";
mrPluginsState.query = "";
loadModrinthPlugins(true);
};
if (pluginTypeBtn) pluginTypeBtn.addEventListener("click", () => setStoreProjectType("plugin"));
if (modTypeBtn) modTypeBtn.addEventListener("click", () => setStoreProjectType("mod"));
loadModrinthPlugins(true);
}
async function loadModrinthPlugins(reset) {
const grid = document.getElementById("mrPluginGrid");
const loadMoreBtn = document.getElementById("mrPluginLoadMore");
if (!grid) return;
if (mrPluginsState.loading) {
// At most one load is ever in flight. A fresh search (type flip, new
// query, refresh) supersedes it; paging just waits its turn.
if (reset) {
mrPluginsLoadSeq++;
mrPluginsState.pendingReset = true;
const pendingType = mrPluginsState.projectType === "mod" ? "mods" : "plugins";
grid.innerHTML = `
`;
} finally {
mrPluginsState.loading = false;
if (mrPluginsState.pendingReset) {
mrPluginsState.pendingReset = false;
loadModrinthPlugins(true);
}
}
}
function renderModrinthCard(hit, target, projectType) {
const grid = target || document.getElementById("mrPluginGrid");
if (!grid) return;
// Capture the type this card was searched under: if the user flips the
// Plugins/Mods toggle before clicking, the card must still install as
// the type of the result list it belongs to.
const cardProjectType = projectType === "mod" ? "mod" : "plugin";
const card = document.createElement("div");
card.className = "mr-plugin-card";
const icon = hit.icon_url || "";
const iconMarkup = icon
? ``
: `
`;
card.querySelector(".mr-plugin-install-btn").addEventListener("click", (ev) => {
ev.stopPropagation();
openModrinthPluginModal(hit.project_id, hit.title, cardProjectType);
});
card.addEventListener("click", () => openModrinthPluginModal(hit.project_id, hit.title, cardProjectType));
grid.appendChild(card);
}
async function openModrinthPluginModal(projectId, name, projectType) {
if (!mrPluginModal) return;
const requestedProjectId = projectId;
mrCurrentProjectId = projectId;
mrCurrentProjectType = projectType === "mod" ? "mod" : "plugin";
mrSelectedPlatform = null;
mrSelectedMcVersion = null;
mrPluginInstallBtn.disabled = true;
if (mrPluginModalTitle) mrPluginModalTitle.textContent = mrCurrentProjectType === "mod" ? "Install Mod" : "Install Plugin";
mrPluginInstallBtn.innerHTML = `${mrCurrentProjectType === "mod" ? "Install Mod" : "Install Plugin"}`;
mrPluginName.textContent = name;
const platformSelect = document.getElementById("mrPlatformSelect");
const versionSelect = document.getElementById("mrVersionSelect");
if (!platformSelect || !versionSelect) return;
platformSelect.disabled = true;
versionSelect.disabled = true;
platformSelect.innerHTML = ``;
versionSelect.innerHTML = ``;
syncCustomSelectOptions("mrPlatformSelect");
syncCustomSelectOptions("mrVersionSelect");
showModalElement(mrPluginModal);
try {
const res = await fetch(`https://api.modrinth.com/v2/project/${encodeURIComponent(projectId)}/version`);
if (mrCurrentProjectId !== requestedProjectId) return;
if (!res.ok) {
platformSelect.innerHTML = ``;
syncCustomSelectOptions("mrPlatformSelect");
} else {
const versions = await res.json();
if (mrCurrentProjectId !== requestedProjectId) return;
mrAllProjectVersions = Array.isArray(versions) ? versions : [];
populateModrinthPlatforms();
}
} catch (e) {
if (mrCurrentProjectId !== requestedProjectId) return;
platformSelect.innerHTML = ``;
syncCustomSelectOptions("mrPlatformSelect");
}
}
function closeModrinthPluginModal() {
if (!mrPluginModal) return;
const closingProjectType = mrCurrentProjectType;
mrCurrentProjectId = null;
animateClose(mrPluginModal, () => {
mrCurrentProjectId = null;
mrCurrentProjectType = "plugin";
mrAllProjectVersions = [];
mrSelectedPlatform = null;
mrSelectedMcVersion = null;
const platformSelect = document.getElementById("mrPlatformSelect");
const versionSelect = document.getElementById("mrVersionSelect");
if (platformSelect) {
platformSelect.disabled = false;
platformSelect.innerHTML = ``;
syncCustomSelectOptions("mrPlatformSelect");
}
if (versionSelect) {
versionSelect.disabled = true;
versionSelect.innerHTML = ``;
syncCustomSelectOptions("mrVersionSelect");
}
mrPluginInstallBtn.disabled = true;
mrPluginInstallBtn.classList.remove("is-loading");
mrPluginInstallBtn.innerHTML = `${closingProjectType === "mod" ? "Install Mod" : "Install Plugin"}`;
});
}
if (mrPluginModalClose) mrPluginModalClose.addEventListener("click", (event) => {
event.preventDefault();
event.stopImmediatePropagation();
closeModrinthPluginModal();
});
if (mrPluginCancel) mrPluginCancel.addEventListener("click", (event) => {
event.preventDefault();
closeModrinthPluginModal();
});
if (mrPluginModal) {
mrPluginModal.addEventListener("click", (e) => {
if (e.target === mrPluginModal) closeModrinthPluginModal();
});
}
function populateModrinthPlatforms() {
const platformSelect = document.getElementById("mrPlatformSelect");
const versionSelect = document.getElementById("mrVersionSelect");
if (!platformSelect || !versionSelect) return;
// Only offer loaders compatible with the destination: a plugin build
// goes to plugins/, a mod build to mods/, so cross-type loaders would
// produce a jar the server never loads.
const allowedLoaders = mrCurrentProjectType === "mod" ? MR_MOD_LOADERS : MR_PLUGIN_LOADERS;
const loaderSet = new Set();
(mrAllProjectVersions || []).forEach(v => {
(v.loaders || []).forEach(l => {
if (allowedLoaders.includes(l)) loaderSet.add(l);
});
});
platformSelect.innerHTML = ``;
versionSelect.innerHTML = ``;
platformSelect.disabled = false;
versionSelect.disabled = true;
mrSelectedPlatform = null;
mrSelectedMcVersion = null;
mrPluginInstallBtn.disabled = true;
if (!loaderSet.size) {
platformSelect.disabled = true;
platformSelect.innerHTML = ``;
syncCustomSelectOptions("mrPlatformSelect");
syncCustomSelectOptions("mrVersionSelect");
return;
}
Array.from(loaderSet).sort().forEach(loader => {
const opt = document.createElement('option');
opt.value = loader;
opt.textContent = loader.toUpperCase();
platformSelect.appendChild(opt);
});
syncCustomSelectOptions("mrPlatformSelect");
syncCustomSelectOptions("mrVersionSelect");
platformSelect.onchange = () => {
mrSelectedPlatform = platformSelect.value || null;
mrSelectedMcVersion = null;
mrPluginInstallBtn.disabled = true;
versionSelect.disabled = !mrSelectedPlatform;
populateModrinthVersions();
syncCustomSelectOptions("mrPlatformSelect");
syncCustomSelectOptions("mrVersionSelect");
};
versionSelect.onchange = () => {
mrSelectedMcVersion = versionSelect.value || null;
mrPluginInstallBtn.disabled = !(mrSelectedPlatform && mrSelectedMcVersion);
syncCustomSelectOptions("mrVersionSelect");
};
}
function populateModrinthVersions() {
const versionSelect = document.getElementById("mrVersionSelect");
if (!versionSelect) return;
versionSelect.innerHTML = ``;
versionSelect.disabled = !mrSelectedPlatform;
if (!mrSelectedPlatform) {
syncCustomSelectOptions("mrVersionSelect");
return;
}
const versionsSet = new Set();
(mrAllProjectVersions || []).forEach(v => {
if (!v.loaders || !v.game_versions) return;
if (!v.loaders.includes(mrSelectedPlatform)) return;
v.game_versions.forEach(gv => {
const match = String(gv).match(/^(\d+\.\d+(\.\d+)?)$/);
if (match) versionsSet.add(match[1]);
});
});
const list = Array.from(versionsSet).sort(compareMcVersionsDesc);
if (!list.length) {
versionSelect.disabled = true;
versionSelect.innerHTML = ``;
syncCustomSelectOptions("mrVersionSelect");
return;
}
versionSelect.disabled = false;
list.forEach(ver => {
const opt = document.createElement('option');
opt.value = ver;
opt.textContent = ver;
versionSelect.appendChild(opt);
});
syncCustomSelectOptions("mrVersionSelect");
}
mrPluginInstallBtn.addEventListener("click", async () => {
if (!mrCurrentProjectId || !mrSelectedPlatform || !mrSelectedMcVersion) return;
const match = (mrAllProjectVersions || []).find(v =>
v.loaders && v.game_versions &&
v.loaders.includes(mrSelectedPlatform) &&
v.game_versions.includes(mrSelectedMcVersion)
);
if (!match) {
showStoreToast("No matching Modrinth version found for this platform / Minecraft version.", 'error');
return;
}
const files = match.files || [];
const file = files.find(f => f.primary) || files[0];
if (!file || !file.url) {
showStoreToast("This Modrinth version does not expose a downloadable file.", 'error');
return;
}
const label = `${mrPluginName.textContent} (${mrSelectedPlatform.toUpperCase()} ${mrSelectedMcVersion})`;
const pluginFileName = file.filename || file.url.split('/').pop() || 'plugin.jar';
// Mirror the assistant flow's destRoot: mod builds must land in mods/,
// plugin builds in plugins/ — the loader filter above guarantees the
// selected platform matches this destination.
const destRoot = mrCurrentProjectType === "mod" ? "mods" : "plugins";
const installButtonHtml = mrPluginInstallBtn.innerHTML;
mrPluginInstallBtn.disabled = true;
mrPluginInstallBtn.classList.add("is-loading");
mrPluginInstallBtn.innerHTML = `Installing...`;
try {
await applyVersion(`modrinth-${mrCurrentProjectType}`, match.id || `${mrCurrentProjectId}-${mrSelectedPlatform}-${mrSelectedMcVersion}`, label, file.url, { destPath: `${destRoot}/${pluginFileName}` });
closeModrinthPluginModal();
} catch (e) {
showStoreToast("Failed to trigger install: " + (e && e.message ? e.message : e), 'error');
} finally {
mrPluginInstallBtn.classList.remove("is-loading");
mrPluginInstallBtn.innerHTML = installButtonHtml;
if (!mrPluginModal || !mrPluginModal.classList.contains("closing")) {
mrPluginInstallBtn.disabled = !(mrSelectedPlatform && mrSelectedMcVersion);
}
}
});
function normalizeStoreComparable(value) {
return String(value || '').toLowerCase().replace(/[^a-z0-9.]+/g, ' ').trim();
}
function buildStoreProviderAliases(provider) {
const aliases = new Set([
String(provider?.id || '').toLowerCase(),
String(provider?.name || '').toLowerCase()
]);
switch (String(provider?.id || '').toLowerCase()) {
case 'papermc':
aliases.add('paper');
aliases.add('papermc');
break;
case 'nodejs':
aliases.add('node');
aliases.add('node.js');
break;
case 'python':
aliases.add('py');
break;
default:
break;
}
return Array.from(aliases).map((alias) => alias.trim()).filter(Boolean);
}
function matchStoreProviderFromMessage(message, providers) {
const raw = String(message || '').toLowerCase();
let best = null;
for (const provider of (providers || [])) {
for (const alias of buildStoreProviderAliases(provider).sort((a, b) => b.length - a.length)) {
const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(alias)}([^a-z0-9]|$)`, 'i');
if (!pattern.test(raw)) continue;
const score = alias.length;
if (!best || score > best.score) {
best = { provider, score };
}
break;
}
}
return best ? best.provider : null;
}
function findPreferredTaggedVersion(versions) {
const list = Array.isArray(versions) ? versions : [];
if (!list.length) return null;
const preferredTags = ['recommended', 'latest', 'lts', 'stable'];
for (const tag of preferredTags) {
const match = list.find((version) =>
Array.isArray(version?.tags) &&
version.tags.some((entry) => String(entry || '').toLowerCase() === tag)
);
if (match) return match;
}
return list[0] || null;
}
function findRequestedVersionFromMessage(message, versions) {
const raw = String(message || '').toLowerCase();
const list = Array.isArray(versions) ? versions : [];
if (!list.length) return null;
const versionHints = Array.from(new Set(raw.match(/\b\d+(?:\.\d+){0,2}\b/g) || []));
let best = null;
list.forEach((version, index) => {
const candidates = [
version?.id,
version?.name,
version?.label,
version?.mcVersion
].filter(Boolean).map(normalizeStoreComparable);
const tagSet = new Set((version?.tags || []).map((entry) => String(entry || '').toLowerCase()));
let score = 0;
versionHints.forEach((hint) => {
if (candidates.some((candidate) => candidate === hint)) score += 140;
else if (candidates.some((candidate) => candidate.endsWith(` ${hint}`) || candidate.startsWith(`${hint} `) || candidate.includes(hint))) score += 70;
});
if (/\brecommended\b/.test(raw) && tagSet.has('recommended')) score += 80;
if (/\blatest\b/.test(raw) && tagSet.has('latest')) score += 80;
if (/\blts\b/.test(raw) && tagSet.has('lts')) score += 80;
if (/\bstable\b/.test(raw) && (tagSet.has('stable') || tagSet.has('recommended'))) score += 70;
if (!versionHints.length && !/\b(recommended|latest|lts|stable)\b/.test(raw)) {
return;
}
if (!best || score > best.score || (score === best.score && index < best.index)) {
best = { version, score, index };
}
});
if (best && best.score > 0) return best.version;
if (!versionHints.length) return findPreferredTaggedVersion(list);
if (list.length === 1) return list[0];
return null;
}
function detectMinecraftProjectType(message) {
const raw = String(message || '').toLowerCase();
if (/\bmods?\b/.test(raw)) return 'mod';
if (/\bplugins?\b/.test(raw)) return 'plugin';
return null;
}
function detectRequestedLoader(message, projectType) {
const raw = String(message || '').toLowerCase();
const candidates = projectType === 'mod' ? MR_MOD_LOADERS : MR_PLUGIN_LOADERS;
return candidates.find((loader) => new RegExp(`(^|[^a-z0-9])${escapeRegex(loader)}([^a-z0-9]|$)`, 'i').test(raw)) || null;
}
function detectPreferredServerLoader(projectType) {
const runtimeHint = [
serverInfo?.runtime?.providerId,
serverInfo?.start,
serverInfo?.template,
storeCurrentProvider?.id
].filter(Boolean).join(' ').toLowerCase();
if (projectType === 'mod') {
if (runtimeHint.includes('neoforge')) return 'neoforge';
if (runtimeHint.includes('forge')) return 'forge';
if (runtimeHint.includes('fabric')) return 'fabric';
if (runtimeHint.includes('quilt')) return 'quilt';
return null;
}
if (runtimeHint.includes('purpur')) return 'purpur';
if (runtimeHint.includes('spigot')) return 'spigot';
if (runtimeHint.includes('bukkit')) return 'bukkit';
if (runtimeHint.includes('velocity')) return 'velocity';
if (runtimeHint.includes('waterfall')) return 'waterfall';
if (runtimeHint.includes('folia')) return 'folia';
if (runtimeHint.includes('paper')) return 'paper';
return null;
}
function detectRequestedMinecraftVersion(message) {
const match = String(message || '').match(/\b1\.\d+(?:\.\d+)?\b/);
return match ? match[0] : null;
}
function extractRequestedProjectName(message, projectType) {
const quoted = String(message || '').match(/["'`]([^"'`]{2,120})["'`]/);
if (quoted) return quoted[1].trim();
const pattern = projectType === 'mod'
? /(?:install|add|download|setup|set up|use|put|pune|adauga|instaleaza)\s+(?:the\s+)?(?:mod(?:ul)?\s+)?(.+)/i
: /(?:install|add|download|setup|set up|use|put|pune|adauga|instaleaza)\s+(?:the\s+)?(?:plugin(?:ul)?\s+)?(.+)/i;
const match = String(message || '').match(pattern);
let candidate = match ? match[1] : '';
candidate = candidate.replace(/\b(?:for|on|pe|la|using|with)\b[\s\S]*$/i, ' ').trim();
candidate = candidate
.replace(/\b(?:paper|purpur|spigot|bukkit|velocity|waterfall|folia|fabric|forge|neoforge|quilt)\b/gi, ' ')
.replace(/\b1\.\d+(?:\.\d+)?\b/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return candidate || null;
}
async function searchModrinthProjects(query, projectType) {
const facets = encodeURIComponent(JSON.stringify([[`project_type:${projectType}`]]));
const url = `https://api.modrinth.com/v2/search?limit=8&query=${encodeURIComponent(query)}&facets=${facets}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`Modrinth search failed (${response.status})`);
const data = await response.json().catch(() => ({}));
return Array.isArray(data?.hits) ? data.hits : [];
}
async function fetchModrinthVersions(projectId) {
const response = await fetch(`https://api.modrinth.com/v2/project/${encodeURIComponent(projectId)}/version`);
if (!response.ok) throw new Error(`Modrinth versions failed (${response.status})`);
const data = await response.json().catch(() => []);
return Array.isArray(data) ? data : [];
}
function chooseModrinthSearchHit(hits, query) {
const needle = normalizeStoreComparable(query);
if (!needle) return hits[0] || null;
const exact = hits.find((hit) => {
const fields = [hit?.title, hit?.slug, hit?.project_id].filter(Boolean).map(normalizeStoreComparable);
return fields.some((field) => field === needle);
});
return exact || hits[0] || null;
}
function chooseModrinthInstallVersion(allVersions, opts = {}) {
let loader = opts.loader || null;
let mcVersion = opts.mcVersion || null;
const versions = Array.isArray(allVersions) ? allVersions : [];
const allLoaders = Array.from(new Set(
versions.flatMap((version) => Array.isArray(version?.loaders) ? version.loaders : [])
.map((entry) => String(entry || '').toLowerCase())
.filter(Boolean)
));
if (!loader) {
if (allLoaders.length === 1) loader = allLoaders[0];
else return { error: 'missing_loader', loaders: allLoaders.slice(0, 6) };
}
const loaderVersions = versions.filter((version) =>
Array.isArray(version?.loaders) &&
version.loaders.map((entry) => String(entry || '').toLowerCase()).includes(loader)
);
if (!loaderVersions.length) return { error: 'no_loader_match', loader };
const availableVersions = Array.from(new Set(
loaderVersions.flatMap((version) => Array.isArray(version?.game_versions) ? version.game_versions : [])
.map((entry) => String(entry || ''))
.filter((entry) => /^\d+\.\d+(?:\.\d+)?$/.test(entry))
)).sort(compareMcVersionsDesc);
if (!mcVersion) {
if (availableVersions.length === 1) mcVersion = availableVersions[0];
else return { error: 'missing_mc_version', loader, versions: availableVersions.slice(0, 6) };
}
const exactVersions = loaderVersions.filter((version) =>
Array.isArray(version?.game_versions) && version.game_versions.includes(mcVersion)
);
if (!exactVersions.length) return { error: 'no_version_match', loader, mcVersion, versions: availableVersions.slice(0, 6) };
exactVersions.sort((a, b) => {
if (!!b.featured !== !!a.featured) return b.featured ? 1 : -1;
const aTime = Date.parse(a?.date_published || a?.date_created || 0) || 0;
const bTime = Date.parse(b?.date_published || b?.date_created || 0) || 0;
return bTime - aTime;
});
const version = exactVersions[0];
const file = (version?.files || []).find((entry) => entry?.primary) || (version?.files || [])[0];
if (!file?.url) return { error: 'missing_file', loader, mcVersion };
return { loader, mcVersion, version, file };
}
function collectModrinthLoaders(allVersions, projectType) {
const allowedLoaders = projectType === 'mod'
? MR_MOD_LOADERS
: projectType === 'plugin'
? MR_PLUGIN_LOADERS
: MR_VALID_LOADERS;
return Array.from(new Set(
(Array.isArray(allVersions) ? allVersions : [])
.flatMap((version) => Array.isArray(version?.loaders) ? version.loaders : [])
.map((entry) => String(entry || '').toLowerCase())
.filter((entry) => allowedLoaders.includes(entry))
)).sort();
}
function collectModrinthMinecraftVersions(allVersions, loader = null) {
const normalizedLoader = loader ? String(loader).toLowerCase() : null;
return Array.from(new Set(
(Array.isArray(allVersions) ? allVersions : [])
.filter((version) => {
if (!normalizedLoader) return true;
return Array.isArray(version?.loaders) &&
version.loaders.map((entry) => String(entry || '').toLowerCase()).includes(normalizedLoader);
})
.flatMap((version) => Array.isArray(version?.game_versions) ? version.game_versions : [])
.map((entry) => String(entry || '').trim())
.filter((entry) => /^\d+\.\d+(?:\.\d+)?$/.test(entry))
)).sort(compareMcVersionsDesc);
}
function planModrinthInstallRequirements(opts = {}) {
const projectVersions = Array.isArray(opts.projectVersions) ? opts.projectVersions : [];
const availableLoaders = collectModrinthLoaders(projectVersions, opts.projectType);
const selectedLoader = opts.loader ? String(opts.loader).toLowerCase() : (availableLoaders.length === 1 ? availableLoaders[0] : null);
const availableVersions = collectModrinthMinecraftVersions(projectVersions, selectedLoader);
const selectedMcVersion = opts.mcVersion || (availableVersions.length === 1 ? availableVersions[0] : null);
const missing = [];
if (!selectedLoader) missing.push('loader');
if (!selectedMcVersion) missing.push('mcVersion');
return {
projectType: opts.projectType,
query: opts.query,
projectId: opts.projectId,
projectTitle: opts.projectTitle,
loader: selectedLoader,
mcVersion: selectedMcVersion,
missing,
availableLoaders: availableLoaders.slice(0, 6),
availableVersions: availableVersions.slice(0, 6)
};
}
function buildPendingStoreFollowUpPrompt(intent) {
const label = intent.projectTitle || intent.query || 'this project';
const loaderLabel = intent.projectType === 'mod' ? 'loader' : 'server fork and loader';
const loaderWord = intent.projectType === 'mod' ? 'loaders' : 'platforms';
const exampleLoader = intent.loader || intent.availableLoaders[0] || (intent.projectType === 'mod' ? 'fabric' : 'paper');
const exampleVersion = intent.mcVersion || intent.availableVersions[0] || '1.21.4';
const loaderList = intent.availableLoaders.length ? ` Available ${loaderWord}: ${intent.availableLoaders.join(', ')}.` : '';
const versionList = intent.availableVersions.length ? ` Available versions: ${intent.availableVersions.join(', ')}.` : '';
if (intent.missing.includes('loader') && intent.missing.includes('mcVersion')) {
return `I found **${label}**. Reply once with the ${loaderLabel} and Minecraft version, for example: ${exampleLoader} ${exampleVersion}.${loaderList}${versionList}`;
}
if (intent.missing.includes('loader')) {
return `I found **${label}**. Reply once with the ${loaderLabel}, for example: ${exampleLoader}.${loaderList}`;
}
return `I found **${label}**. Reply once with the Minecraft version for **${intent.loader}**, for example: ${exampleVersion}.${versionList}`;
}
function buildPendingModrinthFollowUpOperation(plan) {
if (!plan?.missing?.length) return null;
return {
type: 'follow_up',
source: 'modrinth',
projectType: plan.projectType,
query: plan.query,
projectId: plan.projectId,
projectTitle: plan.projectTitle,
loader: plan.loader || null,
mcVersion: plan.mcVersion || null,
missing: Array.isArray(plan.missing) ? plan.missing.slice() : [],
availableLoaders: Array.isArray(plan.availableLoaders) ? plan.availableLoaders.slice() : [],
availableVersions: Array.isArray(plan.availableVersions) ? plan.availableVersions.slice() : [],
prompt: buildPendingStoreFollowUpPrompt(plan)
};
}
async function resolveModrinthProjectOperation(opts = {}) {
const projectType = opts.projectType;
const query = String(opts.query || opts.projectTitle || '').trim();
let projectId = String(opts.projectId || '').trim();
let projectTitle = String(opts.projectTitle || query || '').trim();
if (!projectType) {
return { type: 'message', message: 'Tell me whether you want a plugin or a mod.' };
}
if (!projectId) {
if (!query) {
return { type: 'message', message: `Tell me the exact ${projectType} name you want to install.` };
}
const hits = await searchModrinthProjects(query, projectType);
const hit = chooseModrinthSearchHit(hits, query);
if (!hit?.project_id) {
return { type: 'message', message: `I could not find a Modrinth ${projectType} matching "${query}".` };
}
projectId = hit.project_id;
projectTitle = hit.title || query;
}
const projectVersions = await fetchModrinthVersions(projectId);
if (!projectVersions.length) {
return { type: 'message', message: `I found **${projectTitle || query}**, but it has no installable builds on Modrinth right now.` };
}
const plan = planModrinthInstallRequirements({
projectType,
query,
projectId,
projectTitle,
projectVersions,
loader: opts.loader,
mcVersion: opts.mcVersion
});
const followUp = buildPendingModrinthFollowUpOperation(plan);
if (followUp) return followUp;
const resolved = chooseModrinthInstallVersion(projectVersions, {
loader: plan.loader,
mcVersion: plan.mcVersion
});
if (resolved.error === 'no_loader_match') {
return buildPendingModrinthFollowUpOperation(planModrinthInstallRequirements({
projectType,
query,
projectId,
projectTitle,
projectVersions,
loader: null,
mcVersion: opts.mcVersion
})) || {
type: 'message',
message: `I found **${projectTitle || query}**, but it does not support **${resolved.loader}**.`
};
}
if (resolved.error === 'no_version_match') {
return buildPendingModrinthFollowUpOperation(planModrinthInstallRequirements({
projectType,
query,
projectId,
projectTitle,
projectVersions,
loader: resolved.loader || plan.loader,
mcVersion: null
})) || {
type: 'message',
message: `I found **${projectTitle || query}**, but not for Minecraft **${resolved.mcVersion}**.`
};
}
if (resolved.error === 'missing_file') {
return {
type: 'message',
message: `I found **${projectTitle || query}**, but the matched ${projectType} build does not expose a downloadable file.`
};
}
if (resolved.error) {
return {
type: 'message',
message: `I found **${projectTitle || query}**, but I could not match a downloadable ${projectType} build for this request.`
};
}
const fileName = resolved.file.filename || resolved.file.url.split('/').pop() || `${projectType}.jar`;
const destRoot = projectType === 'mod' ? 'mods' : 'plugins';
return {
type: 'modrinth',
projectType,
projectId,
projectTitle: projectTitle || query,
loader: resolved.loader,
mcVersion: resolved.mcVersion,
versionId: resolved.version.id || `${projectId}-${resolved.loader}-${resolved.mcVersion}`,
label: `${projectTitle || query} (${resolved.loader.toUpperCase()} ${resolved.mcVersion})`,
downloadUrl: resolved.file.url,
destPath: `${destRoot}/${fileName}`
};
}
function isLikelyStoreFollowUpAnswer(message, pending) {
if (!pending || pending.source !== 'modrinth') return false;
const raw = String(message || '').trim();
if (!raw) return false;
if (detectRequestedLoader(raw, pending.projectType)) return true;
if (detectRequestedMinecraftVersion(raw)) return true;
return (pending.availableLoaders || []).some((loader) =>
new RegExp(`(^|[^a-z0-9])${escapeRegex(loader)}([^a-z0-9]|$)`, 'i').test(raw)
);
}
async function continuePendingStoreFollowUp(message) {
if (!aiPendingStoreFollowUp || aiPendingStoreFollowUp.source !== 'modrinth') return null;
if (!isLikelyStoreFollowUpAnswer(message, aiPendingStoreFollowUp)) return null;
const loader = detectRequestedLoader(message, aiPendingStoreFollowUp.projectType) || aiPendingStoreFollowUp.loader || null;
const mcVersion = detectRequestedMinecraftVersion(message) || aiPendingStoreFollowUp.mcVersion || null;
const nextOperation = await resolveModrinthProjectOperation({
projectType: aiPendingStoreFollowUp.projectType,
query: aiPendingStoreFollowUp.query,
projectId: aiPendingStoreFollowUp.projectId,
projectTitle: aiPendingStoreFollowUp.projectTitle,
loader,
mcVersion
});
if (nextOperation?.type === 'message') {
clearPendingStoreFollowUp();
}
return nextOperation;
}
function parseAiStoreInstallCommand(spec) {
const raw = String(spec || '').trim();
if (!raw) return null;
const parts = raw.split(':').map((part) => part.trim()).filter(Boolean);
if (!parts.length) return null;
const projectName = parts[0].replace(/^["'`]+|["'`]+$/g, '').trim();
if (!projectName) return null;
let loader = null;
let mcVersion = null;
let projectType = aiPendingStoreFollowUp?.projectType || null;
parts.slice(1).forEach((part) => {
const token = String(part || '').trim().split(/\s+/)[0].replace(/[.,!?;:]+$/g, '');
const lowerToken = token.toLowerCase();
if (!token) return;
if (!mcVersion && /^\d+\.\d+(?:\.\d+)?$/.test(token)) {
mcVersion = token;
return;
}
if (!loader && MR_VALID_LOADERS.includes(lowerToken)) {
loader = lowerToken;
if (!projectType) {
projectType = MR_MOD_LOADERS.includes(lowerToken) ? 'mod' : 'plugin';
}
}
});
if (!projectType && loader) {
projectType = MR_MOD_LOADERS.includes(loader) ? 'mod' : 'plugin';
}
return {
type: 'ai_store_install',
projectName,
projectType,
loader,
mcVersion
};
}
async function resolveDirectAiStoreOperation(message) {
const raw = String(message || '').trim();
const lower = raw.toLowerCase();
if (!raw) return null;
const hasActionVerb = /\b(install|add|apply|switch|change|set|use|update|upgrade|downgrade|download|instaleaza|adauga|schimba|seteaza|pune|aplica|trece)\b/i.test(raw);
const touchesStore = /\b(store|version|runtime|container|paper|papermc|purpur|pufferfish|vanilla|spigot|velocity|waterfall|folia|leaves|node(?:\.js)?|python|fivem|fxserver|artifact|artifacts|plugin|plugins|mod|mods|modrinth)\b/i.test(raw);
if (!hasActionVerb || !touchesStore) return null;
if (!hasPerm('store_access')) {
return { type: 'message', message: 'You do not have permission to use this server store.' };
}
if (!serverInfo) {
try { await loadServerInfo(); } catch { }
}
const { template: tpl } = resolveStoreTemplate();
if (!tpl) {
return { type: 'message', message: 'Choose the Store template for this server first, then I can install versions, plugins, or mods.' };
}
const projectType = detectMinecraftProjectType(raw);
if (projectType) {
if (tpl !== 'minecraft') {
return { type: 'message', message: 'Plugins and mods are available only for Minecraft server templates.' };
}
const query = extractRequestedProjectName(raw, projectType);
const loader = detectRequestedLoader(raw, projectType) || detectPreferredServerLoader(projectType);
const mcVersion = detectRequestedMinecraftVersion(raw);
return resolveModrinthProjectOperation({
projectType,
query,
loader,
mcVersion
});
}
const providersData = await fetchStoreProviders().catch(() => null);
const providers = Array.isArray(storeProvidersCache) ? storeProvidersCache : (providersData?.providers || []);
if (!providers.length) {
return { type: 'message', message: 'I could not load the Store providers for this server.' };
}
const provider = matchStoreProviderFromMessage(raw, providers);
if (!provider) return null;
const versionData = await fetchStoreVersions(provider.id).catch(() => null);
const versions = Array.isArray(versionData?.versions) ? versionData.versions : [];
if (!versions.length) {
return { type: 'message', message: `I could not find installable versions for ${provider.name || provider.id}.` };
}
const version = findRequestedVersionFromMessage(raw, versions);
if (!version) {
const examples = versions.slice(0, 5).map((entry) => entry?.label || entry?.name || entry?.id).filter(Boolean).join(', ');
return {
type: 'message',
message: `Tell me the exact ${provider.name || provider.id} version to install. Examples: ${examples}.`
};
}
return {
type: 'version',
providerId: provider.id,
versionId: version.id || version.name || version.version || '',
label: version.label || version.name || version.id || provider.name || provider.id,
downloadUrl: version.downloadUrl || version.url || null,
template: tpl
};
}
async function executeStoreOperation(operation) {
if (!operation) return false;
if (operation.type === 'message') {
await addChatMessage('ai', operation.message);
return true;
}
try {
if (operation.type === 'follow_up') {
aiPendingStoreFollowUp = {
...operation,
missing: Array.isArray(operation.missing) ? operation.missing.slice() : [],
availableLoaders: Array.isArray(operation.availableLoaders) ? operation.availableLoaders.slice() : [],
availableVersions: Array.isArray(operation.availableVersions) ? operation.availableVersions.slice() : []
};
await addChatMessage('ai', operation.prompt || 'Tell me the missing Store details in one reply.');
return true;
}
clearPendingStoreFollowUp();
if (operation.type === 'ai_store_install') {
const candidateTypes = operation.projectType ? [operation.projectType] : ['plugin', 'mod'];
let resolved = null;
for (const candidateType of candidateTypes) {
resolved = await resolveModrinthProjectOperation({
projectType: candidateType,
query: operation.projectName,
loader: operation.loader,
mcVersion: operation.mcVersion
});
if (!resolved) continue;
if (resolved.type !== 'message' || !/could not find a modrinth/i.test(String(resolved.message || ''))) {
break;
}
}
if (!resolved) {
await addChatMessage('ai', 'I could not match that Store install request.');
return true;
}
return executeStoreOperation(resolved);
}
if (operation.type === 'version') {
await applyVersion(operation.providerId, operation.versionId, operation.label, operation.downloadUrl, {
skipConfirm: true,
silentSuccess: true,
template: operation.template
});
await addChatMessage('ai', `Installed **${operation.label}** on **${bot}**.`);
return true;
}
if (operation.type === 'modrinth') {
await applyVersion(`modrinth-${operation.projectType}`, operation.versionId, operation.label, operation.downloadUrl, {
destPath: operation.destPath,
skipConfirm: true,
silentSuccess: true,
template: 'minecraft'
});
await addChatMessage('ai', `Installed **${operation.label}** in \`${operation.destPath}\`.`);
return true;
}
} catch (err) {
clearPendingStoreFollowUp();
await addChatMessage('ai', err?.message || 'Failed to complete the Store action.');
return true;
}
return false;
}
const activityModal = document.getElementById('activityModal');
const activityModalClose = document.getElementById('activityModalClose');
const activityList = document.getElementById('activityList');
const activitySearchInput = document.getElementById('activitySearchInput');
const activityLoadMore = document.getElementById('activityLoadMore');
let activityData = [];
let activityOffset = 0;
// In-flight guard + generation counter for loadActivityLogs. Without them a
// double-click on "Load More" fetches the same offset twice (every entry of
// that page is appended twice and activityOffset jumps past a page that is
// then never shown), and reopening the modal while an append is still in
// flight lets the stale page splice itself into the freshly reset list.
let activityLoading = false;
let activityLoadSeq = 0;
const ACTIVITY_LIMIT = 50;
let activityFilter = 'all';
// Transient end-of-list row for a failed "Load More" (append) request.
// Reuses the modal's existing activity-empty styling so it needs no new CSS.
function showActivityAppendError() {
// Never stack rows when retries keep failing.
const existing = activityList.querySelector('.activity-append-error');
if (existing) existing.remove();
const row = document.createElement('div');
row.className = 'activity-empty activity-append-error';
row.innerHTML = '
Failed to load older activity. Click "Load More" to retry.
';
activityList.appendChild(row);
}
async function loadActivityLogs(append = false) {
// An append while a load is already running is ignored: the in-flight
// request is fetching exactly the offset this click would ask for again.
// Fresh loads are never ignored — a later load supersedes an earlier one
// through activityLoadSeq below.
if (activityLoading && append) return;
// Appends inherit the current generation (their response is discarded if a
// fresh load started while they were in flight); fresh loads open a new
// generation, silently abandoning any request still outstanding.
const seq = append ? activityLoadSeq : ++activityLoadSeq;
activityLoading = true;
if (!append) {
activityOffset = 0;
activityData = [];
activityList.innerHTML = '
Loading activity...
';
}
// Same plain disabled-flag idiom the other busy buttons in this file use
// (backupCreateConfirm, sendBtn, ...): also stops the double-click at the
// control itself instead of only in this guard.
if (activityLoadMore) activityLoadMore.disabled = true;
try {
const res = await fetch(`/api/server/${encodeURIComponent(bot)}/activity?offset=${activityOffset}&limit=${ACTIVITY_LIMIT}`);
if (!res.ok) throw new Error('Failed to load activity');
const data = await res.json();
// A newer fresh load superseded this one (modal reopened while an append
// was in flight): discard the stale response entirely rather than splice
// its page into the new list or advance activityOffset past a page that
// would then never be shown.
if (seq !== activityLoadSeq) return;
const entries = Array.isArray(data.entries) ? data.entries : [];
activityData = append ? [...activityData, ...entries] : entries;
// Offset only advances for accepted responses so a discarded page stays
// fetchable by the next accepted request.
activityOffset += entries.length;
// renderActivityList rebuilds the list from activityData, which also
// clears a transient append-error row left by a previously failed load.
renderActivityList();
if (activityLoadMore) {
activityLoadMore.style.display = entries.length < ACTIVITY_LIMIT ? 'none' : 'flex';
}
} catch (err) {
if (seq !== activityLoadSeq) return;
console.error('Activity load error:', err);
if (!append) {
activityList.innerHTML = '
Failed to load activity logs
';
} else {
// Append failed: keep the 50+ already-rendered entries and surface the
// failure as a transient row at the end of the list instead of wiping
// the whole audit trail the user is scrolled into.
showActivityAppendError();
}
} finally {
// Only the load that still owns the generation may release the shared
// state; a superseded load must not re-enable Load More or clear
// activityLoading while the newer load is still running.
if (seq === activityLoadSeq) {
activityLoading = false;
if (activityLoadMore) activityLoadMore.disabled = false;
}
}
}
function formatActivityActionLabel(entry) {
const action = String(entry && entry.action || 'unknown');
if (action === 'console_command') return 'Sent command';
return action.replace(/_/g, ' ');
}
function formatActivityDetails(entry) {
const details = entry && entry.details;
const action = String(entry && entry.action || '').toLowerCase();
if (!details) return '';
if (action === 'console_command' && typeof details === 'object' && details.command) {
const source = details.source ? ` (${String(details.source)})` : '';
return `Command${source}: ${String(details.command)}`;
}
return typeof details === 'string' ? details : JSON.stringify(details);
}
function renderActivityList() {
const query = (activitySearchInput?.value || '').toLowerCase();
let filtered = activityData.filter(e => {
if (activityFilter !== 'all') {
const action = String(e.action || '').toLowerCase();
if (activityFilter === 'power' && !['start', 'stop', 'restart', 'kill', 'run'].some(a => action.includes(a))) return false;
if (activityFilter === 'console' && !action.includes('command')) return false;
if (activityFilter === 'file' && !['file', 'upload', 'delete', 'rename', 'create', 'extract'].some(a => action.includes(a))) return false;
}
if (query) {
const text = `${e.user || ''} ${e.ip || ''} ${e.action || ''} ${JSON.stringify(e.details || '')}`.toLowerCase();
if (!text.includes(query)) return false;
}
return true;
});
if (filtered.length === 0) {
activityList.innerHTML = '
No activity found
';
return;
}
activityList.innerHTML = filtered.map(e => {
const ts = e.ts ? new Date(e.ts).toLocaleString() : '—';
const action = escapeHtml(formatActivityActionLabel(e));
const user = escapeHtml(e.user || 'unknown');
const ip = escapeHtml(e.ip || '');
const details = escapeHtml(formatActivityDetails(e));
let icon = 'fa-circle-info';
const actionLower = String(e.action || action).toLowerCase();
if (actionLower.includes('start') || actionLower.includes('run')) icon = 'fa-play';
else if (actionLower.includes('stop') || actionLower.includes('kill')) icon = 'fa-stop';
else if (actionLower.includes('restart')) icon = 'fa-rotate';
else if (actionLower.includes('command')) icon = 'fa-terminal';
else if (actionLower.includes('file') || actionLower.includes('upload') || actionLower.includes('delete')) icon = 'fa-file';
let iconType = 'console';
if (actionLower.includes('start') || actionLower.includes('run')) iconType = 'start';
else if (actionLower.includes('kill')) iconType = 'kill';
else if (actionLower.includes('stop')) iconType = 'stop';
else if (actionLower.includes('restart')) iconType = 'restart';
else if (actionLower.includes('file') || actionLower.includes('upload') || actionLower.includes('delete')) iconType = 'file';
return `
${action}
${details ? `
${details}
` : ''}
${user} ${ts}${ip ? ` ${ip}` : ''}
`;
}).join('');
}
function openActivityModal() {
if (!activityModal) return;
if (!hasPerm('activity_logs')) { alert('You do not have permission to view activity logs'); return; }
showModalElement(activityModal);
afterModalPaint(() => loadActivityLogs());
}
function closeActivityModal() {
if (!activityModal) return;
animateClose(activityModal);
}
if (activityModalClose) activityModalClose.addEventListener('click', closeActivityModal);
if (activitySearchInput) activitySearchInput.addEventListener('input', () => renderActivityList());
if (activityLoadMore) activityLoadMore.addEventListener('click', () => loadActivityLogs(true));
document.querySelectorAll('#activityModal .activity-pill').forEach(pill => {
pill.addEventListener('click', () => {
document.querySelectorAll('#activityModal .activity-pill').forEach(p => p.classList.remove('active'));
pill.classList.add('active');
activityFilter = pill.dataset.filter || 'all';
renderActivityList();
});
});
const backupsModal = document.getElementById('backupsModal');
const backupsModalClose = document.getElementById('backupsModalClose');
const backupsList = document.getElementById('backupsList');
const backupsCreateBtn = document.getElementById('backupsCreateBtn');
const backupsRefreshBtn = document.getElementById('backupsRefreshBtn');
const backupCreateModal = document.getElementById('backupCreateModal');
const backupCreateClose = document.getElementById('backupCreateClose');
const backupCreateCancel = document.getElementById('backupCreateCancel');
const backupCreateConfirm = document.getElementById('backupCreateConfirm');
const backupNameInput = document.getElementById('backupNameInput');
const backupDescInput = document.getElementById('backupDescInput');
// Generation counter for loadBackups, same pattern as activityLoadSeq above:
// keeps an overlapping refresh (e.g. an AI backups_updated reload racing a
// manual Refresh click) from rendering the older snapshot last.
let backupsLoadSeq = 0;
// In-flight guard for restoreBackup/deleteBackup, same idea as the
// activityLoading flag: a second click while one of these one-time-token
// requests is already running is ignored instead of firing a parallel
// duplicate (createBackup already guards itself via its disabled button).
let backupOpInFlight = false;
async function loadBackups() {
if (!backupsList) return;
// Fresh generation per load, exactly like activityLoadSeq in
// loadActivityLogs: every load opens a new generation, so if a newer load
// starts while this one is in flight, this response is discarded instead
// of rendering its older snapshot last.
const seq = ++backupsLoadSeq;
backupsList.innerHTML = '
Loading backups...
';
if (backupsRefreshBtn) backupsRefreshBtn.classList.add('is-loading');
try {
// adpanel:backups-fetch-bound — keep the deadline through the JSON body,
// not just until the response headers arrive.
const res = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/backups`, { signal: AbortSignal.timeout(15000) });
if (!res.ok) throw new Error('Failed to load backups');
const data = await res.json();
if (seq !== backupsLoadSeq) return;
const backups = Array.isArray(data.backups) ? data.backups : [];
renderBackupsList(backups);
} catch (err) {
if (seq !== backupsLoadSeq) return;
console.error('Backups load error:', err);
// An aborted (timed-out) fetch lands here with the browser's opaque
// abort message — the rendered text stays the same plain failure
// message the !res.ok path uses, so it can never surface (same
// AbortError-to-plain-text handling as the scheduler loader's catch).
backupsList.innerHTML = '
Failed to load backups
';
} finally {
// Only the load that still owns the generation may release the shared
// spinner state; a superseded load must not un-spin a newer one.
if (seq === backupsLoadSeq && backupsRefreshBtn) backupsRefreshBtn.classList.remove('is-loading');
}
}
function renderBackupsList(backups) {
if (!backups || backups.length === 0) {
const hint = hasPerm('backups_create') ? 'Create your first backup to protect your server data' : 'No backups available';
backupsList.innerHTML = `
`;
}).join('');
backupsList.querySelectorAll('.backup-action-btn.restore').forEach(btn => {
btn.addEventListener('click', () => restoreBackup(btn.dataset.id));
});
backupsList.querySelectorAll('.backup-action-btn.delete').forEach(btn => {
btn.addEventListener('click', () => deleteBackup(btn.dataset.id));
});
}
function formatBytes(bytes) {
if (!bytes || bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
async function createBackup() {
if (!hasPerm('backups_create')) {
alert('You do not have permission to create backups.');
return;
}
const name = backupNameInput?.value?.trim() || 'Backup';
const description = backupDescInput?.value?.trim() || '';
if (backupCreateConfirm) {
backupCreateConfirm.disabled = true;
backupCreateConfirm.innerHTML = ' Creating...';
}
try {
const res = await fetchWithServerActionToken(`/api/nodes/server/${encodeURIComponent(bot)}/backups`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, description })
}, 'backupCreate');
if (!res.ok) {
const err = await res.json().catch(() => ({}));
if (res.status === 507 || err.error === 'disk_limit_exceeded') {
throw new Error(err.message || 'This server has exceeded its disk space limit. Delete files to free space before creating a backup.');
}
// Panel-side pre-create cap refusal (adpanel:backup-count-cap): surface
// the server's actionable detail, not the raw error code — same
// structured-body precedence as the 507 branch above. The daemon's 409
// (backup op already in flight) carries a different error code and
// keeps falling through to the generic branch below.
if (res.status === 409 && err.error === 'backup_cap_reached') {
throw new Error(err.detail || 'This server has reached its backup limit. Delete backups to make room (requires the backups_delete permission).');
}
throw new Error(err.error || 'Failed to create backup');
}
closeBackupCreateModal();
loadBackups();
if (backupsModalIsActive()) alert('Backup created successfully!');
} catch (err) {
if (backupsModalIsActive()) alert('Failed to create backup: ' + (err.message || err));
} finally {
if (backupCreateConfirm) {
backupCreateConfirm.disabled = false;
backupCreateConfirm.innerHTML = 'Create Backup';
}
}
}
async function restoreBackup(id) {
if (!id) return;
// Same client-side pre-check as createBackup/deleteBackup: without it a
// backups_view-only user would burn a failed token roundtrip and see the
// raw ACTION_TOKEN_INVALID alert instead of a permission message.
if (!hasPerm('backups_create')) {
alert('You do not have permission to restore backups.');
return;
}
// One restore at a time (guard shared with deleteBackup): a double-click
// must not burn a second one-time token in parallel with the first. The
// flag is only set after confirm() and always cleared in finally, so a
// cancelled confirm or a failed request can never leave it stuck.
if (backupOpInFlight) return;
if (!confirm('Restore this backup? The server will stop and its current files will be replaced.')) return;
backupOpInFlight = true;
try {
// Restore replaces every server file: one-time token, freshly minted
// per call (refreshBefore) so a stale modal can never replay a burned
// nonce — same contract as the file-delete/reinstall flows. The JSON
// body's deleteOldFiles:true is what makes the daemon wipe post-backup
// files before copying the backup in (its default is merge-mode when no
// body is sent), matching the confirm dialog's "files will be replaced"
// promise above.
const res = await fetchWithServerActionToken(`/api/nodes/server/${encodeURIComponent(bot)}/backups/${encodeURIComponent(id)}/restore`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ deleteOldFiles: true })
}, 'backupRestore', { refreshBefore: true });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
if (res.status === 507 || err.error === 'disk_limit_exceeded') {
throw new Error(err.message || 'This server has exceeded its disk space limit. Delete files to free space before restoring a backup.');
}
throw new Error(err.error || 'Failed to restore backup');
}
if (backupsModalIsActive()) alert('Backup restored successfully. The server remains stopped.');
loadBackups();
} catch (err) {
if (backupsModalIsActive()) alert('Failed to restore backup: ' + (err.message || err));
} finally {
backupOpInFlight = false;
}
}
async function deleteBackup(id) {
if (!id) return;
if (!hasPerm('backups_delete')) {
alert('You do not have permission to delete backups.');
return;
}
// One delete at a time: same shared guard as restoreBackup, set only
// after confirm() and always cleared in finally so it can never stick.
if (backupOpInFlight) return;
if (!confirm('Are you sure you want to delete this backup? This cannot be undone.')) return;
backupOpInFlight = true;
try {
// Deleting a backup is unrecoverable: one-time token, freshly minted
// per call — same contract as restore above.
// adpanel:backups-delete-fetch-bound — a stalled delete response must
// not hold backupOpInFlight (the silent Restore/Delete guard) until the
// browser kills the socket. Bounded at 360000 = the relay's own 330000
// delete budget (the daemon's 5m backupDeleteCallerWaitBudget + 30s
// slack, nodes.js) plus the same 30s slack again, so the bound can
// never abort a legitimate delete. Create/restore stay
// exemption-list-unbounded by doctrine (minutes-long daemon jobs).
const res = await fetchWithServerActionToken(`/api/nodes/server/${encodeURIComponent(bot)}/backups/${encodeURIComponent(id)}`, { method: 'DELETE' }, 'backupDelete', { refreshBefore: true, timeoutMs: 360000 });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Failed to delete backup');
}
loadBackups();
} catch (err) {
if (backupsModalIsActive()) {
// The delete may still complete server-side after the client times out.
const message = err?.name === 'AbortError' || err?.name === 'TimeoutError' ? 'Request timed out. Refresh the list to check whether it completed.' : (err.message || err);
alert('Failed to delete backup: ' + message);
}
} finally {
backupOpInFlight = false;
}
}
function openBackupsModal() {
if (!backupsModal) return;
if (!hasPerm('backups_view')) {
alert('You do not have permission to view backups.');
return;
}
showModalElement(backupsModal);
if (backupsCreateBtn) {
if (!hasPerm('backups_create')) {
backupsCreateBtn.style.display = 'none';
} else {
backupsCreateBtn.style.display = '';
}
}
afterModalPaint(() => loadBackups());
}
function closeBackupsModal() {
if (!backupsModal) return;
animateClose(backupsModal);
}
// Same .show predicate the other modal guards use (schedulerModalIsActive,
// filesModalIsActive, isEulaPopupVisible): completion alerts only fire
// while the backups scene is still on screen — a request outliving a
// closed modal must not popup an alert over whatever the user opened next.
// adpanel:backups-alert-scene-guard — the anchor is the scene container
// #backupsModal, never #backupCreateModal: the create modal is a SIBLING
// overlay (bot.ejs renders it outside #backupsModal) and createBackup
// closes it BEFORE alerting success, so a create-modal predicate would
// suppress every success alert. .show is added by openBackupsModal's
// showModalElement on every open in BOTH modes (inline mode opens pages
// through the dock trigger, which runs this same open function) and
// stripped by every close/switch-away path (animateClose.finish,
// showInlinePage's per-page strip) — the same both-modes open marker the
// AI backups_updated relay checks before reloading this scene.
function backupsModalIsActive() {
return !!(backupsModal && backupsModal.classList.contains('show'));
}
function openBackupCreateModal() {
if (!backupCreateModal) return;
if (backupNameInput) backupNameInput.value = '';
if (backupDescInput) backupDescInput.value = '';
showModalElement(backupCreateModal);
}
function closeBackupCreateModal() {
if (!backupCreateModal) return;
animateClose(backupCreateModal);
}
if (backupsModalClose) backupsModalClose.addEventListener('click', closeBackupsModal);
if (backupsCreateBtn) backupsCreateBtn.addEventListener('click', openBackupCreateModal);
if (backupsRefreshBtn) backupsRefreshBtn.addEventListener('click', loadBackups);
if (backupCreateClose) backupCreateClose.addEventListener('click', closeBackupCreateModal);
if (backupCreateCancel) backupCreateCancel.addEventListener('click', closeBackupCreateModal);
if (backupCreateConfirm) backupCreateConfirm.addEventListener('click', createBackup);
const schedulerModal = document.getElementById('schedulerModal');
const schedulerModalClose = document.getElementById('schedulerModalClose');
const schedulerTasksList = document.getElementById('schedulerTasksList');
const schedulerRefreshBtn = document.getElementById('schedulerRefreshBtn');
const schedulerCreateBtn = document.getElementById('schedulerCreateBtn');
const schedulerTabs = document.querySelectorAll('.scheduler-tab');
const schedulerTasksTab = document.getElementById('schedulerTasksTab');
const schedulerCreateTab = document.getElementById('schedulerCreateTab');
const schedulerStatusIndicator = document.getElementById('schedulerStatusIndicator');
const schedulerTaskName = document.getElementById('schedulerTaskName');
const schedulerScheduleOptions = document.querySelectorAll('.scheduler-schedule-option');
const schedulerOnceSection = document.getElementById('schedulerOnceSection');
const schedulerRecurringSection = document.getElementById('schedulerRecurringSection');
const schedulerDate = document.getElementById('schedulerDate');
const schedulerTime = document.getElementById('schedulerTime');
const schedulerRecurringType = document.getElementById('schedulerRecurringType');
const schedulerSecondsConfig = document.getElementById('schedulerSecondsConfig');
const schedulerMinutesConfig = document.getElementById('schedulerMinutesConfig');
const schedulerHourlyConfig = document.getElementById('schedulerHourlyConfig');
const schedulerDailyConfig = document.getElementById('schedulerDailyConfig');
const schedulerWeeklyConfig = document.getElementById('schedulerWeeklyConfig');
const schedulerSecondsInterval = document.getElementById('schedulerSecondsInterval');
const schedulerMinutesInterval = document.getElementById('schedulerMinutesInterval');
const schedulerHourlyInterval = document.getElementById('schedulerHourlyInterval');
const schedulerDailyTime = document.getElementById('schedulerDailyTime');
const schedulerWeeklyDay = document.getElementById('schedulerWeeklyDay');
const schedulerWeeklyTime = document.getElementById('schedulerWeeklyTime');
const schedulerActionType = document.getElementById('schedulerActionType');
const schedulerActionConsole = document.getElementById('schedulerActionConsole');
const schedulerActionServerControl = document.getElementById('schedulerActionServerControl');
const schedulerActionFile = document.getElementById('schedulerActionFile');
const schedulerActionBackup = document.getElementById('schedulerActionBackup');
const schedulerActionPlanner = document.getElementById('schedulerActionPlanner');
const schedulerActionAgentPrompt = document.getElementById('schedulerActionAgentPrompt');
const schedulerCommand = document.getElementById('schedulerCommand');
const schedulerServerControlText = document.getElementById('schedulerServerControlText');
const schedulerFilePath = document.getElementById('schedulerFilePath');
const schedulerFileContent = document.getElementById('schedulerFileContent');
const schedulerBackupName = document.getElementById('schedulerBackupName');
const schedulerBackupDesc = document.getElementById('schedulerBackupDesc');
const schedulerPlannerRefreshBtn = document.getElementById('schedulerPlannerRefreshBtn');
const schedulerPlannerPromptPreview = document.getElementById('schedulerPlannerPromptPreview');
const schedulerAgentPrompt = document.getElementById('schedulerAgentPrompt');
const schedulerAiModelSelector = document.getElementById('schedulerAiModelSelector');
const schedulerAiModelSelect = document.getElementById('schedulerAiModelSelect');
const schedulerAiModelTrigger = document.getElementById('schedulerAiModelTrigger');
const schedulerAiModelCurrent = document.getElementById('schedulerAiModelCurrent');
const schedulerAiModelOptions = document.getElementById('schedulerAiModelOptions');
let schedulerCurrentScheduleType = 'once';
let schedulerPlannerPreviewLoading = false;
let schedulerCreateInFlight = false;
let pendingSchedulerCreate = null;
let schedulerTasksLoadSeq = 0;
let schedulerStatusLoadSeq = 0;
let schedulerAiModelPopulateSeq = 0;
let schedulerDeleteInFlight = false;
function localDateInputValue(date = new Date()) {
const pad = (n) => String(n).padStart(2, '0');
return `${String(date.getFullYear()).padStart(4, '0')}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
// adpanel:scheduler-action-perm-mirror — the create route enforces
// per-action permissions server-side (index.js
// schedulerRequiredPermissionForAction, applied at create time by
// POST /api/scheduler/:serverName/tasks: a missing perm answers 403 "no
// permission to schedule actions" AFTER the user filled the whole
// form), so this form must offer only actions the user can actually submit.
// This object is the exact client-side mirror of that map, evaluated with
// hasPerm against the PERMS payload /permissions already delivers (admins
// pass inside hasPerm). The server check stays authoritative — this only
// keeps the UI truthful; keep both maps in lockstep.
const SCHEDULER_ACTION_REQUIRED_PERM = {
console_command: 'console_write',
server_start: 'server_start',
server_stop: 'server_stop',
create_file: 'files_create',
modify_file: 'files_write',
backup: 'backups_create',
planner_next_to_agent: 'planner_access',
agent_prompt: 'scheduler_access'
};
// Marks every action-type option whose mapped perm the user lacks as
// opt.hidden (syncCustomSelectOptions then keeps it out of the custom
// dropdown), shows the inline warning when NO action is available, and —
// when the currently selected action became unavailable — falls back to the
// first allowed action (or '' when none is, which keeps the form
// non-submittable via createSchedulerTask's existing actionType guard; no
// fake action is ever invented). Returns true when it had to rebase the
// selection, so the caller can run the existing config-update path.
function applySchedulerActionPermGating() {
const schedulerActionPermWarning = document.getElementById('schedulerActionPermWarning');
if (!schedulerActionType) return false;
let selectionUnavailable = false;
Array.from(schedulerActionType.options).forEach(opt => {
if (!opt.value) return; // the "Select an action..." placeholder stays
const required = Object.prototype.hasOwnProperty.call(SCHEDULER_ACTION_REQUIRED_PERM, opt.value)
? SCHEDULER_ACTION_REQUIRED_PERM[opt.value]
: null;
const allowed = (!required || hasPerm(required)) && (!['planner_next_to_agent', 'agent_prompt'].includes(opt.value) || hasAgentAccess());
if (!allowed && opt.selected) selectionUnavailable = true;
opt.hidden = !allowed;
});
syncCustomSelectOptions('schedulerActionType');
const firstAllowed = Array.from(schedulerActionType.options).find(opt => opt.value && !opt.hidden) || null;
if (schedulerActionPermWarning) {
schedulerActionPermWarning.classList.toggle('hidden', !!firstAllowed);
}
if (!selectionUnavailable) return false;
schedulerActionType.value = firstAllowed ? firstAllowed.value : '';
syncCustomSelectOptions('schedulerActionType');
return true;
}
function openSchedulerModal() {
if (!schedulerModal) return;
if (!hasPerm('scheduler_access')) {
alert('You do not have permission to access the scheduler.');
return;
}
showModalElement(schedulerModal);
afterModalPaint(() => {
loadSchedulerTasks();
checkSchedulerStatus();
});
if (schedulerDate && !schedulerDate.value) {
schedulerDate.value = localDateInputValue();
}
const createTab = document.querySelector('.scheduler-tab[data-tab="create"]');
if (createTab) {
if (!hasPerm('scheduler_create')) {
createTab.style.display = 'none';
} else {
createTab.style.display = '';
}
}
// adpanel:scheduler-action-perm-mirror — re-derive option visibility on
// every open (PERMS may have refreshed since the last open) and keep the
// form coherent when a retained selection was knocked out: the fallback
// runs the existing config-update path so the shown config section always
// matches the effective action.
if (applySchedulerActionPermGating()) {
updateActionConfig();
}
}
function closeSchedulerModal() {
if (!schedulerModal) return;
animateClose(schedulerModal);
}
// Same .show predicate the other modal guards use (filesModalIsActive,
// isEulaPopupVisible): completion alerts only fire while the scheduler
// scene is still on screen — a request outliving a closed modal must not
// popup an alert over whatever the user opened next.
function schedulerModalIsActive() {
return !!(schedulerModal && schedulerModal.classList.contains('show'));
}
async function loadSchedulerTasks() {
if (!schedulerTasksList) return;
const seq = ++schedulerTasksLoadSeq;
schedulerTasksList.innerHTML = '
Loading tasks...
';
if (schedulerRefreshBtn) {
schedulerRefreshBtn.classList.add('spinning');
}
try {
// adpanel:scheduler-fetch-bound — bounded like checkSchedulerStatus so a
// stalled response cannot leave "Loading tasks..." and a spinning
// refresh button up forever; the abort lands in the catch below.
const res = await fetchWithTimeout(`/api/scheduler/${encodeURIComponent(bot)}/tasks`, {}, 15000);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Failed to load tasks');
}
const data = await res.json();
if (seq !== schedulerTasksLoadSeq) return;
renderSchedulerTasks(data.tasks || [], data.recurring || []);
} catch (err) {
if (seq !== schedulerTasksLoadSeq) return;
console.error('Scheduler tasks load error:', err);
// An aborted (timed-out) fetch carries the browser's opaque abort
// message — show the same plain failure text the !res.ok path uses
// (same AbortError-name branch style as the agent-run catch).
const message = err?.name === 'AbortError' || err?.name === 'TimeoutError' ? 'Failed to load tasks' : (err.message || 'Failed to load tasks');
schedulerTasksList.innerHTML = '
`;
}).join('');
if (canDelete) {
schedulerTasksList.querySelectorAll('.scheduler-task-delete').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
deleteSchedulerTask(btn.dataset.id);
});
});
}
}
function getActionIcon(actionType) {
const icons = {
'console_command': '',
'server_start': '',
'server_stop': '',
'create_file': '',
'modify_file': '',
'backup': '',
'planner_next_to_agent': '',
'agent_prompt': ''
};
return icons[actionType] || '';
}
function closeSchedulerAiModelDropdown() {
if (!schedulerAiModelSelector || !schedulerAiModelTrigger) return;
schedulerAiModelSelector.classList.remove('open');
schedulerAiModelTrigger.setAttribute('aria-expanded', 'false');
schedulerAiModelOptions?.setAttribute('aria-hidden', 'true');
}
// adpanel:scheduler-model-locality — this selector's choice is per-task form
// state: it flows ONLY into the agent_prompt create payload
// (createSchedulerTask sends payload.provider/model; the server route
// normalizes + validates that explicit selection and deliberately never
// touches the saved default). It must NOT route through
// saveSelectedAiModelToStorage — that writer owns the ACCOUNT-GLOBAL
// default the interactive agent chat uses and every future
// planner_next_to_agent schedule binds at create time, so persisting a
// one-off cheap model here would silently retarget them.
function updateSchedulerAiModelSelectorState() {
if (!schedulerAiModelSelect || !schedulerAiModelCurrent || !schedulerAiModelOptions) return;
const selectedOption = schedulerAiModelSelect.selectedOptions?.[0] || schedulerAiModelSelect.options[schedulerAiModelSelect.selectedIndex] || null;
schedulerAiModelCurrent.textContent = selectedOption?.textContent || 'Select model...';
const selectedValue = schedulerAiModelSelect.value;
schedulerAiModelOptions.querySelectorAll('.ai-model-option').forEach(optionEl => {
const isSelected = optionEl.dataset.value === selectedValue;
optionEl.classList.toggle('selected', isSelected);
optionEl.setAttribute('aria-selected', isSelected ? 'true' : 'false');
});
}
function syncSchedulerAiModelSelectorFromNative() {
if (!schedulerAiModelSelect || !schedulerAiModelTrigger || !schedulerAiModelOptions || !schedulerAiModelCurrent || !schedulerAiModelSelector) return;
closeSchedulerAiModelDropdown();
schedulerAiModelOptions.innerHTML = '';
let hasSelectableOptions = false;
const appendModelOption = (option) => {
if (!option) return;
if (option.disabled) {
if (!option.value) {
const emptyState = document.createElement('div');
emptyState.className = 'ai-model-empty';
emptyState.textContent = option.textContent;
schedulerAiModelOptions.appendChild(emptyState);
}
return;
}
hasSelectableOptions = true;
const optionButton = document.createElement('button');
optionButton.type = 'button';
optionButton.className = 'ai-model-option';
optionButton.dataset.value = option.value;
optionButton.setAttribute('role', 'option');
optionButton.setAttribute('aria-selected', 'false');
optionButton.innerHTML = `
${escapeHtml(option.textContent)}
`;
schedulerAiModelOptions.appendChild(optionButton);
};
Array.from(schedulerAiModelSelect.children).forEach(child => {
const tagName = child.tagName?.toUpperCase();
if (tagName === 'OPTGROUP') {
const groupLabel = document.createElement('div');
groupLabel.className = 'ai-model-group';
groupLabel.textContent = child.label;
schedulerAiModelOptions.appendChild(groupLabel);
Array.from(child.children).forEach(appendModelOption);
} else if (tagName === 'OPTION') {
appendModelOption(child);
}
});
schedulerAiModelTrigger.disabled = !hasSelectableOptions;
schedulerAiModelSelector.classList.toggle('is-disabled', !hasSelectableOptions);
schedulerAiModelOptions.setAttribute('aria-hidden', schedulerAiModelSelector.classList.contains('open') ? 'false' : 'true');
updateSchedulerAiModelSelectorState();
}
async function populateSchedulerAiModelSelector() {
if (!schedulerAiModelSelect) return;
// Seq guard (same pattern as schedulerTasksLoadSeq): selecting the agent
// action re-triggers this populate, and an older slower run must not
// wipe the select or re-apply a stale selection after a newer one.
const seq = ++schedulerAiModelPopulateSeq;
const backendSelectedModel = await loadSelectedAiModelFromBackend().catch(() => '');
if (seq !== schedulerAiModelPopulateSeq) return;
const previouslySelectedModel = backendSelectedModel || loadSelectedAiModelFromStorage();
const keys = await loadAiKeysFromBackend();
if (seq !== schedulerAiModelPopulateSeq) return;
schedulerAiModelSelect.innerHTML = '';
syncSchedulerAiModelSelectorFromNative();
let hasOptions = false;
const results = await Promise.all(Object.entries(AI_PROVIDERS).map(async ([providerId, config]) => {
if (!keys[providerId]) return null;
const models = await fetchModels(providerId);
return { providerId, name: config.name, models };
}));
if (seq !== schedulerAiModelPopulateSeq) return;
schedulerAiModelSelect.innerHTML = '';
for (const result of results) {
if (!result || !result.models.length) continue;
const optgroup = document.createElement('optgroup');
optgroup.label = result.name;
for (const model of result.models) {
const opt = document.createElement('option');
opt.value = encodeAiModelSelection(result.providerId, model);
opt.textContent = model;
optgroup.appendChild(opt);
}
schedulerAiModelSelect.appendChild(optgroup);
hasOptions = true;
}
if (!hasOptions) {
schedulerAiModelSelect.innerHTML = '';
} else {
const optionValues = Array.from(schedulerAiModelSelect.options).map((option) => option.value);
if (previouslySelectedModel && optionValues.includes(previouslySelectedModel)) {
schedulerAiModelSelect.value = previouslySelectedModel;
} else {
schedulerAiModelSelect.selectedIndex = 0;
}
}
syncSchedulerAiModelSelectorFromNative();
}
async function loadSchedulerPlannerPreview() {
if (!schedulerPlannerPromptPreview || schedulerPlannerPreviewLoading) return;
schedulerPlannerPreviewLoading = true;
if (schedulerPlannerRefreshBtn) schedulerPlannerRefreshBtn.classList.add('spinning');
schedulerPlannerPromptPreview.value = 'Loading next planner prompt...';
try {
const { nextPrompt } = await plannerRequest('?view=next');
schedulerPlannerPromptPreview.value = String(nextPrompt || '').trim() || 'No planner prompt is eligible to run yet.';
} catch (err) {
// Never render the server's raw error string ("access denied") into the
// preview. A 401 already raised the session-expired overlay in
// plannerRequest — surface the same message it showed, no alert on top.
if (err.isPlannerAuthError) {
schedulerPlannerPromptPreview.value = 'Your session has expired. Please sign in again.';
} else if (err.status === 403) {
schedulerPlannerPromptPreview.value = 'You need Planner access to use this action.';
} else {
schedulerPlannerPromptPreview.value = 'Failed to load the planner prompt. Please try again.';
}
} finally {
schedulerPlannerPreviewLoading = false;
if (schedulerPlannerRefreshBtn) schedulerPlannerRefreshBtn.classList.remove('spinning');
}
}
async function deleteSchedulerTask(taskId) {
if (!taskId) return;
if (!hasPerm('scheduler_delete')) {
alert('You do not have permission to delete schedules');
return;
}
// One delete at a time, same guard pattern as backupOpInFlight in the
// backups scene: set only after confirm() and always cleared in finally
// so a cancelled confirm or a failed request can never leave it stuck.
// adpanel:scheduler-delete-inflight-cue — the guard is fleet-wide (it
// blocks a delete of ANY task, and a mid-flight refresh re-renders fresh
// enabled buttons), so a click landing while it is held must say so
// instead of silently dropping: alert + return, still BEFORE confirm()
// so a refused delete can never even open a second dialog.
if (schedulerDeleteInFlight) {
alert('A delete is already in progress — please wait.');
return;
}
if (!confirm('Are you sure you want to delete this scheduled task?')) return;
schedulerDeleteInFlight = true;
// adpanel:scheduler-delete-inflight-cue — mirror the create path's
// in-flight affordance (schedulerCreateBtn disabled + "Creating..."):
// every rendered delete button is disabled for the whole flight so the
// concurrent click is a dead control, not a silent no-op. Same list
// selector the click handlers bind through (renderSchedulerTasks), so
// there is exactly one definition of "the delete buttons". The restore
// in the finally RE-QUERIES instead of holding node references: after a
// success loadSchedulerTasks() has already swapped the list to
// "Loading tasks..." synchronously (its prologue runs before its first
// await), so the captured nodes would be detached — a re-query restores
// only what is still in the DOM and the fresh re-render ships enabled;
// after a failure the same nodes are still there and get re-enabled.
if (schedulerTasksList) {
schedulerTasksList.querySelectorAll('.scheduler-task-delete').forEach(btn => {
btn.disabled = true;
});
}
try {
// The delete route gates on the session-bound schedulerDelete token;
// it is repeatable but short-lived, so refresh-before avoids a
// guaranteed first-use 403 after the 300s TTL. Bounded via
// opts.timeoutMs (adpanel:scheduler-fetch-bound): a stalled response
// must not hold schedulerDeleteInFlight — the disabled delete buttons —
// until the browser kills the socket.
const res = await fetchWithServerActionToken(`/api/scheduler/${encodeURIComponent(bot)}/tasks/${encodeURIComponent(taskId)}`, {
method: 'DELETE'
}, 'schedulerDelete', { refreshBefore: true, timeoutMs: 20000 });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Failed to delete task');
}
loadSchedulerTasks();
} catch (err) {
if (schedulerModalIsActive()) alert('Failed to delete task: ' + (err.message || err));
} finally {
schedulerDeleteInFlight = false;
// adpanel:scheduler-delete-inflight-cue — release the affordance with
// the guard: re-query (never a captured NodeList) so the post-success
// re-render case is a no-op over an already-swapped list, not a write
// to detached nodes.
if (schedulerTasksList) {
schedulerTasksList.querySelectorAll('.scheduler-task-delete').forEach(btn => {
btn.disabled = false;
});
}
}
}
async function createSchedulerTask() {
if (schedulerCreateInFlight) return;
if (!hasPerm('scheduler_create')) {
alert('You do not have permission to create schedules');
return;
}
const name = schedulerTaskName?.value?.trim() || '';
const actionType = schedulerActionType?.value;
if (!actionType) {
alert('Please select an action type');
return;
}
// Set before the first await so a second click during the model save or
// the create request cannot submit twice; always cleared in the finally.
schedulerCreateInFlight = true;
let scheduleType, scheduleValue, scheduleTime, scheduledTimestamp;
let payload = {};
try {
if (schedulerCurrentScheduleType === 'once') {
scheduleType = 'once';
const dateVal = schedulerDate?.value;
const timeVal = schedulerTime?.value || '00:00';
if (!dateVal) {
alert('Please select a date');
return;
}
const localRunAt = new Date(`${dateVal}T${timeVal}`);
scheduledTimestamp = localRunAt.getTime();
// adpanel:scheduler-nan-timestamp — reject malformed dates before the future check.
if (!Number.isFinite(scheduledTimestamp)) {
alert('Please enter a valid date and time');
return;
}
const [requestedHour, requestedMinute] = timeVal.split(':').map(Number);
if (localDateInputValue(localRunAt) !== dateVal || localRunAt.getHours() !== requestedHour || localRunAt.getMinutes() !== requestedMinute) {
alert('That date and time does not exist in your local time zone. Please choose another time.');
return;
}
} else {
const recurringType = schedulerRecurringType?.value || 'seconds';
scheduleType = recurringType;
if (recurringType === 'seconds') {
scheduleValue = schedulerSecondsInterval?.value || '30';
} else if (recurringType === 'minutes') {
scheduleValue = schedulerMinutesInterval?.value || '5';
} else if (recurringType === 'hourly') {
scheduleValue = schedulerHourlyInterval?.value || '1';
} else if (recurringType === 'daily') {
scheduleTime = schedulerDailyTime?.value || '00:00';
} else if (recurringType === 'weekly') {
scheduleValue = schedulerWeeklyDay?.value || '0';
scheduleTime = schedulerWeeklyTime?.value || '00:00';
}
}
// Client-side mirror of the server's create-time 5-minute floors for
// the disk/AI-heavy actions: fail before the round-trip so the user
// fixes the interval instead of learning about it from a 400. The
// server check stays authoritative. daily/weekly (like once) are
// inherently above the floor; hourly scales into it only via a
// fractional value the selects never produce.
if (scheduleType !== 'once' && (actionType === 'backup' || actionType === 'planner_next_to_agent' || actionType === 'agent_prompt')) {
let recurrenceSeconds = Infinity;
if (scheduleType === 'seconds') recurrenceSeconds = parseInt(scheduleValue, 10);
else if (scheduleType === 'minutes') recurrenceSeconds = parseInt(scheduleValue, 10) * 60;
else if (scheduleType === 'hourly') recurrenceSeconds = parseInt(scheduleValue, 10) * 3600;
if (recurrenceSeconds < 300) {
alert(actionType === 'backup'
? 'backup tasks must run at most every 5 minutes'
: 'agent prompt tasks must run at most every 5 minutes');
return;
}
}
if (actionType === 'console_command') {
const command = schedulerCommand?.value?.trim();
if (!command) {
alert('Please enter a command');
return;
}
payload.command = command;
} else if (actionType === 'create_file' || actionType === 'modify_file') {
const filePath = schedulerFilePath?.value?.trim();
if (!filePath) {
alert('Please enter a file path');
return;
}
payload.filePath = filePath;
payload.content = schedulerFileContent?.value || '';
} else if (actionType === 'backup') {
payload.backupName = schedulerBackupName?.value?.trim() || 'Scheduled Backup';
payload.description = schedulerBackupDesc?.value?.trim() || '';
} else if (actionType === 'planner_next_to_agent') {
if (!hasAgentAccess()) {
alert('You do not have permission to access ' + BRAND_NAME + ' Agent.');
return;
}
// Mirrors the server's schedule-save validation: planner_access on top
// of the agent-access check (index.js schedulerRequiredPermissionForAction).
if (!hasPerm('planner_access')) {
alert('You do not have permission to access the planner.');
return;
}
const schedulerModelValue = String(aiModelSelect?.value || '').trim();
if (schedulerModelValue) payload.selection = schedulerModelValue;
} else if (actionType === 'agent_prompt') {
if (!hasAgentAccess()) {
alert('You do not have permission to access ' + BRAND_NAME + ' Agent.');
return;
}
const prompt = schedulerAgentPrompt?.value?.trim() || '';
if (!prompt) {
alert('Please enter the prompt for ' + BRAND_NAME + ' Agent.');
schedulerAgentPrompt?.focus();
return;
}
const modelValue = schedulerAiModelSelect?.value || '';
const { providerId, modelName } = decodeAiModelSelection(modelValue);
if (!providerId || !modelName) {
alert('Please select an AI model.');
return;
}
payload.prompt = prompt;
payload.provider = providerId;
payload.model = modelName;
}
const editWarning = schedulerModal?.dataset.agentAutoEditWarning;
const autoApproveFileEdits = !!editWarning && (actionType === 'planner_next_to_agent' || actionType === 'agent_prompt');
// Send the browser's timezone so the server evaluates cron schedules in the user's timezone.
// The create route gates on the session-bound schedulerCreate token;
// it is repeatable but short-lived, so refresh-before avoids a
// guaranteed first-use 403 after the 300s TTL. Bounded via
// opts.timeoutMs (adpanel:scheduler-fetch-bound): a stalled response
// must not hold schedulerCreateInFlight and the "Creating..." button
// until the browser kills the socket.
const body = JSON.stringify({
name: name || `${actionType} task`,
actionType,
payload,
...(autoApproveFileEdits && { autoApproveFileEdits: true }),
scheduleType,
scheduleValue,
scheduleTime,
scheduledTimestamp,
timezone: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch { return ''; } })()
});
if (scheduleType === 'once' && scheduledTimestamp <= Date.now() && pendingSchedulerCreate?.body !== body) {
alert('Scheduled time must be in the future');
return;
}
if (schedulerCreateBtn) {
schedulerCreateBtn.disabled = true;
schedulerCreateBtn.innerHTML = ' Creating...';
}
if (autoApproveFileEdits && !(await storeConfirm(`Create this Agent schedule? ${editWarning} This applies to every run.`))) return;
if (scheduleType === 'once' && pendingSchedulerCreate?.body !== body) {
pendingSchedulerCreate = { body, key: createCommandRequestId() };
}
const res = await fetchWithServerActionToken(`/api/scheduler/${encodeURIComponent(bot)}/tasks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(scheduleType === 'once' && { 'Idempotency-Key': pendingSchedulerCreate.key })
},
body
}, 'schedulerCreate', { refreshBefore: true, timeoutMs: 20000 });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Failed to create task');
}
pendingSchedulerCreate = null;
switchSchedulerTab('tasks');
resetSchedulerForm();
if (schedulerModalIsActive()) alert('Task created successfully!');
} catch (err) {
if (schedulerModalIsActive()) alert('Failed to create task: ' + (err.message || err));
} finally {
schedulerCreateInFlight = false;
if (schedulerCreateBtn) {
schedulerCreateBtn.disabled = false;
schedulerCreateBtn.innerHTML = ' Create Task';
}
}
}
function resetSchedulerForm() {
if (schedulerTaskName) schedulerTaskName.value = '';
if (schedulerCommand) schedulerCommand.value = '';
if (schedulerFilePath) schedulerFilePath.value = '';
if (schedulerFileContent) schedulerFileContent.value = '';
if (schedulerBackupName) schedulerBackupName.value = '';
if (schedulerBackupDesc) schedulerBackupDesc.value = '';
if (schedulerAgentPrompt) schedulerAgentPrompt.value = '';
if (schedulerActionType) {
schedulerActionType.value = '';
syncCustomSelectOptions('schedulerActionType');
}
if (schedulerRecurringType) {
schedulerRecurringType.value = 'seconds';
syncCustomSelectOptions('schedulerRecurringType');
schedulerRecurringType.dispatchEvent(new Event('change'));
}
if (schedulerSecondsInterval) {
schedulerSecondsInterval.value = '30';
syncCustomSelectOptions('schedulerSecondsInterval');
}
if (schedulerMinutesInterval) {
schedulerMinutesInterval.value = '5';
syncCustomSelectOptions('schedulerMinutesInterval');
}
if (schedulerHourlyInterval) {
schedulerHourlyInterval.value = '1';
syncCustomSelectOptions('schedulerHourlyInterval');
}
if (schedulerWeeklyDay) {
schedulerWeeklyDay.value = '0';
syncCustomSelectOptions('schedulerWeeklyDay');
}
switchScheduleType('once');
if (schedulerDate) schedulerDate.value = localDateInputValue();
if (schedulerTime) schedulerTime.value = '00:00';
if (schedulerDailyTime) schedulerDailyTime.value = '00:00';
if (schedulerWeeklyTime) schedulerWeeklyTime.value = '00:00';
hideAllActionConfigs();
}
function switchSchedulerTab(tabName) {
schedulerTabs.forEach(tab => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
if (schedulerTasksTab) schedulerTasksTab.classList.toggle('hidden', tabName !== 'tasks');
if (schedulerCreateTab) schedulerCreateTab.classList.toggle('hidden', tabName !== 'create');
if (tabName === 'tasks') {
loadSchedulerTasks();
}
}
function switchScheduleType(type) {
schedulerCurrentScheduleType = type;
schedulerScheduleOptions.forEach(opt => {
opt.classList.toggle('active', opt.dataset.schedule === type);
});
if (schedulerOnceSection) schedulerOnceSection.classList.toggle('hidden', type !== 'once');
if (schedulerRecurringSection) schedulerRecurringSection.classList.toggle('hidden', type !== 'recurring');
}
function updateRecurringConfig() {
const type = schedulerRecurringType?.value || 'seconds';
if (schedulerSecondsConfig) schedulerSecondsConfig.classList.toggle('hidden', type !== 'seconds');
if (schedulerMinutesConfig) schedulerMinutesConfig.classList.toggle('hidden', type !== 'minutes');
if (schedulerHourlyConfig) schedulerHourlyConfig.classList.toggle('hidden', type !== 'hourly');
if (schedulerDailyConfig) schedulerDailyConfig.classList.toggle('hidden', type !== 'daily');
if (schedulerWeeklyConfig) schedulerWeeklyConfig.classList.toggle('hidden', type !== 'weekly');
}
function hideAllActionConfigs() {
[schedulerActionConsole, schedulerActionServerControl, schedulerActionFile, schedulerActionBackup, schedulerActionPlanner, schedulerActionAgentPrompt].forEach(el => {
if (el) el.classList.add('hidden');
});
}
function updateActionConfig() {
hideAllActionConfigs();
// adpanel:scheduler-action-perm-mirror — re-derive before reading the
// value so every change event evaluates against the current perms; a
// selection knocked out by the map falls back here too and the path below
// runs on the effective value (return ignored on purpose).
applySchedulerActionPermGating();
const action = schedulerActionType?.value;
if ((action === 'planner_next_to_agent' || action === 'agent_prompt') && !hasAgentAccess()) {
alert('You do not have permission to access ' + BRAND_NAME + ' Agent.');
if (schedulerActionType) schedulerActionType.value = '';
syncCustomSelectOptions('schedulerActionType');
return;
}
// The server gates every planner route behind planner_access (the schedule
// save separately re-checks agent access), so this action needs BOTH
// permissions — selecting it would otherwise die at the preview request.
if (action === 'planner_next_to_agent' && !hasPerm('planner_access')) {
alert('You do not have permission to access the planner.');
if (schedulerActionType) schedulerActionType.value = '';
syncCustomSelectOptions('schedulerActionType');
return;
}
if (action === 'console_command' && schedulerActionConsole) {
schedulerActionConsole.classList.remove('hidden');
} else if ((action === 'server_start' || action === 'server_stop') && schedulerActionServerControl) {
schedulerActionServerControl.classList.remove('hidden');
if (schedulerServerControlText) {
schedulerServerControlText.textContent = action === 'server_start'
? 'The server will be started at the scheduled time.'
: 'The server will be stopped at the scheduled time.';
}
} else if ((action === 'create_file' || action === 'modify_file') && schedulerActionFile) {
schedulerActionFile.classList.remove('hidden');
} else if (action === 'backup' && schedulerActionBackup) {
schedulerActionBackup.classList.remove('hidden');
} else if (action === 'planner_next_to_agent' && schedulerActionPlanner) {
schedulerActionPlanner.classList.remove('hidden');
loadSchedulerPlannerPreview().catch((err) => console.error('[scheduler] Planner preview error:', err));
} else if (action === 'agent_prompt' && schedulerActionAgentPrompt) {
schedulerActionAgentPrompt.classList.remove('hidden');
populateSchedulerAiModelSelector().catch((err) => console.error('[scheduler] Model selector error:', err));
}
}
async function checkSchedulerStatus() {
// adpanel:scheduler-status-seq — a slow/timed-out status response from a
// previous modal open must not overwrite a newer verdict, same guard as
// the tasks loader (schedulerTasksLoadSeq).
const seq = ++schedulerStatusLoadSeq;
try {
// Bounded so a hung /status request cannot leave the indicator stuck
// between "Checking status…" and a verdict; an abort lands in the
// catch below as "Scheduler Status Unknown".
const res = await fetchWithTimeout('/api/scheduler/status', {}, 10000);
if (!res.ok) throw new Error('Status check failed');
const data = await res.json();
if (seq !== schedulerStatusLoadSeq) return;
if (schedulerStatusIndicator) {
const dot = schedulerStatusIndicator.querySelector('.scheduler-status-dot');
const text = schedulerStatusIndicator.querySelector('.scheduler-status-text');
if (data.available) {
if (dot) dot.classList.remove('offline');
if (data.queue) {
const pendingCount = (data.queue?.waiting || 0) + (data.queue?.delayed || 0);
if (text) text.textContent = `Scheduler Ready (${pendingCount} pending, ${data.queue?.active || 0} active)`;
} else {
if (text) text.textContent = 'Scheduler Ready';
}
} else {
if (dot) dot.classList.add('offline');
if (text) {
if (!data.redisConfigured) {
text.textContent = 'Scheduler Offline (REDIS_URL not configured)';
} else {
text.textContent = 'Scheduler Offline (Connection error)';
}
}
}
}
} catch (err) {
console.error('Scheduler status check failed:', err);
if (seq !== schedulerStatusLoadSeq) return;
if (schedulerStatusIndicator) {
const dot = schedulerStatusIndicator.querySelector('.scheduler-status-dot');
const text = schedulerStatusIndicator.querySelector('.scheduler-status-text');
if (dot) dot.classList.add('offline');
if (text) text.textContent = 'Scheduler Status Unknown';
}
}
}
if (schedulerModalClose) schedulerModalClose.addEventListener('click', closeSchedulerModal);
if (schedulerRefreshBtn) schedulerRefreshBtn.addEventListener('click', loadSchedulerTasks);
if (schedulerCreateBtn) schedulerCreateBtn.addEventListener('click', createSchedulerTask);
schedulerTabs.forEach(tab => {
tab.addEventListener('click', () => switchSchedulerTab(tab.dataset.tab));
});
schedulerScheduleOptions.forEach(opt => {
opt.addEventListener('click', () => switchScheduleType(opt.dataset.schedule));
});
if (schedulerRecurringType) {
schedulerRecurringType.addEventListener('change', updateRecurringConfig);
}
if (schedulerActionType) {
schedulerActionType.addEventListener('change', updateActionConfig);
}
if (schedulerPlannerRefreshBtn) {
schedulerPlannerRefreshBtn.addEventListener('click', () => {
loadSchedulerPlannerPreview().catch((err) => console.error('[scheduler] Planner preview refresh error:', err));
});
}
if (schedulerAiModelTrigger) {
schedulerAiModelTrigger.addEventListener('click', (e) => {
e.stopPropagation();
if (schedulerAiModelTrigger.disabled) return;
const willOpen = !schedulerAiModelSelector?.classList.contains('open');
closeSchedulerAiModelDropdown();
if (willOpen && schedulerAiModelSelector) {
schedulerAiModelSelector.classList.add('open');
schedulerAiModelTrigger.setAttribute('aria-expanded', 'true');
schedulerAiModelOptions?.setAttribute('aria-hidden', 'false');
}
});
}
if (schedulerAiModelOptions && schedulerAiModelSelect) {
const handleSchedulerAiModelOptionSelect = (optionButton) => {
if (!optionButton) return;
if (!schedulerAiModelSelector?.classList.contains('open')) return;
const nextValue = optionButton.dataset.value || '';
if (!nextValue) return;
schedulerAiModelSelect.value = nextValue;
schedulerAiModelSelect.dispatchEvent(new Event('change', { bubbles: true }));
updateSchedulerAiModelSelectorState();
closeSchedulerAiModelDropdown();
schedulerAiModelTrigger?.focus();
};
schedulerAiModelOptions.addEventListener('pointerdown', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
e.preventDefault();
handleSchedulerAiModelOptionSelect(optionButton);
});
schedulerAiModelOptions.addEventListener('click', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
handleSchedulerAiModelOptionSelect(optionButton);
});
}
if (schedulerAiModelSelect) {
schedulerAiModelSelect.addEventListener('change', () => updateSchedulerAiModelSelectorState());
}
document.addEventListener('click', (e) => {
if (!e.target.closest('#schedulerAiModelSelector')) {
closeSchedulerAiModelDropdown();
}
});
if (schedulerModal) {
schedulerModal.addEventListener('click', (e) => {
if (e.target === schedulerModal || e.target.classList.contains('scheduler-glass-layer')) {
closeSchedulerModal();
}
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && schedulerModal?.classList.contains('show')) {
closeSchedulerModal();
}
if (e.key === 'Escape') {
const clearModal = document.getElementById('clearConsoleModal');
if (typeof closeClearConsoleModal === 'function' && clearModal && clearModal.style.display !== 'none') {
closeClearConsoleModal();
} else if (clearModal && clearModal.style.display !== 'none') {
clearModal.style.display = 'none';
}
}
});
const plannerModal = document.getElementById('plannerModal');
const plannerModalClose = document.getElementById('plannerModalClose');
const plannerRefreshBtn = document.getElementById('plannerRefreshBtn');
const plannerTabs = document.querySelectorAll('.planner-tab');
const plannerBoardTab = document.getElementById('plannerBoardTab');
const plannerComposeTab = document.getElementById('plannerComposeTab');
const plannerSummary = document.getElementById('plannerSummary');
const plannerActiveList = document.getElementById('plannerActiveList');
const plannerCompletedSection = document.getElementById('plannerCompletedSection');
const plannerCompletedList = document.getElementById('plannerCompletedList');
const plannerOpenComposeBtn = document.getElementById('plannerOpenComposeBtn');
const plannerItemIdInput = document.getElementById('plannerItemId');
const plannerTitleInput = document.getElementById('plannerTitleInput');
const plannerPromptInput = document.getElementById('plannerPromptInput');
const plannerResetBtn = document.getElementById('plannerResetBtn');
const plannerSaveBtn = document.getElementById('plannerSaveBtn');
const plannerStatusIndicator = document.getElementById('plannerStatusIndicator');
const plannerEditIndicator = document.getElementById('plannerEditIndicator');
const plannerEditIndicatorTitle = document.getElementById('plannerEditIndicatorTitle');
const plannerEditCancelBtn = document.getElementById('plannerEditCancelBtn');
const PLANNER_API_BASE = `/api/servers/${encodeURIComponent(bot)}/planner`;
// adpanel:planner-send-completion — the completion poll's wall-clock budget:
// it must cover the SERVER's job deadline (AI_AGENT_JOB_MAX_RUNTIME_MS,
// default 20 min, env-clamped 2–120) PLUS the serial-queue wait behind up to
// 500 pending jobs, with margin. The former fixed 90-attempt cap (~3.6 min)
// silently abandoned every longer run while it was still live, and since
// this poll is the planner board's SOLE completion surface, the board stayed
// stale forever. Exhaustion must be visible, never silent (pollAiAgentJob).
const PLANNER_JOB_POLL_MAX_MS = 30 * 60 * 1000;
// Delay tiers bounding request volume as the poll ages: 4000ms while the run
// may still be seconds old — deliberately no faster than the mid tier,
// because the seconds right after the send are exactly where the user's own
// interactive requests concentrate, and the first poll still lands ~4s in,
// so a 30-second quick run repaints within one 4s beat of settling — then
// 2500ms until ~5 min (peak 24 req/min), then 4000ms (15 req/min): roughly
// 500 requests across a full 30-minute poll. GET /api/ai/jobs/:id carries a
// DEDICATED always-on per-account limiter (shared Redis store, keyed on the
// account email) budgeted at ~45 req/60s — sized from this poll's own
// arithmetic (~24 req/min peak on the 2.5s tier, ~17 req/min average over a
// full 30-minute poll): that budget fits roughly ONE peak poller with
// headroom, and two tabs both sitting in the 2.5s tier simultaneously can
// brush the ceiling — the 429 branch below then sheds that excess (30s
// backoff, no failure strike), matching the limiter's own sizing note. The
// conditional GLOBAL per-IP limiters (security.rate_limiting, code default
// ON: a Redis-backed limiter over /api code-defaulted to 100 req/120s and
// shipped at 300 req/120s in security.json, with an in-memory fallback
// code-defaulted to 25 req/120s — both config-driven via security.limit)
// remain a second layer beneath it: the poll's 2.5s tier (24 req/min =
// 48 req/120s) fits inside the Redis-backed limiter's defaults, while the
// in-memory fallback's own 25/120s code default would bind — but it reads
// the same security.limit (300 shipped) when engaged, and a tripped 429
// sheds gracefully either way. A 429 from EITHER
// limiter is THROTTLING, not a job failure — the poll backs off
// PLANNER_JOB_POLL_THROTTLED_DELAY_MS and retries instead of burning a
// failure strike (pollAiAgentJob), shedding load rather than aborting.
const PLANNER_JOB_POLL_FAST_MS = 10 * 1000;
const PLANNER_JOB_POLL_SLOW_MS = 5 * 60 * 1000;
const PLANNER_JOB_POLL_FAST_DELAY_MS = 4000;
const PLANNER_JOB_POLL_SLOW_DELAY_MS = 2500;
const PLANNER_JOB_POLL_IDLE_DELAY_MS = 4000;
const PLANNER_JOB_POLL_THROTTLED_DELAY_MS = 30 * 1000;
let plannerItems = [];
let plannerCurrentTab = 'board';
let plannerLastActiveOrder = [];
// The edited item's updated_at, snapshotted when the Compose form was
// filled and echoed to the server as expectedUpdatedAt on save, so a
// teammate's concurrent edit is rejected with 409 instead of silently
// clobbered (see savePlannerItem).
let plannerEditingSnapshot = null;
let plannerSaveInFlight = false;
// Double-submit brake for the billable send-to-agent flow (mirrors plannerSaveInFlight).
let plannerSendAgentInFlight = false;
// Per-item double-submit brake for the board's toggle/delete buttons: a
// rapid second click on the same card used to fire a second DELETE that
// 404ed (the first had already removed the row) and alerted "Planner item
// not found". Keyed by item id so different cards stay independent;
// re-entrant clicks on an in-flight item are ignored silently.
const plannerItemOpsInFlight = new Set();
// adpanel:planner-poll-registry — ONE registry owning the lifetime of the
// fire-and-forget send-completion pollers (pollAiAgentJob). Every send
// spawned a ~30-minute loop with no dedupe and no cancellation: N sends
// stacked N concurrent pollers burning the dedicated ~45 req/60s job-limiter
// budget sized for roughly ONE peak poller (see the PLANNER_JOB_POLL_*
// constants), and a poller kept running (and re-firing loadPlannerItems() on
// settle) for a card the user had already deleted or completed. Keyed by job
// id; startPlannerJobPoller refuses a second poller for a job already being
// tracked, deletePlannerItem / a completing-direction togglePlannerItem
// cancel the poller tracking that item, and every exit — settle,
// exhaustion, 3-strike, cancel — removes the entry at the spawn site's
// finally, so no entry can leak.
const plannerJobPollers = new Map();
// Same staleness guard as schedulerTasksLoadSeq/backupsLoadSeq: overlapping
// planner loads resolve out of order, so only the newest may touch the board.
let plannerLoadSeq = 0;
// A native card drag reorders the live list DOM directly; replacing that list
// mid-drag leaves the pending dragend with zero ids and silently drops the
// user's reorder.
let plannerDragInFlight = false;
// Increments on every dragstart: a reorder response that lands while a
// NEWER drag is already running must not repaint the board (it would detach
// the newer drag's node mid-drag and silently discard its reorder) nor
// settle it — the newer drag's own settle point flushes the reload.
let plannerDragSession = 0;
let plannerAcceptedDropSession = 0;
// Set when a load is requested (or its response lands) during a drag; the
// dragend settle path runs one fresh load instead of applying mid-drag.
let plannerReloadQueuedAfterDrag = false;
// adpanel:planner-drag-trailing-click — Date.now() of the last dragend,
// stamped by the dragend handler and read by handlePlannerListClick to
// suppress Chromium's trailing click on the drag source (the window
// rationale lives at that check).
let plannerDragEndAt = 0;
// Increments on every editor transition: an item opened for edit
// (fillPlannerForm) or the form reset toward a new prompt
// (clearPlannerEditState, also via resetPlannerForm). savePlannerItem
// snapshots it at start because its completion-time form resets may only
// run when NO editor session — a re-open of the same item included —
// began during the flight: the saved-vs-form edit ids alone cannot tell
// that case apart.
let plannerEditorEpoch = 0;
// adpanel:planner-action-tokens — the five planner mutation routes require a
// session-bound x-action-token (TTL 300s, reusable, minted per server). This
// planner-local cache is refreshed from EVERY successful planner GET response
// (plannerRequest merges data.actionTokens) and read by plannerMutateRequest;
// an empty cache sends the mutation WITHOUT the header — an older backend
// that does not require the token must never see a client-side hard fail.
let plannerActionTokens = {};
function rememberPlannerActionTokens(actionTokens) {
if (!actionTokens || typeof actionTokens !== 'object') return;
// Merge, never clobber: a GET that re-issues only a subset of the five
// tokens must not drop the ones it did not carry.
plannerActionTokens = { ...plannerActionTokens, ...actionTokens };
}
function setPlannerStatus(text, offline = false) {
if (!plannerStatusIndicator) return;
const dot = plannerStatusIndicator.querySelector('.planner-status-dot');
const label = plannerStatusIndicator.querySelector('.planner-status-text');
if (dot) dot.classList.toggle('offline', !!offline);
if (label) label.textContent = text;
}
// Session expiry gets the same overlay UX the console scene uses in
// fetchPerms() instead of a raw alert, and leaves board state untouched so
// signing back in resumes where the user was.
function showPlannerSessionExpired() {
const offlineOverlay = document.getElementById('offlineOverlay');
const offlineText = document.querySelector('#offlineOverlay .offline-text');
if (offlineOverlay && offlineText) {
offlineText.textContent = 'Not authenticated';
offlineOverlay.classList.add('show');
// adpanel:planner-auth-overlay-owner — claim the shared overlay so the
// node-status writers (updateOfflineState) can neither hide it on a
// node-online transition (the user is still logged out) nor re-purpose
// it on a node flap. Released only by the overlay's own redirect, which
// is a full page navigation.
offlineOverlayOwner = 'planner-auth';
}
}
function plannerRequest(path = '', options = {}) {
// adpanel:scheduler-fetch-bound — bounded so a stalled planner response
// cannot pin "Loading…" (or a drag/mutation guard) up forever. Every
// caller funnels rejections into its own planner catch flow, so the
// abort surfaces as a normal planner failure (auth-error handling and
// status mapping below are unchanged).
return fetchWithTimeout(`${PLANNER_API_BASE}${path}`, options, 20000).then(async (response) => {
if (response.status === 401) {
showPlannerSessionExpired();
const err = new Error('Your session has expired. Please sign in again.');
err.isPlannerAuthError = true;
throw err;
}
if (!response.ok) {
const err = await response.json().catch(() => ({}));
const failure = new Error(err.error || err.message || `Planner request failed (${response.status})`);
// Callers map UX text by status (403 => permission, 409 => cap) without
// having to parse the raw server error string.
failure.status = response.status;
// adpanel:planner-action-tokens — carry the server's machine code so
// plannerMutateRequest can key its single token-retry to
// ACTION_TOKEN_INVALID without re-parsing the error body.
failure.code = err.code || null;
throw failure;
}
// A non-JSON 200 (proxy page, plain text) parses to {} and would render
// "0 active, 0 completed" as if real data said so; treat it as an error.
let data = null;
try {
data = await response.json();
} catch (parseErr) {
data = null;
}
if (!data || typeof data !== 'object') {
throw new Error('The planner returned an unreadable response. Please try again.');
}
// adpanel:planner-action-tokens — every successful planner GET mints the
// five session-bound mutation tokens for this server; merge them into the
// planner-local cache so every mutation call site attaches a fresh
// x-action-token (the scheduler preview's GET refreshes them too).
if ((!options.method || options.method === 'GET') && data.actionTokens && typeof data.actionTokens === 'object') {
rememberPlannerActionTokens(data.actionTokens);
}
return data;
});
}
// The ONE mutation entry for the five token-gated planner routes (create,
// send-agent, reorder, update, delete): attaches the cached x-action-token
// when one exists, and on exactly one 403 whose payload code is
// ACTION_TOKEN_INVALID refreshes the tokens through the existing planner
// board GET and retries ONCE. Every other failure — the CAS 409s
// (planner_item_modified / planner_prompt_changed), 404s, the cap 409 —
// propagates untouched to the caller's own recovery flows.
async function plannerMutateRequest(path = '', options = {}, tokenKey = '') {
const send = () => {
const headers = new Headers(options.headers || {});
const token = String(plannerActionTokens[tokenKey] || '').trim();
if (token) headers.set('x-action-token', token);
return plannerRequest(path, { ...options, headers });
};
try {
return await send();
} catch (err) {
if (!err || err.status !== 403 || err.code !== 'ACTION_TOKEN_INVALID') throw err;
// A bare plannerRequest('') instead of loadPlannerItems(): the token
// refresh must still run mid-drag (loadPlannerItems defers while a drag
// is in flight) and must never repaint the board from a retry path. A
// failed refresh must not mask the original 403.
try {
await plannerRequest('');
} catch (refreshErr) {
if (refreshErr.isPlannerAuthError) throw refreshErr;
console.error('[planner] Action-token refresh failed:', refreshErr);
throw err;
}
return send();
}
}
function derivePlannerTitle(prompt) {
const clean = String(prompt || '').trim().replace(/\s+/g, ' ');
if (!clean) return 'Untitled Prompt';
return clean.length > 72 ? `${clean.slice(0, 69)}...` : clean;
}
function plannerAuthorLabel(email) {
const raw = String(email || '').trim();
if (!raw) return 'Team';
const base = raw.split('@')[0] || raw;
return base.slice(0, 28);
}
function plannerActiveItems() {
return plannerItems.filter((item) => !Number(item.is_done));
}
function plannerCompletedItems() {
return plannerItems.filter((item) => Number(item.is_done));
}
// adpanel:planner-order-baseline — the ONE derivation of the drag no-op
// baseline: the active items of the current plannerItems snapshot, in board
// order (exactly what renderPlannerBoard paints). renderPlannerBoard
// refreshes it on every render, and EVERY site that reassigns plannerItems
// without a render must call it too — a stale baseline makes the dragend
// no-op detector treat the user's next real (corrective) drag as a no-op,
// so the settle reload silently repaints the older order over their move.
// The ONE exception is the create-success branch
// (adpanel:planner-create-baseline): there the snapshot runs AHEAD of the
// rendered DOM, so the baseline must be reseeded from the rendered order
// instead of the array.
function syncPlannerLastActiveOrder() {
plannerLastActiveOrder = plannerActiveItems().map((item) => Number(item.id));
}
// adpanel:planner-create-baseline — the DOM-order twin of
// syncPlannerLastActiveOrder, for that one exception: it seeds the no-op
// baseline from the .planner-item ids actually on screen (the same
// derivation the dragend handler reads back), because the caller has
// reassigned plannerItems without rendering and the snapshot momentarily
// contains ids the dragend could never observe.
function syncPlannerLastActiveOrderFromDom() {
if (!plannerActiveList) return;
plannerLastActiveOrder = [...plannerActiveList.querySelectorAll('.planner-item')]
.map((entry) => parseInt(entry.dataset.id, 10))
.filter((id) => !Number.isNaN(id));
}
function switchPlannerTab(tabName) {
plannerCurrentTab = tabName;
plannerTabs.forEach((tab) => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
if (plannerBoardTab) plannerBoardTab.classList.toggle('hidden', tabName !== 'board');
if (plannerComposeTab) plannerComposeTab.classList.toggle('hidden', tabName !== 'compose');
if (tabName === 'compose') {
setTimeout(() => plannerTitleInput?.focus(), 40);
}
}
function setPlannerEditIndicator(title) {
if (!plannerEditIndicator) return;
if (plannerEditIndicatorTitle) plannerEditIndicatorTitle.textContent = title || '';
plannerEditIndicator.classList.toggle('hidden', !title);
}
// Clears only the editing markers (hidden id, button label, indicator) so a
// submit creates a new item; drafted text is preserved across tab switches
// and modal reopen. Full clear stays the job of resetPlannerForm().
function clearPlannerEditState() {
// The editor identity changes here (and in fillPlannerForm): bump the
// epoch so an in-flight save's completion never resets the newer session.
plannerEditorEpoch += 1;
if (plannerItemIdInput) plannerItemIdInput.value = '';
// Clear the snapshot with its item id so new drafts cannot reuse it.
plannerEditingSnapshot = null;
// While a save is in flight the button is disabled and its spinner label
// is owned by savePlannerItem (its finally re-derives the label from the
// hidden id once the save settles) — overwriting it here (modal reopen,
// Compose-tab click mid-save) would flip "Saving..." back to "Save
// Prompt" while the button is still disabled.
if (plannerSaveBtn && !plannerSaveInFlight) {
plannerSaveBtn.innerHTML = 'Save Prompt';
}
setPlannerEditIndicator(null);
}
function resetPlannerForm() {
clearPlannerEditState();
if (plannerTitleInput) plannerTitleInput.value = '';
if (plannerPromptInput) plannerPromptInput.value = '';
// While a save is in flight its finally owns the Save button: re-enabling
// here (a Reset or Compose click mid-save) would let a second submit fire
// before the first one finished.
if (plannerSaveBtn && !plannerSaveInFlight) plannerSaveBtn.disabled = false;
}
function fillPlannerForm(item) {
if (!item) return;
// Opening an edit — even a re-open of the SAME item while a save of it is
// still in flight — starts a new editor session the save's completion
// must not reset.
plannerEditorEpoch += 1;
if (plannerItemIdInput) plannerItemIdInput.value = String(item.id || '');
// Snapshot the version this form is now showing; savePlannerItem sends it
// back so the server can 409 when the row changed underneath us.
plannerEditingSnapshot = item;
if (plannerTitleInput) plannerTitleInput.value = item.title || '';
if (plannerPromptInput) plannerPromptInput.value = item.prompt || '';
if (plannerSaveBtn) {
plannerSaveBtn.innerHTML = 'Update Prompt';
}
setPlannerEditIndicator(item.title || derivePlannerTitle(item.prompt));
switchPlannerTab('compose');
plannerTitleInput?.focus();
}
// Passing null for either list renders that counter as "—": used after a
// failed load, when the true counts are unverified rather than genuinely zero.
function renderPlannerSummaryCards(activeItems, completedItems) {
if (!plannerSummary) return;
const activeCount = Array.isArray(activeItems) ? activeItems.length : '—';
const completedCount = Array.isArray(completedItems) ? completedItems.length : '—';
const nextUp = Array.isArray(activeItems) ? (activeItems[0] ? 'P1' : '0') : '—';
plannerSummary.innerHTML = `
Active${activeCount}
Next Up${nextUp}
Completed${completedCount}
`;
}
function renderPlannerItemCard(item, index, isDone = false) {
const title = escapeHtml(item.title || derivePlannerTitle(item.prompt));
const prompt = escapeHtml(item.prompt || '').replace(/\n/g, ' ');
const relativeTime = item.updated_at ? formatRelativeTime(item.updated_at) : 'Just now';
const priorityBadge = isDone
? 'Done'
: `${index === 0 ? 'Now' : `P${index + 1}`}`;
// adpanel:planner-send-done — the send-agent route refuses is_done rows, so
// a completed card must not offer send: the whole-card button renders as a
// non-interactive div (same class, no data-planner-action for the list
// click handler to resolve) and the paper-plane action button is omitted —
// the actions row keeps edit/toggle/delete only. Active-card markup is
// unchanged except that the drag handle sits OUTSIDE the whole-card send
// button (a deliberate structural move: a grip click can never resolve to
// a send action); done cards render a non-interactive main and no send
// button.
const canSend = !isDone && hasAgentAccess();
const mainOpen = !canSend
? '
`;
}
function renderPlannerBoard() {
if (!plannerActiveList || !plannerCompletedList) return;
const activeItems = plannerActiveItems();
const completedItems = plannerCompletedItems();
renderPlannerSummaryCards(activeItems, completedItems);
syncPlannerLastActiveOrder();
if (!activeItems.length) {
plannerActiveList.innerHTML = `
No prompts in the queue yet.
`;
const emptyBtn = document.getElementById('plannerEmptyComposeBtn');
if (emptyBtn) {
emptyBtn.addEventListener('click', () => {
resetPlannerForm();
switchPlannerTab('compose');
});
}
} else {
plannerActiveList.innerHTML = activeItems.map((item, index) => renderPlannerItemCard(item, index, false)).join('');
bindPlannerDragAndDrop();
}
if (!completedItems.length) {
plannerCompletedSection?.classList.add('hidden');
plannerCompletedList.innerHTML = '';
} else {
plannerCompletedSection?.classList.remove('hidden');
plannerCompletedList.innerHTML = completedItems.map((item, index) => renderPlannerItemCard(item, index, true)).join('');
}
}
// Returns true when a fresh server response was applied; false when the load
// was superseded, deferred past a drag, or failed, so callers don't paint a
// "saved"/"deleted" success status over an unverified board.
async function loadPlannerItems() {
if (!plannerActiveList || !plannerCompletedList) return false;
const seq = ++plannerLoadSeq;
if (plannerDragInFlight) {
// Never wipe the list while a card drag is in flight: the pending dragend
// reads ids from these DOM nodes, and replacing them silently drops the
// user's reorder. One fresh load runs once the drag settles instead.
plannerReloadQueuedAfterDrag = true;
return false;
}
plannerActiveList.innerHTML = '
Loading planner...
';
plannerCompletedList.innerHTML = '';
if (plannerRefreshBtn) plannerRefreshBtn.classList.add('spinning');
setPlannerStatus('Loading planner...');
try {
const data = await plannerRequest();
if (seq !== plannerLoadSeq) return false;
if (plannerDragInFlight) {
// The drag started while this fetch was in flight; applying now would
// yank the cards out from under it.
plannerReloadQueuedAfterDrag = true;
return false;
}
plannerItems = Array.isArray(data.items) ? data.items : [];
renderPlannerBoard();
setPlannerStatus(`${plannerActiveItems().length} active, ${plannerCompletedItems().length} completed`);
return true;
} catch (err) {
if (seq !== plannerLoadSeq) return false;
if (plannerDragInFlight) {
plannerReloadQueuedAfterDrag = true;
return false;
}
console.error('[planner] Load error:', err);
// Keep the last known board on screen: a transient failure must never
// present itself as an empty planner. The counters go unknown ("—")
// because the server state could not be verified this round.
if (plannerItems.length) {
setPlannerStatus('Planner unavailable — showing your last synced prompts', true);
// The pre-fetch wipe left a "Loading planner..." spinner in the lists;
// rebuild them from the intact last-synced plannerItems (a pure DOM
// re-render that never touches the status line), then knock the
// counters back to unknown ("—") for this unverified round.
renderPlannerBoard();
renderPlannerSummaryCards(null, null);
} else {
renderPlannerSummaryCards(null, null);
const message = err.isPlannerAuthError
? err.message
: 'Could not load the planner. Check your connection and try again.';
plannerActiveList.innerHTML = `
${escapeHtml(message)}
`;
plannerCompletedSection?.classList.add('hidden');
setPlannerStatus('Planner unavailable', true);
}
return false;
} finally {
if (seq === plannerLoadSeq && plannerRefreshBtn && !plannerDragInFlight) {
plannerRefreshBtn.classList.remove('spinning');
}
}
}
function openPlannerModal() {
if (!plannerModal) return;
if (!hasPerm('planner_access')) {
alert('You do not have permission to access the planner.');
return;
}
// adpanel:planner-open-idempotent — re-activating an ALREADY-ACTIVE
// planner (habitual re-click on the active Planner dock button, deep
// link while it is open) must never reset an in-progress edit session:
// the clearPlannerEditState() below wipes the hidden item id +
// updated_at while deliberately keeping the drafted text, so the next
// Save silently became a CREATE duplicate (the server has no duplicate
// detection by design). The already-active marker for BOTH modes is
// .show on #plannerModal: modal mode is .show alone; inline-page mode
// is .adpanel-page-active PLUS .show — showInlinePage (bot.ejs) sets
// .adpanel-page-active BEFORE the synthetic dock click reaches this
// function (inside the boot-perm-gate window too), so that class alone
// cannot discriminate a first open from a re-click; .show is added by
// this function's own showModalElement on every open in either mode and
// is stripped by every close/switch-away path (animateClose.finish,
// showInlinePage's per-page strip, showConsoleView, the install-overlay
// teardown). No-op when already active: no reset, no tab switch, no
// board reload — the in-progress view must not flicker. A genuine
// reopen (modal hidden / page inactive) still takes the full reset path
// below, so the stale-edit-state contract in the next comment holds.
if (plannerModal.classList.contains('show')) return;
// The modal DOM persists across close/reopen, so stale edit state from a
// previous session would turn the next submit into a silent overwrite.
// Draft text is deliberately kept here.
clearPlannerEditState();
showModalElement(plannerModal);
switchPlannerTab('board');
afterModalPaint(() => loadPlannerItems());
}
function closePlannerModal() {
if (!plannerModal) return;
animateClose(plannerModal);
}
function plannerGetDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.planner-item:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset, element: child };
}
return closest;
}, { offset: Number.NEGATIVE_INFINITY, element: null }).element;
}
// Drag settle point, called when a drag fully ends (after any reorder request
// resolves). Clears the in-flight flag and runs one deferred load — forced
// after a failed reorder so the server order is restored on screen.
function plannerSettleDrag(forceReload = false) {
plannerDragInFlight = false;
const needsReload = forceReload || plannerReloadQueuedAfterDrag;
plannerReloadQueuedAfterDrag = false;
if (needsReload) loadPlannerItems();
}
function bindPlannerDragAndDrop() {
if (!plannerActiveList) return;
plannerActiveList.querySelectorAll('.planner-item').forEach((item) => {
// Session captured at dragstart so dragend can tell whether a newer
// drag has taken over the board while this one's reorder was in flight.
let cardDragSession = 0;
item.addEventListener('dragstart', (event) => {
cardDragSession = ++plannerDragSession;
plannerDragInFlight = true;
item.classList.add('dragging');
// adpanel:planner-drag-firefox — Firefox requires at least one setData
// call in dragstart or the drag aborts before dragover/dragend ever
// fire.
try { event.dataTransfer.setData('text/plain', String(item.dataset.id || '')); } catch (_) {}
});
item.addEventListener('dragend', async () => {
const session = cardDragSession;
// adpanel:planner-drag-trailing-click — suppress the trailing click on every exit.
plannerDragEndAt = Date.now();
item.classList.remove('dragging');
if (session !== plannerAcceptedDropSession) {
if (session === plannerDragSession) plannerSettleDrag(true);
return;
}
const siblings = [...plannerActiveList.querySelectorAll('.planner-item')];
const idx = siblings.indexOf(item);
const orderedIds = siblings
.map((entry) => parseInt(entry.dataset.id, 10))
.filter((id) => !Number.isNaN(id));
// Only the newest drag may reconcile a preview against the saved order.
if (!orderedIds.length) {
if (session === plannerDragSession) plannerSettleDrag(true);
return;
}
if (JSON.stringify(orderedIds) === JSON.stringify(plannerLastActiveOrder)) {
if (session === plannerDragSession) plannerSettleDrag(true);
return;
}
const draggedId = parseInt(item.dataset.id, 10);
if (!Number.isFinite(draggedId)) {
if (session === plannerDragSession) plannerSettleDrag(true);
return;
}
// Relative-move anchors read from the live DOM: aboveId is the card
// we landed UNDER, belowId the card we landed ABOVE. The server
// splices the dragged id between those anchors in ITS current order,
// so prompts created (or completed/deleted) since our last render
// keep their position — the old absolute id list silently demoted
// anything the client had never seen.
const aboveRaw = idx > 0 ? parseInt(siblings[idx - 1].dataset.id, 10) : NaN;
const belowRaw = idx > -1 && idx < siblings.length - 1 ? parseInt(siblings[idx + 1].dataset.id, 10) : NaN;
try {
const data = await plannerMutateRequest('/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
itemId: draggedId,
aboveId: Number.isNaN(aboveRaw) ? null : aboveRaw,
belowId: Number.isNaN(belowRaw) ? null : belowRaw
})
}, 'plannerReorder');
plannerItems = Array.isArray(data.items) ? data.items : plannerItems;
// adpanel:planner-null-items — the reorder committed but its
// post-commit board re-read failed (items null): plannerItems above
// stayed pre-drag, so painting it would visually revert the user's
// move, and deriving the baseline below from that stale snapshot
// would desync the no-op detector from the committed DOM — a later
// dragend comparing its dropped DOM order against the stale baseline
// would early-return there as a "no-op", and the settle reload
// would repaint the older order, silently discarding the user's
// corrective move. Rebuild the active portion from the committed DOM
// instead: the dropped order IS what the server committed (every
// active card on screen maps to a snapshot entry — loads defer while
// a drag is in flight, so the snapshot cannot have been replaced
// mid-drag), and completed items keep their snapshot order (a
// reorder never touches them).
if (!Array.isArray(data.items)) {
const activeById = new Map(plannerActiveItems().map((entry) => [Number(entry.id), entry]));
plannerItems = [
...orderedIds.map((id) => activeById.get(id)).filter(Boolean),
...plannerCompletedItems()
];
}
// adpanel:planner-order-baseline — this response committed a new
// server order, so the no-op baseline must track it even when the
// branches below paint nothing: the newer-drag branches deliberately
// skip the render (repainting mid-drag detaches the dragged node),
// and the next dragend compares its dropped DOM order against
// plannerLastActiveOrder. With items null the rebuild above is what
// makes this derivation track the committed order instead of the
// stale pre-drag snapshot.
syncPlannerLastActiveOrder();
// adpanel:planner-null-items — queue the settle reload so the board
// is re-fetched from the server instead of trusting the snapshot.
if (!Array.isArray(data.items)) plannerReloadQueuedAfterDrag = true;
if (session === plannerDragSession) {
// adpanel:planner-load-seq — the committed reorder makes any load
// request issued before the drag stale; bumping the generation
// stops its response from repainting the old order over the
// server-confirmed one after settle. The superseded load's
// finally skips the spinner clear on a stale seq, and nothing
// queued a replacement load here — clear it explicitly.
plannerLoadSeq++;
if (plannerRefreshBtn) plannerRefreshBtn.classList.remove('spinning');
// adpanel:planner-null-items — with items null the snapshot is
// pre-drag; leave the committed DOM order on screen and let the
// settle reload queued above repaint from the server response.
if (Array.isArray(data.items)) renderPlannerBoard();
setPlannerStatus('Priority updated');
plannerSettleDrag();
} else if (plannerDragInFlight) {
// A newer drag owns the board — repainting now would detach its
// dragged node mid-drag and silently discard its reorder, and
// settling would clear its in-flight flag. Queue the reload so
// the newer drag's settle point repaints the server-confirmed
// order no matter which branch its own dragend takes (the
// early-return branches force that settle reload too).
plannerReloadQueuedAfterDrag = true;
} else {
// The newer drag already settled, so nothing would consume the
// queued flag — repaint the confirmed order now instead.
loadPlannerItems();
}
} catch (err) {
console.error('[planner] Reorder error:', err);
// 409 planner_order_changed / 404 stay SILENT: the server order is
// authoritative and the forced reload below repaints the board, so
// alerting would only scold the user for a teammate race they
// could neither see nor avoid.
// adpanel:planner-order-baseline — these paths never reassign
// plannerItems, so the no-op baseline legitimately keeps tracking
// the last-rendered snapshot here; the forced settle reload
// repaints the server order and re-derives the baseline from it.
if (err.status === 409 || err.status === 404) {
if (session === plannerDragSession) plannerSettleDrag(true);
// A live newer drag flushes the queued reload at its settle; an
// already-settled one never will, so repaint directly.
else if (plannerDragInFlight) plannerReloadQueuedAfterDrag = true;
else loadPlannerItems();
return;
}
if (!err.isPlannerAuthError) alert(err.message || 'Failed to update planner order');
if (session === plannerDragSession) plannerSettleDrag(true);
else if (plannerDragInFlight) plannerReloadQueuedAfterDrag = true;
else loadPlannerItems();
}
});
});
if (plannerActiveList.dataset.dragBound === '1') return;
plannerActiveList.dataset.dragBound = '1';
plannerActiveList.addEventListener('dragover', (e) => {
const dragging = plannerActiveList.querySelector('.planner-item.dragging');
if (!dragging) return;
e.preventDefault();
const afterElement = plannerGetDragAfterElement(plannerActiveList, e.clientY);
if (!afterElement) {
plannerActiveList.appendChild(dragging);
} else if (afterElement !== dragging) {
plannerActiveList.insertBefore(dragging, afterElement);
}
});
plannerActiveList.addEventListener('drop', (event) => {
if (!plannerActiveList.querySelector('.planner-item.dragging')) return;
event.preventDefault();
plannerAcceptedDropSession = plannerDragSession;
});
}
async function sendPlannerPromptToAgent(item) {
if (!item || !String(item.prompt || '').trim()) {
alert('This planner prompt is empty.');
return;
}
// adpanel:planner-send-done — belt-and-braces for the render-time guard in
// renderPlannerItemCard: a stale board can hold an active-looking card
// whose row was completed meanwhile, and the route refuses is_done rows.
if (Number(item.is_done) === 1) {
setPlannerStatus('This prompt is already completed and cannot be sent to ' + BRAND_NAME + ' Agent.', true);
return;
}
if (!hasAgentAccess()) {
alert('You do not have permission to access ' + BRAND_NAME + ' Agent.');
return;
}
// The user's own in-flight save bumps the item's updated_at, so a send
// fired now would 409 against THEIR write ("This prompt changed since
// you viewed it") — a self-conflict, not a teammate race. Ask them to
// wait instead of surfacing it.
if (plannerSaveInFlight) {
setPlannerStatus('Wait for the current save to finish, then send again.', true);
return;
}
// The brake stays GLOBAL (one billable send at a time), but a silent
// return reads as a dead button — surface it, matching the save-wait
// status above.
if (plannerSendAgentInFlight) {
setPlannerStatus('A prompt is already being sent — wait for it to finish.', true);
return; // Ignore repeats while a send is still running (e.g. rapid double-click)
}
// adpanel:planner-send-confirm — the send route starts a BILLABLE agent
// run and the whole card main is that send button, so a casual click must
// not queue a paid job unasked. The gate sits after every re-runnable
// early-return. The gate is now the shared in-app confirm modal
// (storeConfirm — adpanel:planner-in-app-confirm): the native confirm()
// this replaces was silently suppressed by Chromium's "prevent this page
// from creating more dialogs", so the billable send's own click could
// dead-end with no dialog at all. The brake is taken BEFORE the gate
// because the modal keeps the event loop live while it is open (the old
// native confirm() blocked it): without the brake a second click could
// stack a second send behind the open dialog. A declined confirm releases
// the brake in the finally below with nothing else done. The title is
// normalized through dialogText like every native dialog
// (adpanel:planner-confirm-title).
plannerSendAgentInFlight = true;
try {
const sendConfirmTitle = dialogText(item.title || derivePlannerTitle(item.prompt));
const sendModelValue = String(aiModelSelect?.value || '').trim();
const editWarning = plannerModal?.dataset.agentAutoEditWarning;
const holdWarning = item.agent_edit_hold ? ' Confirm only after checking the files affected by the previous Agent run.' : '';
const sendConfirmed = await storeConfirm(`Send "${sendConfirmTitle}" to the ${BRAND_NAME} Agent now? This starts a billable agent run.${editWarning ? ` ${editWarning}` : ''}${holdWarning}`);
if (!sendConfirmed) return;
setPlannerStatus('Sending to ' + BRAND_NAME + ' Agent...');
// Both echoes authorize the version the sender saw on the board: the
// server answers 409 planner_prompt_changed when a teammate edited the
// prompt first, so the send can never run against a stale snapshot.
// expectedUpdatedAt alone is a second-precision fast path — a
// teammate's same-second edit leaves it unchanged — so expectedPrompt
// (the exact text being authorized) is the actual laundering gate and
// is mandatory server-side (adpanel:send-agent-version-echo).
const data = await plannerMutateRequest(`/${encodeURIComponent(item.id)}/send-agent`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
expectedUpdatedAt: item.updated_at ?? null,
expectedPrompt: String(item.prompt ?? ''),
...(sendModelValue && { selection: sendModelValue }),
...(item.agent_edit_hold && { checkedAgentEditHold: item.agent_edit_hold }),
...(editWarning && { autoApproveFileEdits: true })
})
}, 'plannerSendAgent');
// The request resolved — the job is queued and the send succeeded. Only
// the plannerRequest call is success-critical: everything below is
// follow-up UI, and a failure there must never repaint this as
// 'Send failed' — and the completion poll below runs regardless of the
// follow-up UI outcome (the queued job is billable either way).
setPlannerStatus('Prompt sent to ' + BRAND_NAME + ' Agent');
try {
closePlannerModal();
await new Promise((resolve) => setTimeout(resolve, 120));
await openAiHelpModal();
// adpanel:planner-send-chat-id — validate the conversion BEFORE it
// reaches shared state: a malformed response must never store NaN into
// aiCurrentChatId (switchToChat(NaN) silently no-ops and the poisoned
// id lingers across planner/AI state). Same usable-id contract as
// isValidChatId; the send's success path above is untouched either way.
const sentChatId = Number(data.chatId);
if (isValidChatId(sentChatId)) {
aiCurrentChatId = sentChatId;
await loadChatsFromDb();
await switchToChat(aiCurrentChatId);
}
} catch (uiErr) {
console.error('[planner] Post-send UI error:', uiErr);
setPlannerStatus('Prompt sent — couldn\'t open the Agent panel');
}
if (data.jobId) {
// adpanel:planner-poll-registry — spawn through the registry gate: a
// job already being tracked reuses its live poller instead of stacking
// a second one, and the registry entry is removed when this poller
// exits. The first poller of a job keeps the exact loop and settle
// behavior it always had.
startPlannerJobPoller(data.jobId, data.chatId, item.id);
}
} catch (err) {
setPlannerStatus('Send failed', true);
// A 401 already raised the session-expired overlay in plannerRequest;
// alerting on top of it would double-prompt the same failure.
if (err.status === 409 && err.message === 'planner_prompt_changed') {
// The stored prompt moved since the sender viewed it — the job was
// NOT queued. Refresh the board so the next send authorizes the
// current text instead of surfacing the raw conflict code.
alert('This prompt changed since you viewed it. The board has been refreshed — review it and send again.');
loadPlannerItems();
} else if (err.status === 409 && err.message === 'planner_agent_edit_hold') {
alert('Check the previous Agent edits before sending this prompt again.');
loadPlannerItems();
} else if (err.status === 404) {
// adpanel:planner-send-gone — the send route answers 404 'Planner item
// not found' when the row was deleted mid-flight (a teammate's delete
// is real both while the confirm dialog sits open and between confirm
// and POST). The board-is-authoritative contract togglePlannerItem
// and deletePlannerItem apply to their 404s covers the send too:
// reload so the dead card drops instead of staying fully actionable
// and re-alerting on every send. Same recovery shape as the delete
// branch: a failed load reports itself on the status line, and only a
// successful one says why the card vanished — no alert of the raw
// server message. The 409 branch above and the generic-alert fallback
// below (with its auth-error suppression) are untouched.
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus('Prompt no longer exists');
} else if (!err.isPlannerAuthError) alert(err.message || 'Failed to send planner prompt to ' + BRAND_NAME + ' Agent.');
} finally {
plannerSendAgentInFlight = false;
}
}
async function pollAiAgentJob(jobId, chatId = null, pollHandle = null) {
const safeJobId = Number(jobId);
if (!Number.isFinite(safeJobId) || safeJobId <= 0) return;
// adpanel:planner-send-completion — the loop bounds itself on ELAPSED
// WALL-CLOCK TIME against PLANNER_JOB_POLL_MAX_MS (declared beside the
// planner constants), not an attempt count: an attempt cap measures
// requests, not the job's real window (runtime cap + serial-queue wait),
// so it abandoned long runs silently. Delays tier up with poll age per
// the constants' volume rationale.
const pollStartedAt = Date.now();
// The queued job is billable, so one dropped poll must not abandon it: a
// failed fetch or a non-OK response is tolerated (same delay, the wall-
// clock budget above still caps the total) until three fail IN A ROW — a
// transient blip resets on the next good response; the third consecutive
// one gives up VISIBLY (offline status + one reconcile, same contract as
// exhaustion). A 429 is the shared limiter throttling, not a job failure:
// it neither counts nor strikes — it backs off hard and retries.
let consecutiveFailures = 0;
for (;;) {
const elapsedMs = Date.now() - pollStartedAt;
if (elapsedMs >= PLANNER_JOB_POLL_MAX_MS) {
// adpanel:planner-send-completion — exhaustion must be VISIBLE: the
// poll gave up, the job did not (the server still owns the run and
// its live status lives in the AI panel). A silent return here left
// the board stale forever — the user re-sent a dedupe-409ing card or
// toggle-completed an already-flipped row and never saw the reply.
// Surface the state, then fire ONE last fire-and-forget reconcile
// (same contract as the terminal branch below: loadPlannerItems
// neither blocks nor rejects; it defers during drags and honors
// plannerLoadSeq).
console.error('[ai-agent-job] Poll budget exhausted for job', safeJobId, 'after', Math.round(elapsedMs / 60000), 'min — surfacing and reconciling once');
setPlannerStatus('Still waiting for ' + BRAND_NAME + ' Agent to finish — live status is in the AI panel.', true);
loadPlannerItems();
return;
}
const waitMs = elapsedMs < PLANNER_JOB_POLL_FAST_MS ? PLANNER_JOB_POLL_FAST_DELAY_MS : elapsedMs < PLANNER_JOB_POLL_SLOW_MS ? PLANNER_JOB_POLL_SLOW_DELAY_MS : PLANNER_JOB_POLL_IDLE_DELAY_MS;
await new Promise((resolve) => setTimeout(resolve, waitMs));
// adpanel:planner-poll-registry — a cancelled poller (its item was
// deleted or completed) exits silently: it fires no further request and
// none of the visible exits below (the user's delete/completion already
// decided the card's fate). Two gates cover every await point: this one
// (cancel landing during the sleep) and the post-fetch one (cancel
// landing mid-request).
if (pollHandle?.cancelled) return;
let data = null;
try {
const response = await fetch(`/api/ai/jobs/${encodeURIComponent(safeJobId)}`, { cache: 'no-store' });
// adpanel:planner-send-completion — a 429 is limiter throttling, not a
// job-state failure, and EITHER limiter can send it: the dedicated
// per-account 45 req/60s brake on this route (the binding constraint
// for pollers — two tabs in the 2.5s tier can brush it) or a global
// per-IP limiter when an operator has lowered its limit below the
// poll's sustained rate. Counting a 429 as a strike burned the
// 3-failure budget ~1 minute in under an enabled limiter and
// abandoned a poll that still had nearly all of its budget left. Shed
// load instead: back off hard and retry — the wall-clock check at the
// loop top still ends the poll on time, and the failure counter is
// left untouched so the next good response still resets it.
if (response.status === 429) {
await new Promise((resolve) => setTimeout(resolve, PLANNER_JOB_POLL_THROTTLED_DELAY_MS));
continue;
}
if (!response.ok) throw new Error(`Job poll failed (${response.status})`);
data = await response.json().catch(() => ({}));
} catch (pollErr) {
consecutiveFailures += 1;
if (consecutiveFailures >= 3) {
// adpanel:planner-send-completion — this exit must be VISIBLE like
// the exhaustion exit above: three 404s in a row (the server was
// deleted mid-poll and the job rows went with it) used to
// bare-return silently, leaving a stale card over a billable run
// nobody could see. Say honestly that tracking is lost, then fire
// one final fire-and-forget reconcile — same contract as exhaustion.
console.error('[ai-agent-job] Poll abandoned for job', safeJobId, 'after 3 consecutive failures:', pollErr);
setPlannerStatus('Could not keep tracking the ' + BRAND_NAME + ' Agent task — check the AI panel for its live status.', true);
loadPlannerItems();
return;
}
continue;
}
// adpanel:planner-poll-registry — the second cancel gate: a poller whose
// item was deleted or completed while this request was in flight must
// not fire its settle path (the chat repaint or the board reconcile)
// for a card the user already disposed of. The registry entry was
// already removed by the cancel; this return just ends the loop.
if (pollHandle?.cancelled) return;
consecutiveFailures = 0;
const status = String(data?.job?.status || '').toLowerCase();
if (!status || status === 'queued' || status === 'running') continue;
const targetChatId = Number(chatId || data?.job?.chat_id || aiCurrentChatId);
// A throw from the chat repaint must not skip the board reconcile below
// (it would escape to the caller's .catch): the job IS settled — only
// the chat view failed — so best-effort the repaint and still reconcile.
try {
if (targetChatId && aiCurrentChatId === targetChatId) {
await switchToChat(targetChatId);
} else {
await loadChatsFromDb();
renderChatsList();
}
} catch (repaintErr) {
console.error('[ai-agent-job] Chat repaint failed after job', safeJobId, 'settled:', repaintErr);
}
// adpanel:planner-send-completion — the poll is what makes the completion
// visible on the planner board: the modal closed at send time and nothing
// else repaints it when the job settles. Constraint: the poll's lifetime
// must cover the server's job deadline + queue window (see
// PLANNER_JOB_POLL_MAX_MS) and every exit from this loop is visible — a
// settled job (best-effort chat repaint, then the board reconcile here),
// budget exhaustion (offline status + one reconcile), or three
// consecutive failures (offline status + one reconcile) — never silence.
// Fire-and-forget so it can neither block nor reject into the return
// path (loadPlannerItems never rejects; it defers during drags and
// honors plannerLoadSeq): the server flips the item done on success
// (both planner sources) and leaves it active on failure/cancellation.
loadPlannerItems();
return;
}
}
// adpanel:planner-poll-registry — the ONE spawn gate for send-completion
// pollers: a job already being tracked reuses its live loop (never a second
// concurrent poller for the same job), and the registry entry is removed at
// this poller's own exit — settle, budget exhaustion, 3-strike or cancel —
// so no entry can outlive the loop it describes.
function startPlannerJobPoller(jobId, chatId, itemId = null) {
const safeJobId = Number(jobId);
if (!Number.isFinite(safeJobId) || safeJobId <= 0) return;
if (plannerJobPollers.has(safeJobId)) return;
const handle = { cancelled: false, itemId: Number(itemId) };
plannerJobPollers.set(safeJobId, handle);
pollAiAgentJob(safeJobId, chatId, handle)
.catch((err) => console.error('[ai-agent-job] Poll failed:', err))
.finally(() => {
if (plannerJobPollers.get(safeJobId) === handle) plannerJobPollers.delete(safeJobId);
});
}
// adpanel:planner-poll-registry — stops the poller(s) tracking an item's
// latest send. Called when the item's delete commits and when a toggle
// completes it (active→done only): the job the poller follows can no longer
// finish a card the user already disposed of, so the loop must exit instead
// of polling to its 30-minute budget and re-reconciling a dead card. The
// entry is removed here; the loop notices the flag at its next gate and
// exits silently.
function cancelPlannerJobPollersForItem(itemId) {
const idNum = Number(itemId);
if (!Number.isFinite(idNum)) return;
plannerJobPollers.forEach((handle, jobId) => {
if (Number(handle.itemId) === idNum) {
handle.cancelled = true;
plannerJobPollers.delete(jobId);
}
});
}
async function savePlannerItem() {
if (plannerSaveInFlight) return; // Ignore repeats while a save is still running (e.g. rapid Ctrl+Enter)
const prompt = String(plannerPromptInput?.value || '').trim();
const id = parseInt(plannerItemIdInput?.value || '', 10);
const isEditing = !Number.isNaN(id);
// An edit opened while this save is in flight must survive its completion:
// fillPlannerForm() can stash a different card into the form during the
// POST, so completion only resets when the form still refers to the item
// we just saved.
const savedEditId = isEditing ? String(id) : '';
// Ids cannot distinguish the original edit from a re-open of the SAME
// item during the flight, so the epoch decides: any editor transition
// (fillPlannerForm / clearPlannerEditState) after this point cancels the
// completion-time form resets below.
const savedEditorEpoch = plannerEditorEpoch;
const title = String(plannerTitleInput?.value || '').trim() || derivePlannerTitle(prompt);
if (!prompt) {
alert('Write a prompt first.');
plannerPromptInput?.focus();
return;
}
plannerSaveInFlight = true;
if (plannerSaveBtn) {
plannerSaveBtn.disabled = true;
plannerSaveBtn.innerHTML = `${isEditing ? 'Updating...' : 'Saving...'}`;
}
try {
// Captured on the edit (PUT) branch only — its items carry the row's
// authoritative updated_at for the re-stamp below.
let data = null;
if (!isEditing) {
const created = await plannerMutateRequest('', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, prompt })
}, 'plannerCreate');
// adpanel:planner-create-success-decoupled — the POST commit IS the
// save; the follow-up board load only repaints. The create route
// answers with the SAME fetchPlannerItemsForServer shaping as the
// GET ({ ok, itemId, items } vs { ok, items }), so seed plannerItems
// from it now — no render here (the load, or the drag settle when the
// load defers, paints it): if that load then fails or is superseded,
// the failure path still re-renders from a snapshot that contains
// the created item instead of a "last synced" board without it.
if (Array.isArray(created.items)) {
plannerItems = created.items;
// adpanel:planner-create-baseline — keep the no-render decision, but
// seed the drag no-op baseline from the RENDERED DOM instead of the
// new snapshot: the snapshot now includes the created id while the
// board does not, and the dragend detector compares DOM ids against
// this baseline — an array-derived seed would make every dragend in
// the pre-repaint window mismatch and POST a reorder for a move the
// user did not make. The array-based sync is deferred to the
// follow-up repaint: renderPlannerBoard re-derives it, and when that
// load defers behind a live drag, the drag settle path repaints and
// re-derives it — so the snapshot/DOM gap closes on every path
// without a render here. The seed itself is skipped while a drag is
// in flight: mid-drag the DOM is PARKED (the dragged card sits at
// its dragged position), so seeding from it would bake the parked
// order into the baseline, the dragend compare would match it, and
// the settle reload would repaint the pre-drag order — reverting
// the user's move. The pre-drag baseline must survive instead so
// dragend compares the dropped DOM against it: a real move
// mismatches and POSTs (the server recomputes the created item's
// position from the anchors), a no-op matches and the settle reload
// repaints and re-derives the baseline. The deferral converges:
// both the create's own follow-up load and the drag settle run
// loadPlannerItems → renderPlannerBoard →
// syncPlannerLastActiveOrder once the drag ends.
if (!plannerDragInFlight) syncPlannerLastActiveOrderFromDom();
}
} else {
// The timestamp and content version both come from the form snapshot.
data = await plannerMutateRequest(`/${encodeURIComponent(id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, prompt, expectedUpdatedAt: plannerEditingSnapshot?.updated_at ?? null, expectedEditVersion: plannerEditingSnapshot?.edit_version ?? null })
}, 'plannerUpdate');
}
const reloaded = await loadPlannerItems();
// On a failed or deferred reload the board is unverified; loadPlannerItems
// already reported that, so don't paint success over it.
// adpanel:planner-create-success-decoupled — the CREATE branch is the
// deliberate exception: the row is already committed server-side, so
// its "Prompt saved" confirmation and compose-form reset are factual
// regardless of the reload's outcome and must never be skipped. A
// failed or superseded GET used to leave the draft in Compose with an
// enabled Save button and no confirmation — the user's natural retry
// then POSTed a duplicate (the create route has no duplicate detection;
// only the 200-item cap bounds it). The EDIT branch keeps the gate:
// there a retry re-PUTs the same row, so over an unverified board the
// draft deliberately stays visible for the user to retry.
if (reloaded || !isEditing) {
setPlannerStatus('Prompt saved');
// Reset+switch only when the form still refers to the item we just
// saved: an edit opened during this in-flight save must keep its
// draft. The epoch also covers a re-open of the SAME item, whose id
// would still match below while its editor session is newer than this
// save. A draft typed (or cleared) while the POST or the reload was
// in flight is newer than the save — the reset would wipe it — so the
// inputs must still carry the submitted values for the reset to run.
// On a create this reset runs even over a failed/deferred reload (the
// retry it leaves enabled is a DUPLICATE POST, not a safe re-PUT);
// on an edit a failed reload keeps the draft so the user can see and
// retry exactly what they submitted.
const formEditId = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
const currentPrompt = String(plannerPromptInput?.value || '').trim();
const currentTitle = String(plannerTitleInput?.value || '').trim() || derivePlannerTitle(currentPrompt);
if (plannerEditorEpoch === savedEditorEpoch && formEditId === savedEditId && currentPrompt === prompt && currentTitle === title) {
resetPlannerForm();
switchPlannerTab('board');
}
// When the reset was skipped (the user typed during the save, or
// opened another edit), the form still carries a version snapshot
// from BEFORE this write — re-stamp it from the verified reload or
// the next Save would 409 against its own successful write.
const formEditIdNow = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (savedEditId && formEditIdNow === savedEditId) {
const saved = plannerItems.find((entry) => String(entry.id) === savedEditId);
if (saved && saved.title === title && saved.prompt === prompt) plannerEditingSnapshot = saved;
}
} else {
// adpanel:planner-save-restamp — the server's response items are
// authoritative for the row just written; without the re-stamp the
// next save 409s against the user's own write and misreports it as a
// teammate conflict.
const formEditIdNow = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (savedEditId && formEditIdNow === savedEditId && data && typeof data === 'object' && Array.isArray(data.items)) {
const saved = data.items.find((entry) => String(entry.id) === savedEditId);
if (saved && saved.title === title && saved.prompt === prompt) plannerEditingSnapshot = saved;
} else if (savedEditId && formEditIdNow === savedEditId && data && typeof data === 'object' && !Array.isArray(data.items)) {
// adpanel:planner-null-items — the PUT committed but its post-commit
// board re-read failed (items null): the re-stamp above has nothing
// to read, and the form may still be open on the row just written.
// A bare fire-and-forget refresh would leave that form's version
// stamp stale, so its next Save 409s planner_item_modified against
// the user's OWN commit and the 409 recovery misreports it as a
// teammate conflict. Chain a silent re-stamp onto the refresh
// instead: once it lands a fresh board, re-stamp from the reloaded
// row — but only while nothing has claimed the editor since the
// committed response arrived (same epoch and hidden id), no newer
// save is mid-flight with its own completion logic, and the stamp
// still carries the value this write obsoleted (a newer
// fillPlannerForm may already have stamped fresh). No status line,
// no refill — the user's draft stays untouched.
const epochAtSave = plannerEditorEpoch;
const staleSnapshot = plannerEditingSnapshot;
loadPlannerItems().then((reloadedLate) => {
const formEditIdLate = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (!reloadedLate || plannerSaveInFlight || plannerEditorEpoch !== epochAtSave || formEditIdLate !== savedEditId || plannerEditingSnapshot !== staleSnapshot) return;
const fresh = plannerItems.find((entry) => String(entry.id) === savedEditId);
if (fresh && fresh.title === title && fresh.prompt === prompt) plannerEditingSnapshot = fresh;
});
}
}
} catch (err) {
console.error('[planner] Save error:', err);
// Order matters: cap first, then stale-edit recovery, then the generic
// mapping. The CREATE route answers 409 { error:
// 'planner_item_limit_reached' } when the server hits its planner cap —
// a quota, not a concurrency conflict. It shares the 409 status with
// planner_item_modified but must never fall into the concurrent-edit
// branch: on a create `id` is NaN, so that branch's find() could never
// match, and the user would be told their perfectly valid draft was
// both "changed" and "deleted" before it was wiped. The check keys off
// the message, not isEditing, for the same reason.
if (err.message === 'planner_item_limit_reached') {
alert('This server has reached its planner limit (200 prompts). Delete some prompts before adding more.');
} else if (err.status === 404 && isEditing && err.message === 'Planner item not found') {
// 404 — the item was deleted by a teammate while it sat in the form.
// Clearing edit state breaks the old 404 alert loop: the next Save
// CREATES a new prompt instead of re-PUTting the dead id forever.
alert('This prompt was deleted by another user.');
// The card is gone server-side: drop it from the local snapshot too,
// so it cannot linger on the board until the next unrelated refresh.
const deadIndex = plannerItems.findIndex((entry) => Number(entry.id) === id);
if (deadIndex !== -1) {
plannerItems.splice(deadIndex, 1);
// adpanel:planner-order-baseline — the splice shrank the active set;
// the mid-drag branch below paints nothing, so keep the no-op
// baseline tracking the snapshot (the settle reload re-derives it).
syncPlannerLastActiveOrder();
if (plannerDragInFlight) {
// Same contract as loadPlannerItems: never repaint the list
// mid-drag — the dragend settle point flushes the fresh board.
plannerReloadQueuedAfterDrag = true;
} else {
// adpanel:planner-load-seq — same stale-repaint contract as the
// dragend commit: the splice makes any load request issued before
// it stale, so bump the generation; the superseded load's finally
// skips the spinner clear on a stale seq, so clear it here too.
plannerLoadSeq++;
if (plannerRefreshBtn) plannerRefreshBtn.classList.remove('spinning');
renderPlannerBoard();
// The bumped generation may have discarded an in-flight load that
// was mid-write on the status line ("Loading planner...") —
// repaint the counts its success path would have written.
setPlannerStatus(`${plannerActiveItems().length} active, ${plannerCompletedItems().length} completed`);
}
}
// Only clear when the dead id is still the one in the form: an edit
// opened during this in-flight save must not be wiped by its 404.
// The epoch extends that to a re-open of the SAME dead item, whose
// id would still match here.
const formEditId = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (plannerEditorEpoch === savedEditorEpoch && formEditId === savedEditId) {
resetPlannerForm();
switchPlannerTab('board');
} else if (savedEditId && formEditId === savedEditId) {
// adpanel:planner-dead-edit-loop — the reset was skipped by the epoch
// guard because the SAME dead item was re-opened during the save:
// the form stays bound to the deleted id and every Save re-404s into
// this branch forever. The draft must be preserved (no auto-reset),
// so point at the escape hatch persistently in the edit indicator
// the user is looking at — a status line would be overwritten by the
// next board action. A formEditId mismatch means a different, live
// item owns the form: no loop, no guidance there either.
setPlannerEditIndicator('This prompt no longer exists — press Clear to discard the form and start a new prompt.');
}
} else if (err.status === 409 && isEditing && err.message === 'planner_item_modified') {
// 409 planner_item_modified — this form lost a concurrent-edit race.
// Reload and refill so the form carries the winning version snapshot;
// the next Save can then succeed. The conflict belongs to the item we
// were saving, never to a draft opened meanwhile: when the form was
// repurposed while this save was in flight, running the recovery here
// would stamp that draft into the saved item's identity and cross-
// write the two on the next Save, so only the board may refresh.
const conflictFormId = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (conflictFormId !== savedEditId) {
// A different edit owns the form now — board refresh only, the form
// and its draft stay untouched.
loadPlannerItems();
} else {
// adpanel:planner-409-recovery-promise — the reload decides which
// promise the alert may make, so it runs BEFORE the alert: only a
// reload that actually re-stamped the edit snapshot lets
// "saving will apply them on top of the latest version" come true.
// When the reload failed, the form keeps its stale snapshot and
// every retry re-409s until a refresh succeeds — say that instead
// of the promise. The draft is kept either way.
const reloadedAfterConflict = await loadPlannerItems();
// The reload above awaited: re-read the form id before any form
// mutation — an edit opened during the load owns the form now and
// its draft must survive untouched.
const afterLoadFormId = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
if (afterLoadFormId === savedEditId) {
const fresh = plannerItems.find((entry) => Number(entry.id) === id);
if (reloadedAfterConflict && fresh) {
alert('This prompt was changed by another user. Your unsaved edits were kept — saving will apply them on top of the latest version.');
// Keep the user's draft: fillPlannerForm re-stamps the hidden id,
// button label, edit indicator and — critically — the FRESH
// edit snapshot, but it would overwrite
// the in-progress text. Capture the draft before the refill and
// re-apply it after, so the unsaved edits survive while the form
// still carries the fresh version stamp (the next Save succeeds
// instead of 409ing on a stale snapshot).
const draftTitle = plannerTitleInput?.value;
const draftPrompt = plannerPromptInput?.value;
fillPlannerForm(fresh);
if (plannerTitleInput) plannerTitleInput.value = draftTitle ?? '';
if (plannerPromptInput) plannerPromptInput.value = draftPrompt ?? '';
} else if (reloadedAfterConflict) {
// The item vanished in the same race — recover exactly like a
// 404, but only reset when no newer editor session (same-item
// re-open included) started during the flight.
alert('This prompt was deleted by another user.');
if (plannerEditorEpoch === savedEditorEpoch) {
resetPlannerForm();
switchPlannerTab('board');
} else if (savedEditId) {
// adpanel:planner-dead-edit-loop — same escape hatch as the 404
// skip, same edit-only guard: the form still holds the vanished
// id (checked above) and a same-item re-open started a newer
// session, so without guidance every Save re-409s into this
// branch forever. savedEditId is non-empty only on a genuine
// edit — the '' create sentinel would match a create-mode form
// and claim a prompt that never existed. The draft is kept; the
// Clear button is the way out.
setPlannerEditIndicator('This prompt no longer exists — press Clear to discard the form and start a new prompt.');
}
} else {
// The reload failed: the form still carries the STALE version
// snapshot, so the success promise above would be false — the
// accurate message points at Refresh, the only way a Save can
// succeed from here.
alert('This prompt was changed by another user. Your unsaved edits were kept, but the board could not be refreshed — saving will keep conflicting until a refresh succeeds. Press Refresh and try again.');
}
}
// If the reload itself failed — or the form was repurposed during
// it — the form keeps the user's draft; a failed load already
// reported itself on the status line. The failed-reload alert only
// fires while the conflicted item still owns the form, matching the
// repurposed-form branch above (board refresh, no alert).
}
} else if (!err.isPlannerAuthError) {
// Other errors keep their message (a 401 still only raises the
// session-expired overlay).
alert(err.message || 'Failed to save prompt');
}
} finally {
plannerSaveInFlight = false;
if (plannerSaveBtn) {
// Derive the label from the hidden id so it can never claim "Update"
// after edit state was cleared mid-save (e.g. modal reopened).
const stillEditing = !Number.isNaN(parseInt(plannerItemIdInput?.value || '', 10));
plannerSaveBtn.disabled = false;
plannerSaveBtn.innerHTML = stillEditing
? 'Update Prompt'
: 'Save Prompt';
}
}
}
async function togglePlannerItem(item) {
if (!item) return;
// In-flight brake (plannerItemOpsInFlight), same shape as
// plannerSaveInFlight/plannerSendAgentInFlight but keyed per item: a
// second click while this toggle is still running is ignored silently
// instead of firing a second PUT.
if (plannerItemOpsInFlight.has(Number(item.id))) return;
plannerItemOpsInFlight.add(Number(item.id));
try {
// Toggle sends ONLY the done flag. The server PUT detects fields via
// hasOwnProperty and preserves the canonical stored title/prompt when
// they are absent, so a stale client cache can never clobber a
// teammate's concurrent edits to the item's content.
await plannerMutateRequest(`/${encodeURIComponent(item.id)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isDone: !Number(item.is_done) })
}, 'plannerUpdate');
// adpanel:planner-poll-registry — completing the card (active→done
// direction: item.is_done still holds the pre-toggle value) ends the
// purpose of the send-completion poller tracking it. A done→active
// restore must NOT cancel: a job can still be live for a restored card
// and its settle reconcile is what repaints the board.
if (!Number(item.is_done)) cancelPlannerJobPollersForItem(item.id);
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus(Number(item.is_done) ? 'Prompt moved back to active' : 'Prompt marked as completed');
} catch (err) {
console.error('[planner] Toggle error:', err);
// adpanel:planner-toggle-gone — the PUT route answers 404 'Planner item
// not found' when the row was deleted by a teammate mid-flight (it used
// to return a silent ok), and 409 'planner_item_modified' from the flip
// branch's no-CAS same-state guard (defense-in-depth, practically
// unreachable). Both mean the server board is authoritative: reload it
// so the dead/stale card drops instead of alerting raw tokens the user
// cannot act on.
if (err.status === 404) {
// The item is gone server-side — same recovery as savePlannerItem's
// 404 branch: reload (a failed load reports itself on the status
// line), then say why the card vanished.
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus('Prompt no longer exists');
} else if (err.status === 409) {
// Same posture as the dragend conflict handling: silent reload, no
// alert of the raw 'planner_item_modified' token.
await loadPlannerItems();
} else if (!err.isPlannerAuthError) {
alert(err.message || 'Failed to update prompt');
}
} finally {
plannerItemOpsInFlight.delete(Number(item.id));
}
}
async function deletePlannerItem(item) {
if (!item) return;
// Same per-item in-flight brake as togglePlannerItem, checked at entry
// and cleared in the finally: the second DELETE of a double-click used
// to 404 (the first had already removed the row) and alert "Planner
// item not found". Re-entrant clicks are ignored silently.
if (plannerItemOpsInFlight.has(Number(item.id))) return;
plannerItemOpsInFlight.add(Number(item.id));
try {
const deleteConfirmTitle = dialogText(item.title || derivePlannerTitle(item.prompt));
const expectedEditVersion = item.edit_version;
// adpanel:planner-in-app-confirm — keep the per-item brake across the dialog.
if (!(await storeConfirm(`Delete "${deleteConfirmTitle}"?`))) return;
await plannerMutateRequest(`/${encodeURIComponent(item.id)}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ expectedEditVersion })
}, 'plannerDelete');
// adpanel:planner-poll-registry — the row is committed gone: stop the
// send-completion poller tracking this item so the loop cannot keep
// polling (and reconciling the board for) a card that no longer exists.
cancelPlannerJobPollersForItem(item.id);
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus('Prompt deleted');
} catch (err) {
console.error('[planner] Delete error:', err);
// adpanel:planner-delete-gone — the DELETE route answers 404 'Planner
// item not found' when a teammate deleted the row mid-flight; the board
// is authoritative — reload so the dead card drops.
if (err.status === 404) {
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus('Prompt no longer exists');
} else if (err.status === 409 && err.message === 'planner_item_modified') {
const reloaded = await loadPlannerItems();
if (reloaded) setPlannerStatus('Prompt changed. Review the latest version before deleting.', true);
} else if (!err.isPlannerAuthError) {
alert(err.message || 'Failed to delete prompt');
}
} finally {
plannerItemOpsInFlight.delete(Number(item.id));
}
}
async function handlePlannerListClick(e) {
// adpanel:planner-drag-trailing-click — Chromium fires a trailing click on
// the drag source right after dragend, so a canceled drag (Esc mid-drag,
// release outside the list) would resolve through the whole-card send
// action even though no drop was ever accepted over the list. The 200ms
// window is a deliberate trade-off, not airtight: a fast drag-release →
// re-click CAN land inside it and is then silently swallowed (one dead
// click the user simply repeats), while the suppression can only prevent
// an action, never cause one — the one cost it must never carry is
// letting Chromium's trailing click resolve to the billable send. The
// check is deliberately GLOBAL, not target-scoped: after a committing
// drag the synthetic click can land on a DIFFERENT card that slid under
// the cursor, so keying on the clicked element would re-open exactly the
// leak this closes. Firefox fires no click after dragend at all, so the
// window costs it nothing. The grip path is unaffected (it early-returns
// below regardless), and dragover/drop/reorder logic never runs a click.
if (Date.now() - plannerDragEndAt < 200) return;
// A press-and-release on the grip that never crosses the native drag
// threshold still fires a click; it must never resolve to "send".
if (e.target.closest('.planner-drag-handle')) return;
const itemEl = e.target.closest('.planner-item');
if (!itemEl) return;
const itemId = parseInt(itemEl.dataset.id, 10);
if (Number.isNaN(itemId)) return;
const item = plannerItems.find((entry) => Number(entry.id) === itemId);
if (!item) return;
const actionEl = e.target.closest('[data-planner-action]');
const action = actionEl?.dataset?.plannerAction;
if (!action) return;
if (action === 'send') {
await sendPlannerPromptToAgent(item);
} else if (action === 'edit') {
// adpanel:planner-edit-draft-guard — fillPlannerForm overwrites the
// compose inputs, so clicking Edit used to silently destroy a
// typed-but-unsaved draft (every other path — the 409 recovery, tab
// switches, modal reopen — deliberately preserves it). When the form
// holds a non-empty draft NOT bound to the clicked item (empty hidden
// id or a different one), confirm before overwriting; a decline leaves
// the form untouched. A draft bound to the SAME item is a re-open of
// the item being edited and must not prompt. The guard lives here, not
// in fillPlannerForm, because the 409 recovery's refill calls it
// directly to re-stamp the form around a draft it preserves itself.
const formEditId = plannerItemIdInput ? String(plannerItemIdInput.value || '') : '';
const draftTitle = String(plannerTitleInput?.value || '').trim();
const draftPrompt = String(plannerPromptInput?.value || '').trim();
const holdsUnboundDraft = (draftTitle || draftPrompt) && formEditId !== String(item.id ?? '');
if (holdsUnboundDraft && !(await storeConfirm('Your unsaved prompt draft will be replaced by this item — continue?'))) {
return;
}
fillPlannerForm(item);
} else if (action === 'toggle') {
await togglePlannerItem(item);
} else if (action === 'delete') {
await deletePlannerItem(item);
}
}
if (plannerActiveList) {
plannerActiveList.addEventListener('click', (e) => {
handlePlannerListClick(e).catch((err) => console.error('[planner] Active list error:', err));
});
}
if (plannerCompletedList) {
plannerCompletedList.addEventListener('click', (e) => {
handlePlannerListClick(e).catch((err) => console.error('[planner] Completed list error:', err));
});
}
if (plannerModalClose) plannerModalClose.addEventListener('click', closePlannerModal);
if (plannerRefreshBtn) plannerRefreshBtn.addEventListener('click', loadPlannerItems);
if (plannerOpenComposeBtn) {
plannerOpenComposeBtn.addEventListener('click', () => {
resetPlannerForm();
switchPlannerTab('compose');
});
}
if (plannerResetBtn) plannerResetBtn.addEventListener('click', resetPlannerForm);
if (plannerEditCancelBtn) plannerEditCancelBtn.addEventListener('click', resetPlannerForm);
if (plannerSaveBtn) plannerSaveBtn.addEventListener('click', savePlannerItem);
plannerTabs.forEach((tab) => {
tab.addEventListener('click', () => {
// Re-entering Compose from the Board drops stale edit state (hidden id +
// button label) so a new prompt can never PUT over the last edited item;
// the draft is kept. Edit never passes through here: fillPlannerForm
// calls switchPlannerTab directly and re-applies edit state itself.
if (tab.dataset.tab === 'compose' && plannerCurrentTab !== 'compose') clearPlannerEditState();
switchPlannerTab(tab.dataset.tab);
});
});
if (plannerModal) {
plannerModal.addEventListener('click', (e) => {
if (e.target === plannerModal || e.target.classList.contains('planner-glass-layer')) {
closePlannerModal();
}
});
}
if (plannerPromptInput) {
plannerPromptInput.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
savePlannerItem();
}
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && plannerModal?.classList.contains('show')) {
closePlannerModal();
} else if (e.key === 'Escape' && plannerModal?.classList.contains('adpanel-page-active')) {
// adpanel:install-modal-teardown — once the install overlay has
// stripped .show, the inline-mode planner page is still visible via
// .adpanel-page-active; Esc must still run closePlannerModal's full
// teardown instead of doing nothing.
closePlannerModal();
}
});
const clearConsoleModal = document.getElementById('clearConsoleModal');
const clearConsoleConfirm = document.getElementById('clearConsoleConfirm');
const clearConsoleCancel = document.getElementById('clearConsoleCancel');
const clearConsoleToggleWrapper = document.getElementById('clearConsoleToggleWrapper');
const dockWrap = document.querySelector('.dock-wrap');
if (clearConsoleToggleWrapper) {
clearConsoleToggleWrapper.addEventListener('click', function (e) {
var cb = document.getElementById('clearConsoleNoAsk');
if (!cb) return;
if (e.target === cb) return;
e.preventDefault();
cb.checked = !cb.checked;
});
}
function toggleDock(show) {
if (!dockWrap) return;
dockWrap.classList.toggle('dock-hidden', !show);
}
function closeClearConsoleModal() {
if (!clearConsoleModal) return;
clearConsoleModal.classList.remove('show');
setTimeout(function () {
if (!clearConsoleModal.classList.contains('show')) {
clearConsoleModal.style.display = 'none';
toggleDock(true);
}
}, 300);
}
function openClearConsoleModal() {
if (!clearConsoleModal) return;
clearConsoleModal.style.display = 'flex';
requestAnimationFrame(function () {
clearConsoleModal.classList.add('show');
toggleDock(false);
});
var cb = document.getElementById('clearConsoleNoAsk');
if (cb) cb.checked = false;
}
if (clearConsoleConfirm) {
clearConsoleConfirm.addEventListener('click', async function () {
// Local-only clear: wipes this browser's console view. There is
// deliberately NO server call here (no /console-clear endpoint exists);
// consoleClearWatermarkTs + the preserved seen-entry dedupe set keep
// gap-syncs (tab visibility, socket/EventSource reconnects) from
// re-rendering the cleared lines. Other users and the server-side
// history buffer are not affected.
resetLocalConsoleHistorySession();
var cb = document.getElementById('clearConsoleNoAsk');
if (cb && cb.checked) {
currentUserPreferences.clear_console_no_ask = true;
saveClearConsoleNoAskToStorage(true);
try {
var resp = await fetch('/api/me/preferences', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS),
body: JSON.stringify({ preferences: { clear_console_no_ask: true } })
});
var data = await resp.json();
if (data && data.ok) {
mergeCurrentUserPreferences(data.preferences || { clear_console_no_ask: true });
console.log('[ClearConsole] Preference saved successfully');
} else {
console.error('[ClearConsole] Save failed:', data);
}
} catch (err) {
console.error('[ClearConsole] Failed to save preference:', err);
}
}
closeClearConsoleModal();
});
}
if (clearConsoleCancel) {
clearConsoleCancel.addEventListener('click', function () {
closeClearConsoleModal();
});
}
if (clearConsoleModal) {
clearConsoleModal.addEventListener('click', function (e) {
if (e.target === clearConsoleModal || e.target.classList.contains('clear-console-glass-layer')) {
closeClearConsoleModal();
}
});
}
// ===== Minecraft EULA prompt =====
// Shown in the console when the node refuses to start a Minecraft template
// server because eula.txt is missing or eula=false. Only users that are
// allowed to write files on the server see the popup; the accept request is
// additionally permission-checked server-side.
const eulaModal = document.getElementById('eulaModal');
const eulaAcceptBtn = document.getElementById('eulaAccept');
const eulaCancelBtn = document.getElementById('eulaCancel');
let eulaAcceptInFlight = false;
let resumeStartAfterEula = false;
function canAcceptMinecraftEula() {
return hasPerm('files_write') || hasPerm('files_create');
}
function isEulaPopupVisible() {
return !!(eulaModal && eulaModal.classList.contains('show'));
}
function closeEulaModal() {
resumeStartAfterEula = false;
if (!eulaModal) return;
eulaModal.classList.remove('show');
setTimeout(function () {
if (!eulaModal.classList.contains('show')) {
eulaModal.style.display = 'none';
toggleDock(true);
}
}, 300);
}
function isServerInInstallMode() {
if (isInstallingActive) return true;
if (powerState === POWER_STATE.INSTALLING) return true;
if (powerTransition === POWER_STATE.INSTALLING) return true;
if (document.body && document.body.classList.contains('server-is-installing')) return true;
if (window.__ADPANEL_IS_INSTALLING__) return true;
if (consoleInstallingOverlay && consoleInstallingOverlay.classList.contains('active')) return true;
return false;
}
let pendingEulaPopup = false;
function maybeShowEulaPopup({ resumeStart = false } = {}) {
if (!eulaModal || !canAcceptMinecraftEula()) return false;
if (resumeStart) resumeStartAfterEula = true;
if (isEulaPopupVisible()) return true;
// Do NOT show the EULA popup while the server is still in installation mode.
if (isServerInInstallMode()) {
pendingEulaPopup = true;
return true;
}
pendingEulaPopup = false;
eulaModal.style.display = 'flex';
requestAnimationFrame(function () {
eulaModal.classList.add('show');
toggleDock(false);
});
return true;
}
// Proactively prompt when the console is opened for a Minecraft server whose
// eula.txt is missing or eula=false (e.g. right after creation), instead of
// waiting for the first blocked start attempt.
async function checkMinecraftEulaOnLoad(retries = 3) {
try {
if (!canAcceptMinecraftEula()) return;
const resp = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/eula`, {
credentials: 'include', cache: 'no-store', signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS)
});
if (!resp.ok) {
if (retries > 0 && (resp.status === 409 || resp.status === 502 || resp.status === 503 || resp.status === 504)) {
setTimeout(() => checkMinecraftEulaOnLoad(retries - 1), 1000);
}
return;
}
const data = await resp.json().catch(() => null);
if (data && data.ok && data.required) {
maybeShowEulaPopup();
}
} catch (err) {
if (retries > 0) {
setTimeout(() => checkMinecraftEulaOnLoad(retries - 1), 1000);
}
}
}
if (eulaAcceptBtn) {
eulaAcceptBtn.addEventListener('click', async function () {
if (eulaAcceptInFlight) return;
eulaAcceptInFlight = true;
eulaAcceptBtn.disabled = true;
try {
const resp = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/eula/accept`, {
method: 'POST',
credentials: 'include',
signal: AbortSignal.timeout(CONSOLE_REQUEST_TIMEOUT_MS)
});
const data = await resp.json().catch(() => null);
if (!resp.ok || !data || data.ok === false) {
const message = (data && (data.detail || data.error)) || `HTTP ${resp.status}`;
alert('Could not accept the Minecraft EULA: ' + message);
return;
}
const shouldResumeStart = resumeStartAfterEula;
closeEulaModal();
if (shouldResumeStart && isPowerActionAllowed('run')) run();
appendConsoleNotice('[ADPanel] Minecraft EULA accepted.');
} catch (err) {
alert('Could not accept the Minecraft EULA: ' + ((err && err.message) || err));
} finally {
eulaAcceptInFlight = false;
eulaAcceptBtn.disabled = false;
}
});
}
function cancelMinecraftEula() {
const wasStartRequested = resumeStartAfterEula;
closeEulaModal();
if (wasStartRequested) appendConsoleNotice('[ADPanel] Minecraft EULA not accepted — server start cancelled.');
}
if (eulaCancelBtn) {
eulaCancelBtn.addEventListener('click', cancelMinecraftEula);
}
if (eulaModal) {
eulaModal.addEventListener('click', function (e) {
if (e.target === eulaModal || e.target.classList.contains('clear-console-glass-layer')) {
cancelMinecraftEula();
}
});
}
const resourceStatsPopup = document.getElementById('resourceStatsPopup');
const resourceStatsClose = document.getElementById('resourceStatsClose');
const resMemoryLabel = document.getElementById('resMemoryLabel');
const resMemoryBar = document.getElementById('resMemoryBar');
const resDiskLabel = document.getElementById('resDiskLabel');
const resDiskBar = document.getElementById('resDiskBar');
const resCpuLabel = document.getElementById('resCpuLabel');
const resCpuBar = document.getElementById('resCpuBar');
const resNetworkInboundLabel = document.getElementById('resNetworkInboundLabel');
const resNetworkOutboundLabel = document.getElementById('resNetworkOutboundLabel');
const resUptimeLabel = document.getElementById('resUptimeLabel');
// adpanel:figma-resources - the "Resources Usage" card on the redesigned bot
// page (figma* ids) replaced the old resourceStatsPopup visually, but nothing
// ever subscribed to live data for it since subscribeResourceStats() only ran
// when the (now hidden) popup was opened. Feed the same live data into these
// elements directly instead of relying on the fragile window.io monkeypatch.
const figmaConnectivityVal = document.getElementById('figmaConnectivityVal');
const figmaRamLabel = document.getElementById('figmaRamLabel');
const figmaRamBar = document.getElementById('figmaRamBar');
const figmaCpuLabel = document.getElementById('figmaCpuLabel');
const figmaCpuBar = document.getElementById('figmaCpuBar');
const figmaStorageLabel = document.getElementById('figmaStorageLabel');
const figmaStorageBar = document.getElementById('figmaStorageBar');
const figmaUptimeLabel = document.getElementById('figmaUptimeLabel');
const figmaNetworkInLabel = document.getElementById('figmaNetworkInLabel');
const figmaNetworkOutLabel = document.getElementById('figmaNetworkOutLabel');
let resourceStatsUptimeInterval = null;
let lastFetchedUptime = null;
let uptimeFetchedAt = null;
let resourceStatsSubscribed = false;
let lastNetworkInboundBytes = 0;
let lastNetworkOutboundBytes = 0;
function resetNetworkLabelsToZero() {
lastNetworkInboundBytes = 0;
lastNetworkOutboundBytes = 0;
if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = '0 B';
if (figmaNetworkInLabel) figmaNetworkInLabel.textContent = '0 B';
if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = '0 B';
if (figmaNetworkOutLabel) figmaNetworkOutLabel.textContent = '0 B';
}
function readNetworkBytes(network, keys) {
if (!network || typeof network !== 'object') return null;
for (const key of keys) {
const value = Number(network[key]);
if (Number.isFinite(value) && value >= 0) return value;
}
return null;
}
// adpanel:figma-resources - render the "used / total" value with the "/"
// separator dimmed (#909090) to match the Figma design, while the used and
// total figures keep the normal value color.
function figmaSeparatedValueHtml(usedText, totalText) {
return `${escapeHtml(usedText)} / ${escapeHtml(totalText)}`;
}
function onResourceData(data) {
if (!data || !data.server) return;
if (String(data.server).trim().toLowerCase() !== String(bot).trim().toLowerCase()) return;
const isRunning = data.status === 'running' || data.status === 'online';
if (data.memory && isRunning) {
let usedMb, limitMb, pct;
if (typeof data.memory === 'object') {
usedMb = data.memory.used || 0;
limitMb = data.memory.total || 0;
pct = data.memory.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0);
} else {
usedMb = data.memory; limitMb = 0; pct = 0;
}
const memoryText = limitMb > 0
? `${formatBytes(usedMb * 1048576)} / ${formatBytes(limitMb * 1048576)} (${Math.round(pct)}%)`
: `${formatBytes(usedMb * 1048576)} / Unlimited`;
if (resMemoryLabel) resMemoryLabel.textContent = memoryText;
if (resMemoryBar) resMemoryBar.style.width = `${pct}%`;
if (figmaRamLabel) figmaRamLabel.innerHTML = limitMb > 0
? figmaSeparatedValueHtml(formatBytes(usedMb * 1048576), formatBytes(limitMb * 1048576))
: figmaSeparatedValueHtml(formatBytes(usedMb * 1048576), 'Unlimited');
if (figmaRamBar) figmaRamBar.style.width = `${pct}%`;
} else {
if (resMemoryLabel) resMemoryLabel.textContent = '—';
if (resMemoryBar) resMemoryBar.style.width = '0%';
if (figmaRamLabel) figmaRamLabel.textContent = '—';
if (figmaRamBar) figmaRamBar.style.width = '0%';
}
if (data.disk) {
let usedGb, limitGb, pct;
if (typeof data.disk === 'object') {
usedGb = data.disk.used || 0;
limitGb = data.disk.total || 0;
pct = data.disk.percent ?? (limitGb > 0 ? Math.min(100, Math.round((usedGb / limitGb) * 100)) : 0);
} else {
usedGb = data.disk / 1024; limitGb = 0; pct = 0;
}
// adpanel:backup-storage - storage shown as the combined total (server
// files + backups). When backups exist, append the breakdown so it is
// clear how much of the quota the backups occupy.
const serverMb = (data.disk && typeof data.disk === 'object') ? data.disk.serverMb : null;
const backupsMb = (data.disk && typeof data.disk === 'object') ? data.disk.backupsMb : null;
let diskText = limitGb > 0
? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)`
: `${formatBytes(usedGb * 1073741824)} / Unlimited`;
if (Number.isFinite(backupsMb) && backupsMb > 0 && Number.isFinite(serverMb)) {
diskText += ` — files ${formatBytes(serverMb * 1048576)} + backups ${formatBytes(backupsMb * 1048576)}`;
}
if (resDiskLabel) resDiskLabel.textContent = diskText;
if (resDiskBar) resDiskBar.style.width = `${pct}%`;
if (figmaStorageLabel) figmaStorageLabel.innerHTML = limitGb > 0
? figmaSeparatedValueHtml(formatBytes(usedGb * 1073741824), formatBytes(limitGb * 1073741824))
: figmaSeparatedValueHtml(formatBytes(usedGb * 1073741824), 'Unlimited');
if (figmaStorageBar) figmaStorageBar.style.width = `${pct}%`;
} else {
if (resDiskLabel) resDiskLabel.textContent = '—';
if (resDiskBar) resDiskBar.style.width = '0%';
if (figmaStorageLabel) figmaStorageLabel.textContent = '—';
if (figmaStorageBar) figmaStorageBar.style.width = '0%';
}
if (data.cpu !== undefined && data.cpu !== null && isRunning) {
const cpuMax = data.cpuLimit || 100;
const cpuPct = Math.min(cpuMax, Math.round(data.cpu));
const cpuBarWidth = cpuMax > 0 ? Math.min(100, (cpuPct / cpuMax) * 100) : 0;
if (resCpuLabel) resCpuLabel.textContent = `${cpuPct}% / ${Math.round(cpuMax)}%`;
if (resCpuBar) resCpuBar.style.width = `${cpuBarWidth}%`;
if (figmaCpuLabel) figmaCpuLabel.innerHTML = figmaSeparatedValueHtml(`${cpuPct}%`, `${Math.round(cpuMax)}%`);
if (figmaCpuBar) figmaCpuBar.style.width = `${cpuBarWidth}%`;
} else {
if (resCpuLabel) resCpuLabel.textContent = '—';
if (resCpuBar) resCpuBar.style.width = '0%';
if (figmaCpuLabel) figmaCpuLabel.textContent = '—';
if (figmaCpuBar) figmaCpuBar.style.width = '0%';
}
const network = data.network || null;
const inboundBytes = readNetworkBytes(network, ['inboundBytes', 'rxBytes', 'receivedBytes']);
const outboundBytes = readNetworkBytes(network, ['outboundBytes', 'txBytes', 'transmittedBytes']);
if (inboundBytes !== null && isRunning) {
lastNetworkInboundBytes = inboundBytes;
if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = formatBytes(lastNetworkInboundBytes);
if (figmaNetworkInLabel) figmaNetworkInLabel.textContent = formatBytes(lastNetworkInboundBytes);
} else {
lastNetworkInboundBytes = 0;
if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = isRunning ? '0 B' : '—';
if (figmaNetworkInLabel) figmaNetworkInLabel.textContent = isRunning ? '0 B' : '—';
}
if (outboundBytes !== null && isRunning) {
lastNetworkOutboundBytes = outboundBytes;
if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = formatBytes(lastNetworkOutboundBytes);
if (figmaNetworkOutLabel) figmaNetworkOutLabel.textContent = formatBytes(lastNetworkOutboundBytes);
} else {
lastNetworkOutboundBytes = 0;
if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = isRunning ? '0 B' : '—';
if (figmaNetworkOutLabel) figmaNetworkOutLabel.textContent = isRunning ? '0 B' : '—';
}
if (data.uptime && data.uptime > 0 && isRunning) {
lastFetchedUptime = data.uptime;
uptimeFetchedAt = Date.now();
if (resUptimeLabel) resUptimeLabel.textContent = formatUptime(data.uptime);
if (figmaUptimeLabel) figmaUptimeLabel.textContent = formatUptime(data.uptime);
startUptimeCounter();
} else {
lastFetchedUptime = null;
uptimeFetchedAt = null;
stopUptimeCounter();
const uptimeText = isRunning ? 'Starting...' : 'Offline';
if (resUptimeLabel) resUptimeLabel.textContent = uptimeText;
if (figmaUptimeLabel) figmaUptimeLabel.textContent = uptimeText;
}
}
function subscribeResourceStats() {
if (resourceStatsSubscribed) return;
resourceStatsSubscribed = true;
socket.on('resources:data', onResourceData);
socket.emit('resources:subscribe', { server: bot });
}
function unsubscribeResourceStats() {
if (!resourceStatsSubscribed) return;
resourceStatsSubscribed = false;
socket.off('resources:data', onResourceData);
socket.emit('resources:unsubscribe', { server: bot });
stopUptimeCounter();
}
// adpanel:figma-resources - the Figma "Resources Usage" card is always
// visible on this page (it isn't a toggleable popup), so keep it subscribed
// to live data for the whole lifetime of the page instead of only while the
// legacy resourceStatsPopup happens to be open.
socket.on('connect', () => {
resourceStatsSubscribed = false;
subscribeResourceStats();
});
subscribeResourceStats();
function startUptimeCounter() {
stopUptimeCounter();
if (lastFetchedUptime === null || uptimeFetchedAt === null) return;
resourceStatsUptimeInterval = setInterval(() => {
if (lastFetchedUptime === null || uptimeFetchedAt === null) {
stopUptimeCounter();
return;
}
const elapsed = Math.floor((Date.now() - uptimeFetchedAt) / 1000);
const currentUptime = lastFetchedUptime + elapsed;
const uptimeText = formatUptime(currentUptime);
if (resUptimeLabel) resUptimeLabel.textContent = uptimeText;
if (figmaUptimeLabel) figmaUptimeLabel.textContent = uptimeText;
}, 1000);
}
function stopUptimeCounter() {
if (resourceStatsUptimeInterval) {
clearInterval(resourceStatsUptimeInterval);
resourceStatsUptimeInterval = null;
}
}
function formatUptime(seconds) {
if (!seconds || seconds < 0) return '—';
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
const parts = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (mins > 0) parts.push(`${mins}m`);
if (secs > 0 || parts.length === 0) parts.push(`${secs}s`);
return parts.join(' ');
}
function openResourceStatsPopup() {
if (!resourceStatsPopup) return;
resourceStatsPopup.classList.add('visible');
if (floatingSidebar && floatingSidebar.matches(':hover')) {
resourceStatsPopup.classList.add('sidebar-expanded');
}
subscribeResourceStats();
}
function closeResourceStatsPopup() {
if (!resourceStatsPopup) return;
resourceStatsPopup.classList.remove('visible');
resourceStatsPopup.classList.remove('sidebar-expanded');
// adpanel:figma-resources - do NOT unsubscribe here. The always-visible
// Figma "Resources Usage" card relies on this same subscription staying
// active for the whole page lifetime, not just while the legacy popup
// (now hidden) is open.
}
if (floatingSidebar && resourceStatsPopup) {
floatingSidebar.addEventListener('mouseenter', () => {
if (resourceStatsPopup.classList.contains('visible')) {
resourceStatsPopup.classList.add('sidebar-expanded');
}
});
floatingSidebar.addEventListener('mouseleave', () => {
resourceStatsPopup.classList.remove('sidebar-expanded');
});
}
if (resourceStatsClose) resourceStatsClose.addEventListener('click', closeResourceStatsPopup);
document.addEventListener('click', (e) => {
if (resourceStatsPopup && resourceStatsPopup.classList.contains('visible')) {
if (!resourceStatsPopup.contains(e.target) && !e.target.closest('[data-action="open-resource-stats"]')) {
closeResourceStatsPopup();
}
}
});
const openResourceStatsTab = document.getElementById("openResourceStatsTab");
if (openResourceStatsTab) {
openResourceStatsTab.addEventListener("click", () => {
window.open(`/server/${encodeURIComponent(bot)}/resources`, 'ResourceStats', 'width=400,height=500,resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no');
closeResourceStatsPopup();
});
}
if (storeModalClose) storeModalClose.addEventListener('click', closeStoreModal);
if (storePrefClose) storePrefClose.addEventListener('click', closeStorePrefModal);
if (storePrefModal) storePrefModal.addEventListener('click', (e) => { if (e.target === storePrefModal) closeStorePrefModal(); });
if (storeTabVersions) storeTabVersions.addEventListener('click', async () => {
const { template: tpl } = resolveStoreTemplate();
if (tpl === 'fivem') {
try {
const data = await fetchStoreProviders();
const providers = Array.isArray(data.providers) ? data.providers : [];
const fivemProvider = providers.find(p => String(p.id || p.provider || '').toLowerCase() === 'fivem') || providers[0];
if (fivemProvider) {
await openProviderDetails(fivemProvider, { direct: true });
return;
}
} catch { }
}
renderStoreProvidersView();
});
if (storeTabPlugins) storeTabPlugins.addEventListener('click', () => {
if (storeTabPlugins.classList.contains('hidden')) return;
renderPluginsUI();
});
function focusConsole() { openInfoModal(); }
function clearSelection() {
selectedEntries.clear();
if (selectAllToggle) selectAllToggle.checked = false;
updateSelectionUI();
}
function updateSelectionUI() {
if (!entriesEl) return;
// adpanel:fm-truncated-select-all — the truncation notice row carries the
// `.entry` class for styling but is not a selectable row, so `.entry`
// selections must exclude it or allSelected can never become true.
const entries = Array.from(entriesEl.querySelectorAll('.entry:not(.truncated-note)'));
entries.forEach(li => {
const rel = li.dataset.relPath || "";
const isSelected = selectedEntries.has(rel);
li.classList.toggle('selected', isSelected);
li.classList.toggle('selectable', entries.length > 0);
const cb = li.querySelector('.entry-select-checkbox');
if (cb) cb.checked = isSelected;
});
const allSelected = entries.length > 0 && entries.every(li => selectedEntries.has(li.dataset.relPath || ""));
if (selectAllToggle) selectAllToggle.checked = allSelected;
if (bulkDeleteBtn) bulkDeleteBtn.classList.toggle('show', selectedEntries.size > 0 && hasPerm('files_delete'));
if (bulkArchiveBtn) bulkArchiveBtn.classList.toggle('show', selectedEntries.size > 0 && hasPerm('files_archive'));
// Top action bar switching: Default (New, Upload, Uploader) vs Selection (Download, Rename, Archive, Unarchive, Delete)
const count = selectedEntries.size;
if (fmDefaultActions && fmSelectionActions) {
if (count === 0) {
fmDefaultActions.classList.remove('hidden');
fmDefaultActions.style.display = "inline-flex";
fmSelectionActions.classList.add('hidden');
fmSelectionActions.style.display = "none";
} else {
fmDefaultActions.classList.add('hidden');
fmDefaultActions.style.display = "none";
fmSelectionActions.classList.remove('hidden');
fmSelectionActions.style.display = "inline-flex";
if (count === 1) {
const [singleRel] = Array.from(selectedEntries);
const singleLi = entries.find(el => el.dataset.relPath === singleRel);
const isDir = singleLi ? singleLi.dataset.isDir === "true" : false;
const fileName = (singleRel || "").split('/').pop() || "";
const isArchive = !isDir && EXPLORER_ARCHIVE_EXTENSION.test(fileName);
const canDownload = !isDir && hasPerm('files_read');
const canRename = hasPerm('files_rename');
const canUnarchive = isArchive && hasPerm('files_create');
const canArchive = hasPerm('files_archive');
const canDelete = hasPerm('files_delete');
if (fmDownloadBtn) {
fmDownloadBtn.classList.toggle('hidden', !canDownload);
fmDownloadBtn.style.display = canDownload ? "inline-flex" : "none";
}
if (fmRenameBtn) {
fmRenameBtn.classList.toggle('hidden', !canRename);
fmRenameBtn.style.display = canRename ? "inline-flex" : "none";
}
if (fmUnarchiveBtn) {
fmUnarchiveBtn.classList.toggle('hidden', !canUnarchive);
fmUnarchiveBtn.style.display = canUnarchive ? "inline-flex" : "none";
}
if (fmArchiveBtn) {
fmArchiveBtn.classList.toggle('hidden', !canArchive);
fmArchiveBtn.style.display = canArchive ? "inline-flex" : "none";
}
if (fmDeleteBtn) {
fmDeleteBtn.classList.toggle('hidden', !canDelete);
fmDeleteBtn.style.display = canDelete ? "inline-flex" : "none";
}
} else {
// Multiple items selected
const canArchive = hasPerm('files_archive');
const canDelete = hasPerm('files_delete');
if (fmDownloadBtn) {
fmDownloadBtn.classList.add('hidden');
fmDownloadBtn.style.display = "none";
}
if (fmRenameBtn) {
fmRenameBtn.classList.add('hidden');
fmRenameBtn.style.display = "none";
}
if (fmUnarchiveBtn) {
fmUnarchiveBtn.classList.add('hidden');
fmUnarchiveBtn.style.display = "none";
}
if (fmArchiveBtn) {
fmArchiveBtn.classList.toggle('hidden', !canArchive);
fmArchiveBtn.style.display = canArchive ? "inline-flex" : "none";
}
if (fmDeleteBtn) {
fmDeleteBtn.classList.toggle('hidden', !canDelete);
fmDeleteBtn.style.display = canDelete ? "inline-flex" : "none";
}
}
}
}
}
function toggleEntrySelection(li) {
if (!li) return;
const rel = li.dataset.relPath;
if (!rel) return;
if (selectedEntries.has(rel)) selectedEntries.delete(rel); else selectedEntries.add(rel);
updateSelectionUI();
}
function selectAllEntries() {
if (!entriesEl) return;
selectedEntries.clear();
entriesEl.querySelectorAll('.entry:not(.truncated-note)').forEach(li => {
const rel = li.dataset.relPath;
if (rel) selectedEntries.add(rel);
});
updateSelectionUI();
}
let currentPath = "";
let activeInlineRename = null;
function cancelActiveInlineRename() {
if (!activeInlineRename || typeof activeInlineRename.cancel !== 'function') return;
activeInlineRename.cancel();
}
function renderFileBreadcrumb(pathValue = "") {
if (!breadcrumbs) return;
const cleanPath = String(pathValue || "").replace(/^\/+|\/+$/g, "");
const parts = cleanPath ? cleanPath.split("/").filter(Boolean) : [];
const serverLabel = String(bot || "sfss");
const crumbs = [
`/`,
`${escapeHtml(serverLabel)}`
];
let acc = "";
parts.forEach((part) => {
acc = acc ? `${acc}/${part}` : part;
crumbs.push('/');
crumbs.push(`${escapeHtml(part)}`);
});
breadcrumbs.innerHTML = ``;
}
function startInlineRename(li, nameNode, currentName, oldPath) {
if (!li || !nameNode) return;
if (activeInlineRename && activeInlineRename.li !== li) cancelActiveInlineRename();
if (li.classList.contains('renaming')) return;
let submitting = false;
const input = document.createElement("input");
input.type = "text";
input.className = "entry-rename-input";
input.value = currentName;
input.setAttribute("aria-label", `Rename ${currentName}`);
const actions = document.createElement("div");
actions.className = "entry-rename-actions";
const saveBtn = document.createElement("button");
saveBtn.type = "button";
saveBtn.className = "entry-rename-btn save";
saveBtn.title = "Save";
saveBtn.setAttribute("aria-label", "Save rename");
saveBtn.innerHTML = '';
const cancelBtn = document.createElement("button");
cancelBtn.type = "button";
cancelBtn.className = "entry-rename-btn cancel";
cancelBtn.title = "Cancel";
cancelBtn.setAttribute("aria-label", "Cancel rename");
cancelBtn.innerHTML = '';
actions.appendChild(saveBtn);
actions.appendChild(cancelBtn);
const editor = document.createElement("div");
editor.className = "entry-rename-inline";
editor.appendChild(input);
editor.appendChild(actions);
const originalText = nameNode.textContent;
li.classList.add('renaming');
nameNode.textContent = "";
nameNode.appendChild(editor);
const stopClick = (ev) => ev.stopPropagation();
editor.addEventListener('mousedown', stopClick);
editor.addEventListener('click', stopClick);
const cleanup = () => {
if (activeInlineRename && activeInlineRename.li === li) activeInlineRename = null;
li.classList.remove('renaming');
nameNode.textContent = originalText;
};
const cancelRename = () => {
cleanup();
};
const setEditingState = (isBusy) => {
input.disabled = isBusy;
saveBtn.disabled = isBusy;
cancelBtn.disabled = isBusy;
};
const saveRename = async () => {
if (submitting) return;
const newName = input.value.trim();
if (!newName) { input.focus(); return; }
if (newName === currentName) { cleanup(); return; }
submitting = true;
setEditingState(true);
try {
await apiRename(oldPath, newName);
flashFilesBar();
await loadExplorer();
} catch (err) {
submitting = false;
setEditingState(false);
flashFilesBar();
showStoreToast('Rename failed: ' + (err && err.message ? err.message : 'Request failed'), 'error', 6000);
input.focus();
input.select();
}
};
saveBtn.addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
saveRename();
});
cancelBtn.addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
cancelRename();
});
input.addEventListener('keydown', (ev) => {
ev.stopPropagation();
if (ev.key === 'Enter') {
ev.preventDefault();
saveRename();
} else if (ev.key === 'Escape') {
ev.preventDefault();
cancelRename();
}
});
activeInlineRename = { li, cancel: cancelRename };
input.focus();
input.select();
}
// Refresh the pending destination, not the last rendered folder, while navigating.
let explorerLoadGeneration = 0;
let explorerPendingPath = null;
async function loadExplorer(path = explorerPendingPath ?? currentPath) {
const requestGeneration = ++explorerLoadGeneration;
explorerPendingPath = path;
try {
if (!hasPerm('files_read')) { entriesEl.innerHTML = `
Unauthorized
`; return; }
const data = await apiExplore(path);
if (requestGeneration !== explorerLoadGeneration) {
// Superseded while in flight: ignore this stale response entirely —
// no render, no currentPath reassignment, no selection/rename resets.
// Resolves null so awaiting callers can distinguish a dropped load
// from a rendered one; fire-and-forget callers are unaffected.
return null;
}
currentPath = data.path || "";
renderFileBreadcrumb(currentPath);
entriesEl.innerHTML = "";
const explorerEntries = (Array.isArray(data.entries) ? data.entries : [])
.map(normalizeExplorerEntry)
.filter((entry) => entry.name)
.sort(compareExplorerEntries);
explorerEntries.forEach((e) => {
const li = document.createElement("li"); li.className = "entry selectable";
const relPath = currentPath ? currentPath + "/" + e.name : e.name;
li.dataset.relPath = relPath;
li.dataset.isDir = e.isDir ? "true" : "false";
const left = document.createElement("div"); left.className = "entry-left";
// Checkbox element for selection
const cb = document.createElement("input");
cb.type = "checkbox";
cb.className = "entry-select-checkbox";
cb.checked = selectedEntries.has(relPath);
cb.setAttribute("aria-label", `Select ${e.name}`);
function toggleThisSelection(shouldBeChecked) {
const isChecked = typeof shouldBeChecked === 'boolean' ? shouldBeChecked : !cb.checked;
cb.checked = isChecked;
if (isChecked) {
selectedEntries.add(relPath);
li.classList.add('selected');
} else {
selectedEntries.delete(relPath);
li.classList.remove('selected');
}
updateSelectionUI();
}
cb.addEventListener('click', (ev) => {
ev.stopPropagation();
toggleThisSelection(cb.checked);
});
cb.addEventListener('change', (ev) => {
ev.stopPropagation();
toggleThisSelection(cb.checked);
});
left.appendChild(cb);
// Icon (Folder: files-icon.svg / File: file-icon.svg)
const icon = document.createElement("div");
icon.className = `entry-icon ${e.isDir ? 'folder' : 'file'}`;
const iconImg = document.createElement("img");
iconImg.src = e.isDir
? "/images/files-icon.svg"
: "/images/file-icon.svg";
iconImg.alt = "";
iconImg.className = "entry-icon-svg";
iconImg.width = 22;
iconImg.height = 18;
icon.appendChild(iconImg);
left.appendChild(icon);
// Name (Single line text, clean font, no subtext)
const nm = document.createElement("div");
nm.className = "entry-name";
nm.textContent = e.name;
left.appendChild(nm);
const actions = document.createElement("div");
actions.className = "entry-actions";
['pointerdown', 'mousedown', 'mouseup', 'click', 'dblclick'].forEach((eventName) => {
actions.addEventListener(eventName, (ev) => ev.stopPropagation());
});
const moreBtn = document.createElement("button");
moreBtn.type = "button";
moreBtn.className = "more-btn entry-fileinfo-btn";
moreBtn.title = "Actions";
moreBtn.innerHTML = '';
const menu = document.createElement("div");
menu.className = "more-menu";
['pointerdown', 'mousedown', 'mouseup', 'click', 'dblclick'].forEach((eventName) => {
menu.addEventListener(eventName, (ev) => ev.stopPropagation());
});
if (!e.isDir && hasPerm('files_read')) {
const downloadBtn = document.createElement("button"); downloadBtn.type = "button"; downloadBtn.innerHTML = 'Download';
downloadBtn.addEventListener('click', (ev) => {
ev.preventDefault(); ev.stopPropagation(); menu.classList.remove('show');
const rel = currentPath ? currentPath + "/" + e.name : e.name;
apiDownloadFile(rel);
});
menu.appendChild(downloadBtn);
}
if (hasPerm('files_rename')) {
const renameBtn = document.createElement("button"); renameBtn.type = "button"; renameBtn.innerHTML = 'Rename';
renameBtn.addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
menu.classList.remove('show');
startInlineRename(li, nm, e.name, relPath);
});
menu.appendChild(renameBtn);
}
if (hasPerm('files_archive')) {
const archiveBtn = document.createElement("button"); archiveBtn.type = "button"; archiveBtn.innerHTML = 'Archive';
archiveBtn.addEventListener('click', async (ev) => {
ev.preventDefault();
ev.stopPropagation();
// An upload batch owns the progress wheel while it runs: refuse
// before any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
menu.classList.remove('show');
if (archiveBtn.disabled) return;
archiveBtn.disabled = true;
const rel = currentPath ? currentPath + "/" + e.name : e.name;
let wheelEpoch = null;
try {
wheelEpoch = showProgressWheel(10, `Creating archive of "${e.name}"...`);
const result = await apiArchive([rel], currentPath);
setProgress(100, `Archive created: ${result.name}`, wheelEpoch);
scheduleProgressWheelHide(300, wheelEpoch);
loadExplorer();
flashFilesBar();
} catch (err) {
hideProgressWheel(wheelEpoch);
alert('Archive failed: ' + (err && err.message ? err.message : err));
} finally {
archiveBtn.disabled = false;
}
});
menu.appendChild(archiveBtn);
}
if (hasPerm('files_delete')) {
const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.innerHTML = 'Delete';
deleteBtn.addEventListener('click', async (ev) => {
ev.preventDefault();
ev.stopPropagation();
// An upload batch owns the progress wheel while it runs: refuse
// before any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
// Mirror the archive button: close the menu up front, then make a
// second click a no-op while the delete request is in flight.
menu.classList.remove('show');
if (deleteBtn.disabled) return;
// adpanel:planner-confirm-title — a crafted file/folder name is
// attacker-controllable text reaching a security dialog; native
// confirm() renders plain text, so the hardening is collapsing
// whitespace/newlines and capping length so the name cannot
// restyle the dialog.
const deleteConfirmName = dialogText(e.name);
if (!confirm(`Delete ${e.isDir ? "folder" : "file"} "${deleteConfirmName}"?`)) return;
deleteBtn.disabled = true;
try {
const rel = currentPath ? currentPath + "/" + e.name : e.name;
const deletedMsg = await apiDelete(rel, e.isDir);
showStoreToast(typeof deletedMsg === 'string' && deletedMsg ? deletedMsg : `Deleted ${rel}`, 'success');
setTimeout(() => loadExplorer(), 200);
} catch (err) {
flashFilesBar();
showStoreToast('Delete failed: ' + (err && err.message ? err.message : err), 'error', 6000);
} finally {
deleteBtn.disabled = false;
}
});
menu.appendChild(deleteBtn);
}
const isArchive = !e.isDir && EXPLORER_ARCHIVE_EXTENSION.test(e.name);
if (isArchive && hasPerm('files_create')) {
const unarchiveBtn = document.createElement("button"); unarchiveBtn.type = "button"; unarchiveBtn.textContent = "Unarchive";
unarchiveBtn.addEventListener('click', async (ev) => {
ev.preventDefault(); ev.stopPropagation();
// An upload batch owns the progress wheel while it runs: refuse
// before any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
menu.classList.remove('show');
const targetRel = currentPath ? currentPath + "/" + e.name : e.name;
if (unarchiveBtn.disabled) return;
// adpanel:planner-confirm-title — same display-only flatten as the
// delete dialog above; targetRel keeps the raw name for the request.
const unarchiveConfirmName = dialogText(e.name);
if (!confirm(`Unarchive "${unarchiveConfirmName}" into current folder?`)) return;
unarchiveBtn.disabled = true;
const wheelEpoch = showProgressWheel(6, "Unarchiving...");
try {
const j = await apiExtract(targetRel);
setProgress(100, j.msg || 'Unarchive complete', wheelEpoch); await new Promise(r => setTimeout(r, 250));
loadExplorer(); flashFilesBar();
} catch (err) {
flashFilesBar();
// A failed extract can leave partially extracted files on the
// server: refresh the listing even on failure.
loadExplorer();
alert('Unarchive failed: ' + (err && err.message ? err.message : 'Request failed'));
}
finally { unarchiveBtn.disabled = false; hideProgressWheel(wheelEpoch); }
});
menu.appendChild(unarchiveBtn);
}
actions.appendChild(moreBtn); actions.appendChild(menu);
moreBtn.addEventListener('click', (ev) => {
ev.stopPropagation();
document.querySelectorAll('.more-menu.show').forEach(m => { if (m !== menu) m.classList.remove('show'); });
menu.classList.toggle('show');
});
li.addEventListener('click', async (ev) => {
if (li.classList.contains('renaming')) return;
if (ev.defaultPrevented || ev.target === cb || ev.target.closest('.entry-actions, .more-menu, .entry-select-checkbox, button, input, textarea, a, .entry-rename-inline')) return;
// Check if click occurred in the checkbox area (leftmost 65px of the row)
const rect = li.getBoundingClientRect();
const clickX = ev.clientX - rect.left;
if (clickX <= 65) {
toggleThisSelection();
return;
}
if (e.isDir) {
loadExplorer(currentPath ? currentPath + "/" + e.name : e.name);
} else if (hasPerm('files_read')) {
// Images are viewed, not edited: route them to the image viewer
// BEFORE the nonEditable early-return below, which would swallow
// them (every image extension is also in that list).
if (isImageFile(e.name)) {
openImageViewer(relPath, e.size);
return;
}
const ext = (e.name.split('.').pop() || '').toLowerCase();
const nonEditable = [
// Archives
'zip', 'rar', '7z', 'tar', 'gz', 'tgz', 'bz2', 'xz', 'iso', 'cab',
// Images
'png', 'webp', 'jpg', 'jpeg', 'jfif', 'pjpeg', 'pjp', 'gif', 'bmp', 'dib',
'svg', 'svgz', 'ico', 'cur', 'avif', 'apng', 'tif', 'tiff', 'heic', 'heif',
// Audio
'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'wma',
// Video
'mp4', 'mkv', 'avi', 'mov', 'webm', 'wmv', 'flv', '3gp', 'mpeg', 'mpg'
];
if (nonEditable.includes(ext)) {
// Images never reach this branch (routed to the viewer above);
// archives, audio and video stay non-editable no-ops.
return;
}
await switchEditorFile(relPath, e.size);
}
});
const right = document.createElement("div"); right.className = "entry-right";
const dateText = formatEntryDate(e.mtime);
if (dateText) {
const dateEl = document.createElement("div");
dateEl.className = "entry-date";
dateEl.textContent = dateText;
dateEl.title = dateText;
right.appendChild(dateEl);
}
right.appendChild(actions);
li.appendChild(left); li.appendChild(right); entriesEl.appendChild(li);
});
// The node caps listing responses (truncated flag): say so instead of
// implying this folder ends at the last rendered entry.
if (data.truncated) {
const notice = document.createElement("li");
notice.className = "entry truncated-note";
notice.style.color = "var(--muted)";
notice.textContent = `Showing the first ${explorerEntries.length} entries — this folder has more. Open a subfolder to see the rest.`;
entriesEl.appendChild(notice);
}
const scripts = explorerEntries.filter(e => !e.isDir).map(e => e.name);
if (taskStartupSelect) {
taskStartupSelect.innerHTML = `` + scripts.map(s => ``).join("");
}
} catch (err) {
if (requestGeneration !== explorerLoadGeneration) return null;
console.error("[FileManager] Load failed:", err);
entriesEl.innerHTML = `
`;
} finally {
if (requestGeneration === explorerLoadGeneration) {
explorerPendingPath = null;
cancelActiveInlineRename();
clearSelection();
}
}
}
if (selectAllToggle) {
selectAllToggle.addEventListener('change', (ev) => {
if (ev.target.checked) selectAllEntries(); else clearSelection();
});
}
if (bulkDeleteBtn) {
bulkDeleteBtn.addEventListener('click', () => fmDeleteBtn?.click());
}
if (bulkArchiveBtn) {
bulkArchiveBtn.addEventListener('click', async () => {
if (selectedEntries.size === 0) return;
if (!hasPerm('files_archive')) return alert('Unauthorized: missing files_archive permission');
// An upload batch owns the progress wheel while it runs: refuse before
// any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
if (bulkArchiveBtn.disabled) return;
bulkArchiveBtn.disabled = true;
const paths = Array.from(selectedEntries);
let wheelEpoch = null;
try {
wheelEpoch = showProgressWheel(10, "Creating archive...");
const result = await apiArchive(paths, currentPath);
setProgress(100, `Archive created: ${result.name}`, wheelEpoch);
scheduleProgressWheelHide(300, wheelEpoch);
loadExplorer();
flashFilesBar();
} catch (err) {
hideProgressWheel(wheelEpoch);
alert('Archive failed: ' + (err && err.message ? err.message : err));
} finally {
bulkArchiveBtn.disabled = false;
clearSelection();
}
});
}
if (fmDownloadBtn) {
fmDownloadBtn.addEventListener('click', (ev) => {
ev.preventDefault();
if (selectedEntries.size !== 1) return;
const [rel] = selectedEntries;
if (rel) apiDownloadFile(rel);
});
}
if (fmRenameBtn) {
fmRenameBtn.addEventListener('click', (ev) => {
ev.preventDefault();
if (selectedEntries.size !== 1) return;
const [rel] = selectedEntries;
if (!rel) return;
const li = entriesEl ? Array.from(entriesEl.querySelectorAll('.entry')).find(el => el.dataset.relPath === rel) : null;
if (li) {
const nm = li.querySelector('.entry-name');
const fileName = rel.split('/').pop() || rel;
if (nm) {
li.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
startInlineRename(li, nm, fileName, rel);
}
}
});
}
if (fmUnarchiveBtn) {
fmUnarchiveBtn.addEventListener('click', async (ev) => {
ev.preventDefault();
if (selectedEntries.size !== 1) return;
const [rel] = selectedEntries;
if (!rel) return;
// An upload batch owns the progress wheel while it runs: refuse before
// any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
const fileName = rel.split('/').pop() || rel;
if (fmUnarchiveBtn.disabled) return;
// adpanel:planner-confirm-title — display-only flatten; the request
// below keeps using the raw rel.
const unarchiveConfirmName = dialogText(fileName);
if (!confirm(`Unarchive "${unarchiveConfirmName}" into current folder?`)) return;
fmUnarchiveBtn.disabled = true;
const wheelEpoch = showProgressWheel(6, "Unarchiving...");
try {
const j = await apiExtract(rel);
setProgress(100, j.msg || 'Unarchive complete', wheelEpoch);
await new Promise(r => setTimeout(r, 250));
loadExplorer();
flashFilesBar();
} catch (err) {
flashFilesBar();
// A failed extract can leave partially extracted files on the server,
// so the listing still needs one refresh even on failure.
loadExplorer();
alert('Unarchive failed: ' + (err && err.message ? err.message : 'Request failed'));
} finally {
fmUnarchiveBtn.disabled = false;
hideProgressWheel(wheelEpoch);
}
});
}
if (fmArchiveBtn) {
fmArchiveBtn.addEventListener('click', async () => {
if (selectedEntries.size === 0) return;
if (!hasPerm('files_archive')) return alert('Unauthorized: missing files_archive permission');
// An upload batch owns the progress wheel while it runs: refuse before
// any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
if (fmArchiveBtn.disabled) return;
fmArchiveBtn.disabled = true;
const paths = Array.from(selectedEntries);
const msg = paths.length === 1 ? `Creating archive of "${paths[0].split('/').pop()}"...` : `Creating archive of ${paths.length} items...`;
let wheelEpoch = null;
try {
wheelEpoch = showProgressWheel(10, msg);
const result = await apiArchive(paths, currentPath);
setProgress(100, `Archive created: ${result.name}`, wheelEpoch);
scheduleProgressWheelHide(300, wheelEpoch);
loadExplorer();
flashFilesBar();
} catch (err) {
hideProgressWheel(wheelEpoch);
alert('Archive failed: ' + (err && err.message ? err.message : err));
} finally {
fmArchiveBtn.disabled = false;
clearSelection();
}
});
}
if (fmDeleteBtn) {
fmDeleteBtn.addEventListener('click', async () => {
if (selectedEntries.size === 0) return;
if (!hasPerm('files_delete')) return alert('Unauthorized: missing files_delete permission');
// An upload batch owns the progress wheel while it runs: refuse before
// any state change instead of clobbering/aborting it.
if (uploadBatchActive || urlUploadInFlight) { alert('An upload is already in progress. Please wait for it to finish.'); return; }
if (fmDeleteBtn.disabled) return;
const items = Array.from(entriesEl.querySelectorAll('.entry'))
.map(({ dataset }) => ({ path: dataset.relPath, isDir: dataset.isDir === 'true' }))
.filter(item => item.path && selectedEntries.has(item.path));
if (!items.length) return;
let confirmMsg = "";
if (items.length === 1) {
const { path, isDir } = items[0];
const name = path.split('/').pop() || 'item';
// adpanel:planner-confirm-title — display-only flatten; the delete
// loop below uses the raw relPath.
const deleteConfirmName = dialogText(name);
confirmMsg = `Delete ${isDir ? 'folder' : 'file'} "${deleteConfirmName}"?`;
} else {
confirmMsg = `Delete ${items.length} selected item(s)?`;
}
if (!confirm(confirmMsg)) return;
fmDeleteBtn.disabled = true;
const failures = [];
let deleted = 0;
let wheelEpoch = null;
try {
wheelEpoch = showProgressWheel(4, "Deleting...");
if (REMOTE_MODE && items.length > 1) {
const batchSize = 100;
for (let offset = 0; offset < items.length; offset += batchSize) {
const batch = items.slice(offset, offset + batchSize);
const response = await fetchWithServerActionToken(`${NODE_API_BASE}/delete-batch`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: batch })
}, 'fileDelete', { refreshBefore: true });
const result = await readJsonResponseSafe(response);
if (!response.ok || !Array.isArray(result?.results) || result.results.length !== batch.length) {
throw new Error(result?.error || 'Batch delete result could not be verified.');
}
batch.forEach((item, index) => {
const outcome = result.results[index];
if (outcome?.ok === true) deleted++;
else failures.push({ name: item.path.split('/').pop(), message: outcome?.error || 'delete failed' });
});
}
} else {
for (const item of items) {
try {
await apiDelete(item.path, item.isDir);
deleted++;
} catch (err) {
failures.push({ name: item.path.split('/').pop(), message: err?.message || String(err) });
}
}
}
if (failures.length === 0) {
setProgress(100, "Delete complete", wheelEpoch);
scheduleProgressWheelHide(300, wheelEpoch);
} else {
hideProgressWheel(wheelEpoch);
// adpanel:planner-confirm-title — dialogText the display string, same
// restyle-a-security-dialog hardening as the other alert/confirm sites.
const failedList = failures.map(f => `"${dialogText(f.name)}"` + (f.message ? ` (${dialogText(f.message)})` : '')).join(', ');
alert(`Deleted ${deleted} of ${items.length} item(s). Failed to delete: ${failedList}`);
}
} catch (err) {
hideProgressWheel(wheelEpoch);
alert(`Delete stopped: ${deleted} of ${items.length} item(s) confirmed. ${dialogText(err?.message || err)}`);
} finally {
fmDeleteBtn.disabled = false;
// Exactly one refresh per operation, success or partial/total failure:
// earlier entries in the loop may already be gone from the server.
clearSelection();
loadExplorer();
}
});
}
if (filesModal && fmActions) {
filesModal.addEventListener('scroll', () => {
fmActions.classList.toggle('scrolled', filesModal.scrollTop > 5);
}, { passive: true });
}
let currentProgress = 0, simInterval = null, isActiveOperation = false, operationStart = null;
// The wheel is owned by the operation that started last: both hide timers live
// here, carry the operation generation, and are cancelled by the next
// showProgressWheel, so a hide scheduled for a finished operation can never
// take effect on a newer one's wheel. showProgressWheel returns the minted
// epoch so an operation can epoch-scope its own setProgress/hide calls.
let progressHideTimer = null, progressAutoHideTimer = null, progressEpoch = 0, progressCompleted = false;
// Which operation the currently visible wheel belongs to: 'upload-batch'
// while uploadFilesSequential / startUrlUpload own it, null for every
// non-upload wheel (store installs, file ops, ...). Only the batch's own
// popup owns the cancel affordance: an unrelated operation's wheel close
// must never abort a running batch, so requestUploadCancel is gated on
// this in closeProgressPopup. Set after the guards in both upload paths,
// cleared in each one's finally so no stale owner can outlive its batch.
let progressWheelOwner = null;
function clearProgressHideTimers() {
if (progressHideTimer) { clearTimeout(progressHideTimer); progressHideTimer = null; }
if (progressAutoHideTimer) { clearTimeout(progressAutoHideTimer); progressAutoHideTimer = null; }
}
function showProgressWheel(initial = 0, msg = "Processing...") { progressEpoch++; clearProgressHideTimers(); isActiveOperation = true; progressCompleted = false; operationStart = Date.now(); resetUploadProgressList(); progressWheel.classList.remove('hidden'); setProgress(initial, msg); return progressEpoch; }
function hideProgressWheel(epoch) {
// Same epoch contract as setProgress: a stale operation's hide must not
// tear down a newer operation's wheel (it would also kill its
// simulated-progress timer and reset its active flag). No epoch =
// untracked = behaves exactly as before.
if (epoch != null && epoch !== progressEpoch) return;
if (simInterval) { clearInterval(simInterval); simInterval = null; }
clearProgressHideTimers();
// After the guard above this is the epoch of the wheel being hidden,
// whether the caller passed one or not.
const hideEpoch = progressEpoch;
isActiveOperation = false;
progressHideTimer = setTimeout(() => {
progressHideTimer = null;
if (hideEpoch !== progressEpoch || isActiveOperation) return;
progressWheel.classList.add('hidden');
currentProgress = 0; progressFill.setAttribute('stroke-dasharray', '0 100'); popupPercent.textContent = "0%"; popupBar.style.width = "0%"; popupMsg.textContent = "Processing...";
closeProgressPopupWithoutCancel(); operationStart = null; popupTime.textContent = "—";
}, 300);
}
function setProgress(percent, msg = "Processing...", epoch) {
// Overlap guard for the shared wheel: showProgressWheel mints a monotonic
// epoch and returns it; an operation that passes a captured epoch which no
// longer matches the wheel's current one is stale (a newer operation took
// over), so its update — including its 100% completion message and the
// auto-hide it would trigger — is dropped. Compatibility rule: callers
// WITHOUT an epoch are untracked and always apply, exactly as before; the
// upload paths rely on this (their own guards mutually exclude every
// other wheel user, so their updates can never go stale).
if (epoch != null && epoch !== progressEpoch) return;
if (typeof percent !== 'number') percent = 0; percent = Math.max(0, Math.min(100, Math.round(percent)));
currentProgress = percent; progressFill.setAttribute('stroke-dasharray', percent + ' ' + (100 - percent)); popupPercent.textContent = percent + "%"; popupBar.style.width = percent + "%";
if (msg) popupMsg.textContent = msg;
if (operationStart) { const elapsed = Math.floor((Date.now() - operationStart) / 1000); popupTime.textContent = `${elapsed}s elapsed`; } else popupTime.textContent = "—";
if (percent < 100 && !progressCompleted) isActiveOperation = true;
if (percent >= 100 && isActiveOperation) {
isActiveOperation = false; progressCompleted = true;
if (progressAutoHideTimer) clearTimeout(progressAutoHideTimer);
// Renamed away from `epoch` so it cannot shadow the caller-epoch
// parameter above; post-guard the two always hold the same value, but
// the auto-hide timer's snapshot is the wheel's epoch by definition.
const autoHideEpoch = progressEpoch;
progressAutoHideTimer = setTimeout(() => { progressAutoHideTimer = null; if (autoHideEpoch === progressEpoch) hideProgressWheel(); }, 450);
}
}
// Caller-scheduled hides must be bound to the operation that scheduled them:
// hideProgressWheel snapshots the epoch at call time, so a raw timer firing
// after a newer showProgressWheel would hide the new wheel (and via
// closeProgressPopup cancel its in-flight upload). An operation that
// captured its epoch from showProgressWheel passes it here so the hide stays
// bound to ITS wheel: if a newer operation takes the wheel over before or
// after this call, the fire-time re-check drops the stale hide instead of
// letting it snapshot (and later clobber) the new wheel's epoch. The hide is
// routed through hideProgressWheel(epoch) so that guard applies doubly.
// Without an epoch the wheel's current epoch is captured at schedule time,
// preserving the previous untracked behavior exactly.
function scheduleProgressWheelHide(ms, epoch) {
// Same snapshot-at-schedule / check-at-fire shape as the auto-hide timer
// inside setProgress (autoHideEpoch).
const scheduleEpoch = epoch != null ? epoch : progressEpoch;
setTimeout(() => {
if (scheduleEpoch !== progressEpoch) return;
hideProgressWheel(scheduleEpoch);
}, ms);
}
function openProgressPopup() { progressPopup.style.display = "block"; progressPopup.setAttribute('aria-hidden', 'false'); popupPercent.textContent = currentProgress + "%"; popupBar.style.width = currentProgress + "%"; if (operationStart) { const elapsed = Math.floor((Date.now() - operationStart) / 1000); popupTime.textContent = `${elapsed}s elapsed`; } else popupTime.textContent = "—"; }
// The upload-cancel affordance: every caller is user-driven (Esc, X
// button, wheel toggle), so closing it while an upload batch owns the
// wheel aborts the in-flight XHR and cancels the queue. Timer-driven
// closes must NOT route through here: the auto-hide after a 100% progress
// tick can fire while the last file's response is still in flight, when
// the batch has not yet settled — those go through
// closeProgressPopupWithoutCancel. A non-upload wheel closing never owns
// a batch anyway.
function closeProgressPopup() {
if (!progressPopup) return;
if (progressWheelOwner === 'upload-batch') requestUploadCancel();
animateClose(progressPopup);
}
function closeProgressPopupWithoutCancel() {
if (!progressPopup) return;
animateClose(progressPopup);
}
function escapeProgressText(value) {
return String(value || '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]));
}
function resetUploadProgressList() {
if (!popupFileList) return;
popupFileList.innerHTML = '';
popupFileList.classList.remove('visible');
}
function initUploadProgressList(files) {
if (!popupFileList) return;
const items = Array.from(files || []).filter(Boolean);
if (!items.length) return resetUploadProgressList();
popupFileList.innerHTML = items.map((file, index) => `
${escapeProgressText(file.name || 'file')}
0%
`).join('');
popupFileList.classList.add('visible');
}
function updateUploadProgressList(index, percent) {
if (!popupFileList) return;
const item = popupFileList.querySelector(`[data-upload-index="${index}"]`);
if (!item) return;
const value = Math.max(0, Math.min(100, Math.round(Number(percent) || 0)));
const pct = item.querySelector('.progress-file-percent');
const fill = item.querySelector('.progress-file-fill');
if (pct) pct.textContent = `${value}%`;
if (fill) fill.style.width = `${value}%`;
}
if (progressWheel && progressPopup && popupClose) {
progressWheel.addEventListener('click', () => {
if (progressPopup.style.display === 'block') closeProgressPopup();
else openProgressPopup();
});
popupClose.addEventListener('click', () => closeProgressPopup());
}
function dragPayloadHasFiles(e) {
try {
return Array.from(e?.dataTransfer?.types || []).some(t => String(t).toLowerCase() === 'files');
} catch (_) {
return false;
}
}
// While the Files modal is open, swallow document-level file drags so a stray
// drop outside the modal can never navigate the browser off the panel. The
// handlers stay bound for the page lifetime and no-op whenever the modal is
// hidden, so no close path can leave them intercepting OS drops.
function filesModalIsActive() {
return !!(filesModal && filesModal.classList.contains('show'));
}
function onDocumentDragOver(e) {
if (!filesModalIsActive()) return;
if (!dragPayloadHasFiles(e)) return;
if (filesModal.contains(e.target)) return; // modal handlers manage the drop cursor
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'none';
}
function onDocumentDrop(e) {
if (!filesModalIsActive()) return;
if (!dragPayloadHasFiles(e)) return;
e.preventDefault();
}
function enableDropHandlers() {
if (!filesModal) return;
// The modal root and the document-level swallow guard are static, so bind
// them once for the page lifetime; the dataset flag keeps re-opening the
// modal from stacking them. The document handlers deactivate themselves
// whenever the modal loses .show, so every close path (X, Esc, inline-page
// close) is covered without paired removal.
if (!filesModal.dataset.dropHandlersBound) {
filesModal.dataset.dropHandlersBound = '1';
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => { filesModal.addEventListener(evt, (e) => e.preventDefault(), { passive: false }); });
filesModal.addEventListener('dragenter', onDragEnter);
filesModal.addEventListener('dragover', onDragOver);
filesModal.addEventListener('dragleave', onDragLeave);
filesModal.addEventListener('drop', onDrop);
document.addEventListener('dragover', onDocumentDragOver, { passive: false });
document.addEventListener('drop', onDocumentDrop);
}
}
function disableDropHandlers() {
dragCounter = 0;
if (dropOverlay) dropOverlay.classList.remove('visible');
}
let dragCounter = 0;
function dataTransferHasDirectory(dataTransfer) {
const items = Array.from(dataTransfer?.items || []);
return items.some((item) => {
if (!item || item.kind !== 'file') return false;
try {
const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
return !!(entry && entry.isDirectory);
} catch (_) {
return false;
}
});
}
function fileListHasDirectory(files) {
return Array.from(files || []).some((file) => String(file?.webkitRelativePath || '').includes('/'));
}
function blockFolderUpload() {
alert('Upload folders as an archive.');
}
function onDragEnter(e) { e.preventDefault(); dragCounter++; if (!hasPerm('files_upload') || !dropOverlay) return; dropOverlay.classList.add('visible'); if (dropTitle) dropTitle.textContent = "Drop to upload"; if (dropSubtitle) dropSubtitle.textContent = "Release to upload to current folder"; }
function onDragOver(e) { e.preventDefault(); if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; if (hasPerm('files_upload') && dropOverlay && !dropOverlay.classList.contains('visible')) dropOverlay.classList.add('visible'); }
function onDragLeave(e) { e.preventDefault(); dragCounter = Math.max(0, dragCounter - 1); if (dragCounter === 0 && dropOverlay) dropOverlay.classList.remove('visible'); }
async function onDrop(e) {
e.preventDefault();
dragCounter = 0;
if (dropOverlay) dropOverlay.classList.remove('visible');
if (!hasPerm('files_upload')) return;
if (dataTransferHasDirectory(e.dataTransfer)) {
blockFolderUpload();
return;
}
const items = e.dataTransfer.files;
if (!items || items.length === 0) return;
const files = Array.from(items);
if (fileListHasDirectory(files)) {
blockFolderUpload();
return;
}
await uploadFilesSequential(files);
}
async function uploadFilesSequential(files, targetPath = currentPath) {
files = Array.from(files || []).filter(Boolean);
// Empty-list calls are silent no-ops even during an active batch — an
// empty selection is not an upload attempt (all callers pre-filter, so
// this is unreachable today, kept as the correct semantics for new ones).
if (!files.length) return false;
if (typeof targetPath === 'function') {
const getFolder = targetPath;
let folder = getFolder();
for (;;) {
const loaded = await folder.load;
const latest = getFolder();
if (folder.load === latest.load) {
if (!loaded) {
alert('Could not load the upload destination. Refresh the folder and try again.');
return false;
}
targetPath = latest.path;
break;
}
folder = latest;
}
}
// Re-entrancy guard: a second concurrent batch would reset
// uploadCancelRequested (discarding a pending cancel for the running
// batch) and overwrite uploadAbortCurrent, so requestUploadCancel could
// no longer stop the batch that is still running.
if (uploadBatchActive) {
alert('An upload is already in progress. Please wait for it to finish.');
return false;
}
// A URL upload is a bare POST with no batch slot of its own, but it owns
// the progress wheel while in flight: starting this batch would clobber
// it, and the URL flow's completion path (setProgress(100) → auto-hide →
// closeProgressPopup → requestUploadCancel) would abort this batch's
// in-flight XHR. Refuse until the request settles.
if (urlUploadInFlight) {
alert('A URL upload is already in progress. Please wait for it to finish.');
return false;
}
if (fileListHasDirectory(files)) {
blockFolderUpload();
return false;
}
const wheelEpoch = showProgressWheel(0, files.length === 1 ? `Uploading 1 of 1 — ${files[0].name}` : `Uploading 0 of ${files.length}`);
initUploadProgressList(files);
uploadBatchActive = true;
// Set after the guards above: from here the batch owns the wheel and only
// its popup may cancel it (see closeProgressPopup).
progressWheelOwner = 'upload-batch';
uploadCancelRequested = false;
if (popupClose) popupClose.title = 'Close and cancel upload';
let completed = 0, canceled = false;
// The destination is snapshotted once per batch (default: currentPath at
// call time). currentPath is reassigned on every navigation, so re-reading
// it per iteration would send the remaining files to whatever folder the
// user is viewing mid-upload. Refreshes follow navigation without
// retargeting the batch.
try {
for (let i = 0; i < files.length; i++) {
// A cancel can land in the gap between files with no XHR in flight;
// re-check before starting each one so remaining files never start.
if (uploadCancelRequested) { canceled = true; break; }
const file = files[i], idx = i + 1, total = files.length, msgBase = `Uploading ${idx} of ${total} — ${file.name}`;
try {
await apiUploadWithProgress(file, targetPath, (percent, state) => {
const filePercent = Math.max(0, Math.min(100, Number(percent) || 0));
updateUploadProgressList(i, filePercent);
const overall = total <= 1
? filePercent
: ((i / total) * 100) + (filePercent / total);
setProgress(overall, state || msgBase);
}, msgBase);
completed++;
updateUploadProgressList(i, 100);
setProgress((completed / total) * 100, `Uploaded ${completed} of ${total}`);
await new Promise(r => setTimeout(r, 150)); loadExplorer();
} catch (err) {
// A user cancel stops the whole batch; a watchdog stall abort is an
// ordinary per-file failure and keeps the existing recovery
// (alert + continue with the next file).
if (err && err.uploadCanceled) { canceled = true; break; }
flashFilesBar();
// adpanel:planner-confirm-title — dialogText the display string; the
// name comes from the user's own picker, but the dialog-text
// hardening stays uniform across every alert in the flow.
alert(`Upload failed for "${dialogText(file.name)}": ` + dialogText((err && err.message) ? err.message : 'upload failed'));
}
}
} finally {
uploadBatchActive = false;
// Cleared with the rest of the batch state so the settle-path wheel
// hide (and any later close) can no longer cancel anything.
progressWheelOwner = null;
uploadCancelRequested = false;
uploadAbortCurrent = null;
if (popupClose) popupClose.title = 'Close';
}
if (canceled) {
alert(`Upload canceled. ${completed} of ${files.length} file(s) uploaded.`);
}
scheduleProgressWheelHide(400, wheelEpoch);
flashFilesBar();
return true;
}
function normalizeInput(raw) {
if (typeof raw !== 'string') return '';
return raw.replace(/\r\n?/g, '\n');
}
// adpanel:editor-save-occ — Web Crypto digest (hex) of the exact loaded
// content, the base the panel's optimistic-concurrency guard compares the
// on-disk file against at save time. Returns "" when crypto.subtle is
// unavailable (non-secure context) or the digest fails: the guard is
// opt-in, so a save without the hash silently keeps the legacy behavior
// instead of blocking editing (graceful degradation, never a hard failure).
async function computeEditorBaseSha256(text) {
try {
const value = typeof text === 'string' ? text : '';
if (!(window.crypto && window.crypto.subtle && typeof window.crypto.subtle.digest === 'function')) return '';
const digest = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
} catch (err) {
console.error('[Editor] sha256 of loaded content failed — saving without the concurrency guard:', err);
return '';
}
}
function detectMonacoLanguage(path) {
const lower = (path || "").toLowerCase();
if (lower.endsWith(".js")) return "javascript";
if (lower.endsWith(".ts")) return "typescript";
if (lower.endsWith(".json")) return "json";
if (lower.endsWith(".jsonc")) return "jsonc";
if (lower.endsWith(".yml") || lower.endsWith(".yaml")) return "yaml";
if (lower.endsWith(".html") || lower.endsWith(".htm")) return "html";
if (lower.endsWith(".css")) return "css";
if (lower.endsWith(".java")) return "java";
if (lower.endsWith(".php")) return "php";
if (lower.endsWith(".py")) return "python";
if (lower.endsWith(".rb")) return "ruby";
if (lower.endsWith(".go")) return "go";
if (lower.endsWith(".rs")) return "rust";
if (lower.endsWith(".cs")) return "csharp";
if (lower.endsWith(".c")) return "c";
if (lower.endsWith(".cpp") || lower.endsWith(".cc") || lower.endsWith(".cxx")) return "cpp";
if (lower.endsWith(".xml") || lower.endsWith(".xsd") || lower.endsWith(".svg") || lower.endsWith(".plist")) return "xml";
if (lower.endsWith(".toml")) return "toml";
if (lower.endsWith(".sql")) return "sql";
if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "markdown";
if (lower.endsWith(".properties") || lower.endsWith(".ini") || lower.endsWith(".cfg") || lower.endsWith(".conf") || lower.endsWith(".env")) return "ini";
if (lower.endsWith(".sh") || lower.endsWith(".bash") || lower.endsWith(".zsh") || lower.endsWith(".ksh")) return "shell";
if (lower.endsWith(".ps1")) return "powershell";
if (lower.endsWith("dockerfile")) return "dockerfile";
return "plaintext";
}
function detectAceLanguage(path) {
const lower = (path || "").toLowerCase();
if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) return "ace/mode/javascript";
if (lower.endsWith(".ts")) return "ace/mode/typescript";
if (lower.endsWith(".json") || lower.endsWith(".jsonc")) return "ace/mode/json";
if (lower.endsWith(".yml") || lower.endsWith(".yaml")) return "ace/mode/yaml";
if (lower.endsWith(".html") || lower.endsWith(".htm")) return "ace/mode/html";
if (lower.endsWith(".css")) return "ace/mode/css";
if (lower.endsWith(".java")) return "ace/mode/java";
if (lower.endsWith(".php")) return "ace/mode/php";
if (lower.endsWith(".py")) return "ace/mode/python";
if (lower.endsWith(".rb")) return "ace/mode/ruby";
if (lower.endsWith(".go")) return "ace/mode/golang";
if (lower.endsWith(".rs")) return "ace/mode/rust";
if (lower.endsWith(".cs")) return "ace/mode/csharp";
if (lower.endsWith(".c") || lower.endsWith(".cpp") || lower.endsWith(".cc") || lower.endsWith(".cxx") || lower.endsWith(".h")) return "ace/mode/c_cpp";
if (lower.endsWith(".xml") || lower.endsWith(".xsd") || lower.endsWith(".svg") || lower.endsWith(".plist")) return "ace/mode/xml";
if (lower.endsWith(".toml")) return "ace/mode/toml";
if (lower.endsWith(".sql")) return "ace/mode/sql";
if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "ace/mode/markdown";
if (lower.endsWith(".properties") || lower.endsWith(".ini") || lower.endsWith(".cfg") || lower.endsWith(".conf") || lower.endsWith(".env")) return "ace/mode/ini";
if (lower.endsWith(".sh") || lower.endsWith(".bash") || lower.endsWith(".zsh") || lower.endsWith(".ksh")) return "ace/mode/sh";
if (lower.endsWith(".ps1")) return "ace/mode/powershell";
if (lower.endsWith("dockerfile")) return "ace/mode/dockerfile";
return "ace/mode/text";
}
async function shouldUseAceFallback() {
if (useAceFallback !== null) return useAceFallback;
if (typeof ace === "undefined") { useAceFallback = false; return false; }
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
|| (navigator.maxTouchPoints > 1 && window.innerWidth < 1100);
if (isMobile) {
console.log("[Editor] Mobile/tablet detected → Ace fallback");
useAceFallback = true; return true;
}
const cores = navigator.hardwareConcurrency || 2;
const memory = navigator.deviceMemory || 4;
if (cores < 2 || memory < 2) {
console.log("[Editor] Low-spec device detected (cores:", cores, "mem:", memory, "GB) → Ace fallback");
useAceFallback = true; return true;
}
try {
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (conn && typeof conn.downlink === "number" && conn.downlink < 2) {
console.log("[Editor] Slow connection detected (downlink:", conn.downlink, "Mbps) → Ace fallback");
useAceFallback = true; return true;
}
const t0 = performance.now();
const testUrl = "/style.css?_cb=" + Date.now();
const resp = await fetch(testUrl, { cache: "no-store" });
const blob = await resp.blob();
const elapsed = performance.now() - t0;
const sizeBits = blob.size * 8;
const speedMbps = (sizeBits / elapsed) * 1000 / 1_000_000;
if (speedMbps < 2) {
console.log("[Editor] Speed test:", speedMbps.toFixed(2), "Mbps → Ace fallback");
useAceFallback = true; return true;
}
} catch (e) {
console.warn("[Editor] Speed test failed, assuming capable:", e);
}
useAceFallback = false;
return false;
}
function loadMonaco() {
if (window.monaco) {
return Promise.resolve(window.monaco);
}
if (monacoLoaderPromise) return monacoLoaderPromise;
monacoLoaderPromise = new Promise((resolve, reject) => {
const configureAndLoad = () => {
if (typeof require === "undefined") {
reject(new Error("Monaco loader (require) nu este disponibil"));
return;
}
require.config({
paths: {
// Self-hosted, sha512-verified against the npm registry (see
// PROVENANCE.md) — same-origin, so script-src 'self' covers it
// and a CDN compromise cannot run JS in the panel origin.
vs: "/vendor/monaco-editor/0.55.1/min/vs"
},
waitSeconds: 10
});
require(["vs/editor/editor.main"], function (m) {
try {
m.editor.setTheme("vs-dark");
} catch (e) { }
resolve(m);
}, function (err) {
console.error("Failed to load Monaco", err);
reject(err);
});
};
if (typeof require === "undefined") {
const s = document.createElement("script");
s.src = "/vendor/monaco-editor/0.55.1/min/vs/loader.js";
s.async = true;
s.onload = configureAndLoad;
s.onerror = (err) => reject(new Error("Failed to load Monaco loader script"));
document.head.appendChild(s);
} else {
configureAndLoad();
}
});
return monacoLoaderPromise;
}
function patchMonacoFindWidgetLayout(root) {
const host = root || monacoContainer;
if (!host) return;
host.querySelectorAll(".find-widget .monaco-inputbox > .wrapper > .input").forEach((el) => {
el.style.margin = "0";
el.style.padding = "2px 4px";
el.style.border = "none";
el.style.borderRadius = "0";
el.style.background = "transparent";
el.style.minHeight = "0";
el.style.height = "100%";
el.style.lineHeight = "inherit";
el.style.fontFamily = "inherit";
el.style.fontSize = "inherit";
el.style.boxSizing = "border-box";
el.style.resize = "none";
el.style.backdropFilter = "none";
el.style.webkitBackdropFilter = "none";
el.style.boxShadow = "none";
});
host.querySelectorAll(".find-widget .monaco-inputbox > .wrapper > .mirror").forEach((el) => {
el.style.padding = "2px 4px";
el.style.boxSizing = "border-box";
});
}
function ensureMonacoFindWidgetPatch() {
if (!monacoContainer) return;
patchMonacoFindWidgetLayout(monacoContainer);
if (monacoFindWidgetObserver) return;
monacoFindWidgetObserver = new MutationObserver(() => {
patchMonacoFindWidgetLayout(monacoContainer);
});
monacoFindWidgetObserver.observe(monacoContainer, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style"]
});
}
function openAceEditor(content, filePath) {
if (monacoContainer) monacoContainer.style.display = "none";
if (aceContainer) aceContainer.style.display = "block";
codeShell.style.display = "flex";
textArea.style.display = "none";
const legacyPane = document.querySelector("#codeShell .code-pane");
if (legacyPane) legacyPane.style.display = "none";
if (lineGutter) lineGutter.style.display = "none";
function showRawTextareaFallback(content) {
codeShell.style.display = "none";
if (aceContainer) aceContainer.style.display = "none";
textArea.style.display = "block";
textArea.value = content;
textArea.dataset.original = content;
textArea.oninput = updateEditorSaveDirtyState;
textArea.focus();
}
if (typeof ace === "undefined") {
console.error("[Editor] Ace not available — using raw textarea");
showRawTextareaFallback(content);
return;
}
if (!aceEditor) {
try {
ace.config.set("basePath", "https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict");
aceEditor = ace.edit(aceContainer, {
theme: "ace/theme/one_dark",
fontSize: 14,
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
showPrintMargin: false,
tabSize: 2,
useSoftTabs: true,
wrap: false,
scrollPastEnd: false,
animatedScroll: true,
enableBasicAutocompletion: false,
enableLiveAutocompletion: false,
highlightActiveLine: true,
highlightGutterLine: true,
showLineNumbers: true,
showGutter: true,
displayIndentGuides: true,
fixedWidthGutter: false
});
aceEditor.resize(true);
} catch (err) {
// Null the singleton: a half-initialized editor must not be reused by
// closeEditorModal or later opens; the next open may retry Ace.
aceEditor = null;
console.error("[Editor] Ace init failed — using raw textarea:", err);
showRawTextareaFallback(content);
return;
}
}
const mode = detectAceLanguage(filePath);
aceEditor.session.setMode(mode);
aceEditor.setValue(content, -1);
aceEditor.clearSelection();
aceEditor.moveCursorTo(0, 0);
aceEditor.session.off && aceEditor.session.off('change', updateEditorSaveDirtyState);
aceEditor.session.on('change', updateEditorSaveDirtyState);
requestAnimationFrame(() => {
if (aceEditor) aceEditor.resize(true);
});
aceEditor.focus();
}
async function openEditorModal(path, content, request) {
if (request.generation !== editorOpenGeneration) return;
if (isEditorErrorContent(content)) {
showStoreToast('Could not load file: failed to load file — editor not opened.', 'error', 6000);
return;
}
// adpanel:editor-save-occ - hash the raw contents before normalizing line endings.
const baseSha256 = await computeEditorBaseSha256(content || "");
if (request.generation !== editorOpenGeneration) return;
let monaco;
if (!(await shouldUseAceFallback()) && request.generation === editorOpenGeneration) {
try {
monaco = await loadMonaco();
} catch (err) {
if (request.generation !== editorOpenGeneration) return;
console.error("Failed to load Monaco, trying Ace fallback:", err);
useAceFallback = true;
monacoLoaderPromise = null;
}
}
if (request.generation !== editorOpenGeneration || editorModal.classList.contains('closing')) return;
if (currentEditorPath && getCurrentEditorValue() !== request.sourceValue) {
showStoreToast('The open file changed while loading. Save or discard your edits before switching files.', 'error', 6000);
return;
}
const normalized = normalizeInput(content || "");
showModalElement(editorModal);
// Switching files must not push a second editor history entry.
if (!editorHistoryPushed) {
try {
history.pushState({ adpanelEditor: true, path }, '', window.location.href);
editorHistoryPushed = true;
} catch (_) {}
}
if (monaco && monacoContainer) {
codeShell.style.display = "flex";
if (lineGutter) lineGutter.style.display = "none";
const legacyPane = document.querySelector("#codeShell .code-pane");
if (legacyPane) legacyPane.style.display = "none";
textArea.style.display = "none";
{
monacoContainer.style.display = "block";
if (aceContainer) aceContainer.style.display = "none";
try {
const lang = detectMonacoLanguage(path);
if (monacoEditor) {
const oldModel = monacoEditor.getModel();
const newModel = monaco.editor.createModel(normalized, lang);
monacoEditor.setModel(newModel);
if (oldModel) oldModel.dispose();
monacoEditor.setScrollTop(0);
monacoEditor.setScrollLeft(0);
} else {
monacoEditor = monaco.editor.create(monacoContainer, {
value: normalized,
language: lang,
theme: "vs-dark",
automaticLayout: true,
fontSize: 14,
lineHeight: 21,
padding: { top: 2, bottom: 2 },
minimap: { enabled: false },
scrollbar: {
vertical: 'visible',
horizontal: 'visible',
verticalScrollbarSize: 6,
horizontalScrollbarSize: 6,
useShadows: false
},
quickSuggestions: false,
suggestOnTriggerCharacters: false,
wordBasedSuggestions: "off",
parameterHints: { enabled: false },
snippetSuggestions: "none",
scrollBeyondLastLine: false,
scrollBeyondLastColumn: 1,
tabSize: 2,
insertSpaces: true,
detectIndentation: false,
autoIndent: "full",
formatOnType: true,
formatOnPaste: true
});
// Editor-level listener: registered once at creation; the widget
// re-fires content events from whatever model is attached, so it
// keeps working across setModel switches without re-subscribing.
monacoEditor.onDidChangeModelContent(updateEditorSaveDirtyState);
}
setupMonacoIdleSuggestions(monacoEditor);
ensureMonacoFindWidgetPatch();
monacoEditor.focus();
monacoEditor.__originalValue = normalized;
} catch (err) {
console.error("Failed to init Monaco, trying Ace fallback:", err);
useAceFallback = true;
monacoLoaderPromise = null;
openAceEditor(normalized, path);
}
}
} else {
openAceEditor(normalized, path);
}
currentEditorPath = path || "";
++editorDocumentGeneration;
editorPath.textContent = currentEditorPath;
editorBaseSha256 = baseSha256;
editorOriginalContent = normalized;
setEditorSaveButtonState(editorSaving);
updateEditorSaveDirtyState();
// Populate the mini file manager with the folder containing the open file.
try {
const dir = currentEditorPath.includes('/')
? currentEditorPath.slice(0, currentEditorPath.lastIndexOf('/'))
: "";
renderMiniFm(dir);
} catch (_) { }
}
function closeEditorModal({ discard = false } = {}) {
if (!editorModal) return;
if (!discard && isEditorDirty() && !confirm('You have unsaved changes. Close without saving?')) return;
++editorDocumentGeneration;
++editorOpenGeneration;
pendingEditorRead = null;
// Pop the history entry pushed by openEditorModal so the back button does
// not accumulate dead presses. The flag is cleared first: the popstate
// this triggers is our own navigation and the popstate handler must not
// react to it (no second back, no spurious unsaved-changes confirm).
if (editorHistoryPushed) {
editorHistoryPushed = false;
try { history.back(); } catch (_) {}
}
animateClose(editorModal, () => {
editorPath.textContent = '';
if (monacoIdleSuggestTimer) {
clearTimeout(monacoIdleSuggestTimer);
monacoIdleSuggestTimer = null;
}
if (monacoEditor) {
const model = monacoEditor.getModel && monacoEditor.getModel();
if (model) model.dispose();
monacoEditor.setModel(null);
}
if (aceEditor) {
aceEditor.setValue('', -1);
}
if (aceContainer) aceContainer.style.display = 'none';
if (codeShell) codeShell.style.display = 'none';
if (textArea) {
textArea.value = '';
textArea.dataset.original = '';
textArea.style.display = 'none';
}
editorOriginalContent = "";
// adpanel:editor-save-occ — a closed editor must never leave a base
// hash behind for a file it no longer holds.
editorBaseSha256 = "";
currentEditorPath = '';
});
}
function setEditorSaveButtonState(isSaving) {
if (!editorSave) return;
editorSave.innerHTML = isSaving
? 'Saving...'
: 'Save';
}
async function performSave(opts = {}) {
const closeAfter = opts.closeAfter === true; // default: keep editor open after a manual save
if (editorSaving) return false;
if (!isEditorDirty()) return false;
// The server decides create-vs-overwrite from files_create/files_write and
// reports denials through the save ack, so either permission may attempt a
// save here (editing an existing file only needs files_write).
if (!hasPerm('files_create') && !hasPerm('files_write')) {
showStoreToast('You are not allowed to edit files on this server.', 'error');
console.error('Unauthorized');
return false;
}
const path = currentEditorPath;
if (!path) { console.error('No file open'); return false; }
const documentGeneration = editorDocumentGeneration;
let editorSaveSucceeded = false;
const contentToSave = getCurrentEditorValue();
if (contentToSave === null) {
showStoreToast('Save blocked: no editor is available for this file, so its content is unknown. Reopen the file before saving.', 'error', 6000);
return false;
}
// Never write a read-failure marker (or content typed on top of one) over
// the real file: the marker means the true content is unknown, so saving
// is refused until the file is reopened successfully.
if (isEditorErrorContent(contentToSave) || isEditorErrorContent(editorOriginalContent)) {
showStoreToast('Save blocked: the file did not load correctly, so its real content is unknown. Reopen the file before saving.', 'error', 6000);
return false;
}
editorSaving = true;
if (editorSave) {
editorSave.disabled = true;
editorSave.classList.add("disabled");
setEditorSaveButtonState(true);
}
try {
const savedMsg = await apiWriteFile(path, contentToSave, editorBaseSha256);
// adpanel:editor-save-occ - a reopened path belongs to a different editor document.
if (documentGeneration === editorDocumentGeneration) {
const savedBaseSha256 = await computeEditorBaseSha256(contentToSave);
if (documentGeneration === editorDocumentGeneration) {
editorOriginalContent = contentToSave;
// The disk now hashes to the saved content, so the NEXT save of THIS
// file must verify against the new base, not the open-time one (which
// would 409 against our own previous write).
editorBaseSha256 = savedBaseSha256;
if (monacoEditor) monacoEditor.__originalValue = contentToSave;
if (textArea) textArea.dataset.original = contentToSave;
}
}
if (editorModal && editorModal.classList.contains('show')) flashEditorBar();
showStoreToast(typeof savedMsg === 'string' && savedMsg ? savedMsg : `Saved ${path}`, 'success');
loadExplorer();
refreshMiniFm();
editorSaveSucceeded = true;
} catch (err) {
// adpanel:editor-save-occ — the panel refused the save because the file
// changed on disk since this editor loaded it. Offer the existing
// reload-from-disk flow (openFileInEditor re-reads and re-bases the
// hash); cancelling keeps the local buffer — a later save re-attempts
// with the same base hash and keeps refusing until the file is
// reloaded or matches again.
// The reload offer is only safe while the editor STILL shows the file
// this stale save belongs to: the open entry points (file manager,
// viewer's open-in-editor, mini file manager) do not block on
// editorSaving, so the editor can be closed or switched to another file
// while the write is in flight. Reopening the old path then would swap
// the editor back and silently discard the current file's unsaved
// edits, so in that case the conflict is only reported — the buffer now
// in the editor is left untouched.
if (err && err.code === EDITOR_SAVE_CONFLICT_CODE) {
if (documentGeneration === editorDocumentGeneration) {
const reload = confirm(`${path} changed on disk after you opened it — saving now would overwrite the newer version.\n\nClick OK to reload it from disk (your unsaved edits will be discarded), or Cancel to keep editing.`);
if (reload) await openFileInEditor(path);
} else {
// dialogText: a crafted file name must not restyle a native dialog
// (adpanel:planner-confirm-title — same normalizer as the other
// alert() sites).
alert(`Save blocked: ${dialogText(path)} changed on disk after you opened it, so saving would overwrite the newer version. The file now open in the editor was left untouched — reopen ${dialogText(path)} to pick up the newer version.`);
}
return false;
}
flashEditorBar();
showStoreToast((err && err.message ? err.message : 'Save failed'), 'error', 6000);
console.error('Save failed: ', err);
return false;
} finally {
editorSaving = false;
if (editorSave) {
setEditorSaveButtonState(false);
updateEditorSaveDirtyState();
}
}
if (closeAfter && editorSaveSucceeded && documentGeneration === editorDocumentGeneration) {
closeEditorModal();
}
return editorSaveSucceeded;
}
if (editorSave) {
editorSave.onclick = (e) => {
e.preventDefault();
if (!isEditorDirty() || editorSave.disabled || editorSave.classList.contains('disabled')) {
return;
}
performSave();
};
}
// ============= Mini File Manager (inside Monaco editor) =============
const miniFm = document.getElementById('miniFm');
const miniFmEntries = document.getElementById('miniFmEntries');
const miniFmBreadcrumbs = document.getElementById('miniFmBreadcrumbs');
const miniFmToggle = document.getElementById('miniFmToggle');
const miniFmRefresh = document.getElementById('miniFmRefresh');
const miniFmUpload = document.getElementById('miniFmUpload');
let miniFmPath = "";
// Navigation generation: bumped on every render invocation; a fetch that
// settles after a newer one started is discarded (same superseded-load
// guard as loadPlannerItems) so a slow response can never repaint an older
// directory over the one the user navigated to.
let miniFmNavGeneration = 0;
// Promise of the most recently invoked render, settled or not: the upload
// handler awaits it so the destination is snapshotted only after an
// in-flight editor-open refresh has landed.
let miniFmLatestLoad = null;
function getCurrentEditorValue() {
if (monacoContainer && monacoContainer.style.display !== 'none' && monacoEditor && monacoEditor.getModel()) {
return monacoEditor.getValue();
}
if (aceEditor && aceContainer && aceContainer.style.display !== 'none') return aceEditor.getValue();
if (textArea && textArea.style.display !== 'none') return textArea.value;
return null;
}
function isEditorDirty() {
if (!currentEditorPath) return false;
const value = getCurrentEditorValue();
return value !== null && normalizeInput(value) !== normalizeInput(editorOriginalContent || "");
}
function updateEditorSaveDirtyState() {
if (!editorSave) return;
// Mirrors the performSave gate: the server decides create-vs-overwrite
// from files_create/files_write and reports denials through the save
// ack, so either permission may save (editing an existing file only
// needs files_write).
if (!hasPerm("files_create") && !hasPerm("files_write")) {
editorSave.disabled = true;
editorSave.classList.add("disabled");
return;
}
const dirty = !editorSaving && isEditorDirty();
editorSave.disabled = !dirty;
editorSave.classList.toggle("disabled", !dirty);
}
function refreshMiniFm() {
if (!miniFm || !codeShell || codeShell.style.display === 'none') return;
renderMiniFm(miniFmPath);
}
function renderMiniFmBreadcrumb(pathValue) {
if (!miniFmBreadcrumbs) return;
const clean = String(pathValue || "").replace(/^\/+|\/+$/g, "");
const parts = clean ? clean.split("/").filter(Boolean) : [];
const crumbs = [`${escapeHtml(String(bot || "server"))}`];
let acc = "";
parts.forEach((part) => {
acc = acc ? `${acc}/${part}` : part;
crumbs.push('/');
crumbs.push(`${escapeHtml(part)}`);
});
miniFmBreadcrumbs.innerHTML = crumbs.join("");
}
function renderMiniFm(path = "") {
const gen = ++miniFmNavGeneration;
miniFmLatestLoad = renderMiniFmLoad(path, gen);
return miniFmLatestLoad;
}
// Returns true when a fresh server response was applied; false when the
// load was superseded by a newer navigation, blocked, or failed, so callers
// don't paint a stale directory over the one the user navigated to.
async function renderMiniFmLoad(path, gen) {
if (!miniFmEntries) return false;
if (!hasPerm('files_read')) {
miniFmEntries.innerHTML = `
`).join('');
// Click handling is delegated once on the list container (see
// bindAiChatsListDelegation). Re-attaching per-item listeners on every
// re-render was fragile: a re-render triggered mid-interaction (e.g. right
// after a prompt finished) could rebuild the DOM so the freshly clicked
// node no longer had its listener, making create/delete appear dead until a
// page refresh or a DevTools-induced reflow. Delegation survives every
// re-render because it lives on the stable parent element.
bindAiChatsListDelegation();
}
// bindAiChatsListDelegation wires a single delegated click handler on the
// chats list container. It is idempotent (guarded by a data flag) so calling
// it after every render does not stack duplicate listeners.
function bindAiChatsListDelegation() {
const chatsList = document.getElementById('aiChatsList');
if (!chatsList || chatsList.dataset.delegationBound === '1') return;
chatsList.dataset.delegationBound = '1';
chatsList.addEventListener('click', async (e) => {
const deleteBtn = e.target.closest('.ai-chat-item-delete');
if (deleteBtn) {
e.preventDefault();
e.stopPropagation();
const chatId = parseInt(deleteBtn.dataset.chatId, 10);
if (!Number.isFinite(chatId)) return;
// Use the in-app confirm modal instead of the native confirm(): repeated
// native confirm() dialogs get silently suppressed by the browser
// ("prevent this page from creating more dialogs"), which is exactly why
// spam-clicking did nothing until DevTools was toggled (that resets the
// suppression). The in-app modal is never suppressed.
const ok = await storeConfirm('Delete this chat?');
if (!ok) return;
await deleteChatFromDb(chatId);
// Only reset/redirect when we deleted the chat we are currently viewing.
// If we are in a brand-new unsent chat (aiCurrentChatId === null) and we
// delete some OTHER chat, do NOT yank the user into a different chat:
// just refresh the list and keep them on their new "Hello there!" chat.
if (aiCurrentChatId === chatId) {
aiCurrentChatId = null;
aiChatHistory = [];
await loadChatHistory();
} else {
await loadChatsFromDb();
renderChatsList();
}
return;
}
const item = e.target.closest('.ai-chat-item');
if (item) {
const chatId = parseInt(item.dataset.chatId, 10);
if (Number.isFinite(chatId)) await switchToChat(chatId);
}
});
}
function formatRelativeTime(dateStr) {
const date = new Date(dateStr);
const now = new Date();
const diffMs = now - date;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
async function switchToChat(chatId) {
if (!isValidChatId(chatId)) return;
chatId = Number(chatId);
const loadToken = ++aiChatLoadToken;
aiCurrentChatId = chatId;
window.adpanelAgentReview?.bind(null);
updateSendButton();
const applyData = (data) => {
if (loadToken !== aiChatLoadToken || aiCurrentChatId !== chatId) return false;
aiChatHistory = serverAgentHistory.fromPage(data, chatId);
// Cache the freshest transcript so a later switch back is instant.
aiChatTranscriptCache.set(chatId, serverAgentHistory.clone(aiChatHistory));
renderChatHistory();
renderChatsList();
if (data?.chat?.active_job_id) void sendAiMessage(data.chat.active_job_id, Number(data.chat.active_job_is_review) === 1);
return true;
};
// Is there a background generation still running for this chat? Capture it
// BEFORE anything else so we can render from memory instead of the network.
const activeRun = aiActiveRuns.get(chatId);
// FAST PATH: a run is in flight for this chat. The SSE stream is holding an
// HTTP connection open for the entire run; over HTTP/1.1 a fetch to
// /api/ai/chats/ would queue behind it and not resolve until the run
// ends (the 20-25s "earlier chat won't open" delay). So we DO NOT fetch
// here. We render the run's transcript straight from its in-memory snapshot,
// show the typing indicator, then wait for the run to finish (a local
// promise -- no network) and only THEN reload from the DB, by which point
// the connection is free.
if (activeRun) {
aiChatHistory = activeRun.getView();
renderChatHistory();
renderChatsList();
const alreadyHasReply = aiChatHistory.some((m) => m.role === 'ai');
if (!alreadyHasReply && loadToken === aiChatLoadToken && aiCurrentChatId === chatId) {
showTypingIndicator();
}
// Local promise; resolves when the SSE stream closes. No network.
try { await activeRun.promise; } catch { }
if (loadToken !== aiChatLoadToken || aiCurrentChatId !== chatId) return;
hideTypingIndicator();
// Connection is released now. Reconcile with the DB for the canonical
// transcript, polling briefly for read-after-write lag.
let refreshed = await loadChatFromDb(chatId);
for (let attempt = 0; attempt < 6; attempt++) {
if (loadToken !== aiChatLoadToken || aiCurrentChatId !== chatId) return;
const msgs = Array.isArray(refreshed?.messages) ? refreshed.messages : [];
if (msgs.some((m) => m.role === 'assistant' || m.role === 'ai')) break;
await new Promise((r) => setTimeout(r, 300));
refreshed = await loadChatFromDb(chatId);
}
if (loadToken === aiChatLoadToken && aiCurrentChatId === chatId) {
// adpanel:scheduler-fetch-abort-cache — an aborted reconcile (the
// fetch queueing behind an open SSE stream) must not applyData: that
// renders an empty thread and caches [] for this chatId, which the
// next switch would then show instantly. Keep the in-memory run view
// already rendered and surface the timeout; a later switch or
// revalidate re-reads the DB. Inside the poll loop above the sentinel
// degrades exactly like null (retry), so only this final commit is
// abort-guarded.
if (isChatLoadAborted(refreshed)) {
showStoreToast('The chat request timed out. Please try again.', 'error', 6000);
} else {
applyData(refreshed);
}
}
return;
}
// NORMAL PATH: no active run for THIS chat. But another chat's agent run may
// still be holding an HTTP connection open, which can queue a fresh fetch
// for many seconds over HTTP/1.1. So if we have a cached transcript, render
// it IMMEDIATELY (network-free) and revalidate against the DB in the
// background; the user never waits on a starved connection pool.
const cached = aiChatTranscriptCache.get(chatId);
if (cached) {
const cachedView = serverAgentHistory.clone(cached);
aiChatHistory = cachedView;
renderChatHistory();
renderChatsList();
// Background revalidate without blocking the switch. Guarded by the load
// token so a later switch wins.
(async () => {
const fresh = await loadChatFromDb(chatId);
// adpanel:scheduler-fetch-abort-cache — the sentinel is truthy, so an
// aborted revalidate must be excluded BEFORE the truthiness check or
// it would flow into applyData and cache []. On abort the cached view
// simply stays; the next switch revalidates again. Silent: this is a
// background refresh, not a user-initiated wait.
if (!isChatLoadAborted(fresh) && fresh && loadToken === aiChatLoadToken && aiCurrentChatId === chatId) {
if (aiChatHistory === cachedView) applyData(fresh);
}
})();
return;
}
// No cache yet: fetch. This still queues behind any open SSE stream, but
// there is no in-memory copy to show first. Show the typing/loading
// indicator so the click feels responsive while the fetch is in flight.
showTypingIndicator();
const firstData = await loadChatFromDb(chatId);
if (loadToken === aiChatLoadToken && aiCurrentChatId === chatId) hideTypingIndicator();
// adpanel:scheduler-fetch-abort-cache — an aborted no-cache load (the
// 15000 bound; the fetch often queues behind an open agent SSE stream
// over HTTP/1.1) must not applyData: that renders an empty thread and
// caches [] for this chatId, which the next switch would then show
// instantly from the cached fast path. Keep the previous view (the old
// thread is still rendered — switchToChat never cleared it) and surface
// the timeout; generic failures keep the pre-fix empty-thread behavior.
if (isChatLoadAborted(firstData)) {
if (loadToken === aiChatLoadToken && aiCurrentChatId === chatId) {
showStoreToast('The chat request timed out. Please try again.', 'error', 6000);
}
return;
}
if (!applyData(firstData)) return;
}
async function startNewChat() {
const loadToken = ++aiChatLoadToken;
aiCurrentChatId = null;
aiDraftRunKey = Symbol();
aiChatHistory = [];
window.adpanelAgentReview?.bind(null);
updateSendButton();
await loadChatsFromDb();
if (loadToken !== aiChatLoadToken) return;
renderChatHistory();
renderChatsList();
}
function isAiServerContextMessage(content) {
return String(content || "").startsWith('[ADPanel Server Context]');
}
function renderChatHistory(options = {}) {
if (!aiChatMessages) return;
const { animateLatest = false } = options;
const messages = aiChatHistory;
const chatId = aiCurrentChatId;
const loadToken = aiChatLoadToken;
serverAgentHistory.bindOlderButton(document.getElementById('aiChatOlder'), {
messages, chatId, scrollPane: aiChatMessages, loadPage: loadChatFromDb,
isCurrent: () => !aiActiveRuns.has(Number(chatId) || aiDraftRunKey) && aiChatLoadToken === loadToken && aiChatHistory === messages && aiCurrentChatId === chatId,
applyPage: (history) => { aiChatHistory = history; renderChatHistory(); },
showError: () => showStoreToast('Could not load earlier messages. Please try again.', 'error', 6000),
});
// The persisted "[ADPanel Server Context]" assistant message is internal
// agent context (template/runtime/startup/port), not a conversation bubble.
// Hide it from the rendered thread so the chat still looks like a normal
// assistant↔user conversation. It is still sent to the model as context.
const visibleHistory = aiChatHistory.filter((msg) => !isAiServerContextMessage(msg.content));
if (visibleHistory.length === 0) {
const suggestionItems = ['Check server status'];
if (hasPerm('backups_view')) suggestionItems.push('List available backups');
suggestionItems.push(hasPerm('console_read') ? 'Explain recent console output' : 'Help me troubleshoot an error');
const suggestions = suggestionItems.slice(0, 4).map((label) => ``).join('');
aiChatMessages.innerHTML = `
`;
}).join('');
window.adpanelAgentReview?.bind(aiActiveRuns.has(Number(chatId) || aiDraftRunKey) ? null : serverAgentHistory.reviewJobId(messages, chatId, bot), aiChatMessages, visibleHistory);
aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
bindAiCodeCopyButtons(aiChatMessages);
}
function escapeHtmlAi(s) {
return String(s)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function aiCopyToClipboard(text, btn) {
const cleanText = text.trim();
function onSuccess() {
btn.innerHTML = '';
btn.classList.add('copied');
setTimeout(() => { btn.innerHTML = ''; btn.classList.remove('copied'); }, 1500);
}
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(cleanText).then(onSuccess).catch(() => fallbackCopy(cleanText));
} else {
fallbackCopy(cleanText);
}
function fallbackCopy(t) {
const ta = document.createElement('textarea');
ta.value = t; ta.style.position = 'fixed'; ta.style.opacity = '0';
document.body.appendChild(ta); ta.select();
try { document.execCommand('copy'); onSuccess(); } catch (e) { }
document.body.removeChild(ta);
}
}
function renderAiMarkdown(s) {
let html = escapeHtmlAi(String(s)).replace(/\0/g, '');
const fragments = [];
// adpanel:agent-markdown-attributes - formatting markup must never become part of a link destination.
const hold = (fragment) => `\0${fragments.push(fragment) - 1}\0`;
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
const langLabel = lang || 'bash';
const codeId = 'code-' + Math.random().toString(36).substr(2, 9);
const trimmedCode = code.replace(/^\s+|\s+$/g, '');
return hold('
' +
'
' +
'
' +
'' + escapeHtmlAi(langLabel) + '' +
'' +
'
' +
'
' + trimmedCode + '
' +
'
');
});
html = html.replace(/`([^`\n\0]+)`|\[([^\]\n\0]+)\]\(([^)\n\0]+)\)/g, (_, code, label, url) => {
if (code !== undefined) return hold(`${code}`);
const destination = url.trim();
if (!/^(?:https?:\/\/|mailto:)/i.test(destination)) return label;
return hold(`${label}`);
});
html = html.replace(/\*\*([^*]+)\*\*/g, '$1');
html = html.replace(/\*([^*]+)\*/g, '$1');
html = html.replace(/~~([^~]+)~~/g, '$1');
html = html.replace(/^### (.+)$/gm, '
$1
');
html = html.replace(/^## (.+)$/gm, '
$1
');
html = html.replace(/^# (.+)$/gm, '
$1
');
html = html.replace(/^[\s]*[-] (.+)$/gm, '
$1
');
html = html.replace(/((?:
.*<\/li>\n?)+)/g, '
$1
');
html = html.replace(/^(\d+)\. (.+)$/gm, '
$2
');
html = html.replace(/((?:
\n?)+)/g, '$1');
html = html.replace(/^> (.+)$/gm, '
$1
');
html = html.replace(/^---$/gm, '');
html = html.replace(/\n/g, ' ');
html = html.replace(/\0(\d+)\0/g, (_, index) => fragments[Number(index)]);
html = html.replace(/ \s*(<(?:div|ul|ol|h[2-4]|blockquote|hr|pre))/g, '$1');
html = html.replace(/(<\/(?:div|ul|ol|h[2-4]|blockquote|hr|pre)>)\s* /g, '$1');
return html;
}
function bindSuggestionButtons() {
document.querySelectorAll('.ai-suggestion').forEach(btn => {
btn.addEventListener('click', () => {
if (aiChatInput) {
aiChatInput.value = btn.textContent;
aiChatInput.focus();
updateSendButton();
}
});
});
}
async function typewriteHtml(element, htmlContent, msgObj, speedMs = 15) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
element.innerHTML = '';
async function typeNode(node, parent) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
const textNode = document.createTextNode('');
parent.appendChild(textNode);
const chunkSize = Math.max(1, Math.floor(text.length / 40));
for (let i = 0; i < text.length; i += chunkSize) {
if (!aiChatHistory.includes(msgObj)) return;
textNode.textContent += text.substr(i, chunkSize);
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
await new Promise(r => setTimeout(r, speedMs));
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
const el = document.createElement(node.tagName);
for (let attr of node.attributes) {
el.setAttribute(attr.name, attr.value);
}
parent.appendChild(el);
for (let child of node.childNodes) {
await typeNode(child, el);
if (!aiChatHistory.includes(msgObj)) return;
}
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
}
}
for (let child of tempDiv.childNodes) {
await typeNode(child, element);
if (!aiChatHistory.includes(msgObj)) return;
}
bindAiCodeCopyButtons(element);
}
function bindAiCodeCopyButtons(scope) {
if (!scope) return;
scope.querySelectorAll('.ai-code-copy[data-code-id]').forEach(btn => {
if (btn.dataset.boundCopy === 'true') return;
btn.dataset.boundCopy = 'true';
btn.addEventListener('click', () => {
const codeEl = document.getElementById(btn.dataset.codeId);
if (codeEl) aiCopyToClipboard(codeEl.textContent, btn);
});
});
}
function buildThinkingBadgeHtml(thinkingTimeMs, thinkingContent = null) {
const cleanThinkingContent = sanitizeAiThinkingText(thinkingContent);
if (!cleanThinkingContent) return '';
const durationLabel = formatAiThinkingDuration(thinkingTimeMs);
const badgeLabel = durationLabel ? `Thought for ${durationLabel}` : 'Thinking';
return `
${escapeHtmlAi(badgeLabel)}
${renderAiMarkdown(cleanThinkingContent)}
`;
}
function formatAiThinkingDuration(thinkingTimeMs) {
const ms = Number(thinkingTimeMs);
if (!Number.isFinite(ms) || ms <= 0) return '';
if (ms >= 10000) return `${Math.round(ms / 1000)}s`;
return `${(ms / 1000).toFixed(1)}s`;
}
function sanitizeAiThinkingText(text) {
return String(text || '')
.replace(//gi, '')
.replace(/<\/think(?:ing)?>/gi, '')
.replace(/\[thinking\]/gi, '')
.replace(/\[\/thinking\]/gi, '')
.trim();
}
function claimTypingIndicatorMessageSlot(thinkingTimeMs = null, thinkingContent = null) {
if (!aiChatMessages) return null;
const indicator = aiChatMessages.querySelector('.ai-typing-container');
if (!indicator) return null;
indicator.classList.remove('ai-typing-container', 'is-exiting');
const avatar = indicator.querySelector('.ai-message-avatar, .ai-msg-avatar');
if (avatar) avatar.className = 'ai-msg-avatar ai';
let body = indicator.querySelector('.ai-message-body');
let content = indicator.querySelector('.ai-message-content');
if (!body) {
body = document.createElement('div');
body.className = 'ai-message-body';
indicator.appendChild(body);
}
if (content && content.parentElement !== body) {
body.appendChild(content);
}
if (!content) {
content = document.createElement('div');
content.className = 'ai-message-content';
body.appendChild(content);
}
const existingMeta = body.querySelector('.ai-message-meta');
if (existingMeta) existingMeta.remove();
const thinkingHtml = buildThinkingBadgeHtml(thinkingTimeMs, thinkingContent);
if (thinkingHtml) {
const meta = document.createElement('div');
meta.className = 'ai-message-meta';
meta.innerHTML = thinkingHtml;
body.insertBefore(meta, content);
}
content.classList.add('ai-streaming-content');
content.innerHTML = '';
return content;
}
async function addChatMessage(role, content, thinkingTimeMs = null, model = null, attachment = null, doTypewriter = false, thinkingContent = null) {
const msg = {
role,
content,
thinking_time_ms: thinkingTimeMs,
thinking_content: sanitizeAiThinkingText(thinkingContent),
model,
timestamp: Date.now(),
attachment,
isTyping: doTypewriter && role === 'ai'
};
aiChatHistory.push(msg);
const liveAiContent = role === 'ai' ? claimTypingIndicatorMessageSlot(thinkingTimeMs, msg.thinking_content) : null;
if (!liveAiContent) {
renderChatHistory({ animateLatest: true });
}
if (aiCurrentChatId) {
const dbRole = role === 'ai' ? 'assistant' : role;
const imageData = attachment && attachment.isImage ? attachment.data : null;
saveMessageToDb(aiCurrentChatId, dbRole, content, thinkingTimeMs, model, imageData, msg.thinking_content).catch(console.error);
}
if (liveAiContent) {
if (msg.isTyping) {
await typewriteHtml(liveAiContent, renderAiMarkdown(content), msg);
} else {
liveAiContent.innerHTML = renderAiMarkdown(content);
}
bindAiCodeCopyButtons(liveAiContent.closest('.ai-message-body') || liveAiContent);
liveAiContent.classList.remove('ai-streaming-content');
msg.isTyping = false;
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
return;
}
if (msg.isTyping) {
const messages = aiChatMessages.querySelectorAll('.ai-message.ai');
if (messages.length > 0) {
const lastMessage = messages[messages.length - 1];
const contentDiv = lastMessage.querySelector('.ai-message-content');
if (contentDiv) {
await typewriteHtml(contentDiv, renderAiMarkdown(content), msg);
}
}
msg.isTyping = false;
}
}
function showTypingIndicator() {
if (!aiChatMessages) return;
const existing = aiChatMessages.querySelector('.ai-typing-container');
if (existing) return;
const typingHtml = `
`;
aiChatMessages.insertAdjacentHTML('beforeend', typingHtml);
aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
}
function hideTypingIndicator() {
if (!aiChatMessages) return;
const indicator = aiChatMessages.querySelector('.ai-typing-container');
if (!indicator) return;
if (indicator.classList.contains('is-exiting')) return;
indicator.classList.add('is-exiting');
const cleanup = () => {
if (indicator.parentNode) indicator.remove();
};
indicator.addEventListener('transitionend', cleanup, { once: true });
setTimeout(cleanup, 220);
}
function updateSendButton() {
if (aiChatSend && aiChatInput) {
const hasContent = aiChatInput.value.trim() || aiAttachedFile;
const generating = aiActiveRuns.has(Number(aiCurrentChatId) || aiDraftRunKey);
aiChatSend.disabled = !hasContent && !generating;
if (generating) {
aiChatSend.innerHTML = '';
aiChatSend.classList.add('generating');
aiChatSend.disabled = false;
aiChatSend.title = 'Stop generating';
} else {
aiChatSend.innerHTML = '';
aiChatSend.classList.remove('generating');
aiChatSend.title = 'Send message';
}
}
}
function handleFileAttachment(file) {
if (!file) return;
const maxSize = file.type.startsWith('image/') ? 1500 * 1024 : 24_000;
if (file.size > maxSize) {
alert('File is too large. Maximum size is 5MB.');
return;
}
const reader = new FileReader();
reader.onload = (e) => {
aiAttachedFile = {
name: file.name,
type: file.type,
data: e.target.result,
isImage: file.type.startsWith('image/')
};
showAttachedFilePreview();
updateSendButton();
};
if (file.type.startsWith('image/')) {
reader.readAsDataURL(file);
} else {
reader.readAsText(file);
}
}
function showAttachedFilePreview() {
if (!aiAttachedFile) return;
const existingPreview = document.querySelector('.ai-attached-preview');
if (existingPreview) existingPreview.remove();
const inputBox = document.querySelector('.ai-chat-input-box');
if (!inputBox) return;
const previewHtml = aiAttachedFile.isImage
? `
`
: `
`;
const inputRow = inputBox.querySelector('.ai-chat-input-row');
if (inputRow) {
inputRow.insertAdjacentHTML('beforebegin', previewHtml);
} else {
inputBox.insertAdjacentHTML('afterbegin', previewHtml);
}
const removeBtn = inputBox.querySelector('.ai-attached-remove');
if (removeBtn) {
removeBtn.addEventListener('click', clearAttachedFile);
}
}
function clearAttachedFile() {
aiAttachedFile = null;
const preview = document.querySelector('.ai-attached-preview');
if (preview) preview.remove();
if (aiFileInput) aiFileInput.value = '';
updateSendButton();
}
document.addEventListener('adpanel:agent-review-settled', ({ detail }) => {
const chatId = Number(detail?.chatId);
if (!chatId || chatId !== Number(aiCurrentChatId) || aiActiveRuns.has(chatId) || !hasAgentAccess()) return;
if (detail.conclusionJobId) void sendAiMessage(detail.conclusionJobId, true);
else void reloadVisibleChatFromDb(chatId).catch(() => {});
});
async function sendAiMessage(activeJobId = null, reviewConclusion = false) {
if (!hasAgentAccess()) return;
const runStartChatId = Number(aiCurrentChatId) || null;
const startKey = runStartChatId ?? aiDraftRunKey;
const activeRun = aiActiveRuns.get(startKey);
if (activeRun) {
if (!activeJobId) activeRun.cancel().catch(() => {
showStoreToast('Could not stop this Agent run. Try Stop again.', 'error', 6000);
});
return;
}
const draft = aiChatInput?.value || '';
const attachedFile = aiAttachedFile;
const messageText = draft.trim();
if (!activeJobId && !messageText && !aiAttachedFile) return;
const modelValue = aiModelSelect?.value || '';
const { providerId, modelName } = decodeAiModelSelection(modelValue);
if (!activeJobId && (!providerId || !modelName)) {
showStoreToast('Please select a model first.', 'error', 6000);
return;
}
let message = messageText;
let attachmentInfo = null;
if (!activeJobId && aiAttachedFile) {
attachmentInfo = { ...aiAttachedFile };
if (aiAttachedFile.isImage) {
message = message || 'Please analyze this image.';
} else {
message = `[Attached file: ${aiAttachedFile.name}]\n\nFile content:\n\`\`\`\n${aiAttachedFile.data}\n\`\`\`\n\n${message || 'Please review this file.'}`;
}
}
const queuedRun = activeJobId ? window.adpanelAgentLive.resumeRun(activeJobId, runStartChatId)
: window.adpanelAgentLive.createRun({
server: bot, chatId: runStartChatId, provider: providerId, model: modelName,
prompt: message, image: attachmentInfo?.isImage ? attachmentInfo.data : null,
});
if (!activeJobId) saveSelectedAiModelToStorage(modelValue);
const runViewToken = ++aiChatLoadToken;
const isRunStillVisible = () => aiChatLoadToken === runViewToken;
let settleRun;
const runDonePromise = new Promise((resolve) => { settleRun = resolve; });
const runMessages = serverAgentHistory.clone(aiChatHistory);
const runRecord = {
promise: runDonePromise,
getView: () => serverAgentHistory.clone(runMessages),
cancel: queuedRun.cancel,
};
aiActiveRuns.set(startKey, runRecord);
updateSendButton();
window.adpanelAgentReview?.bind(null);
const userMsgForView = {
role: 'user',
content: (attachmentInfo && attachmentInfo.isImage) ? (messageText || '(Image attached)') : message,
thinking_time_ms: null, thinking_content: null, model: null,
timestamp: Date.now(),
attachment: (attachmentInfo && attachmentInfo.isImage) ? attachmentInfo : null,
};
const activity = createAgentActivityMessage(isRunStillVisible);
let runKey = startKey;
try {
const accepted = await queuedRun.accepted;
const resolvedRunChatId = Number(accepted.chatId);
if (!isValidChatId(resolvedRunChatId)) throw new Error('Could not create the chat.');
if (runKey !== resolvedRunChatId) {
if (aiActiveRuns.has(resolvedRunChatId)) return;
aiActiveRuns.delete(runKey);
runKey = resolvedRunChatId;
aiActiveRuns.set(runKey, runRecord);
}
if (isRunStillVisible()) aiCurrentChatId = resolvedRunChatId;
updateSendButton();
if (!activeJobId) {
runMessages.push(userMsgForView);
if (isRunStillVisible()) {
if (aiChatInput?.value === draft) aiChatInput.value = '';
if (aiAttachedFile === attachedFile) clearAttachedFile();
pushLocalChatMessage('user', userMsgForView.content, userMsgForView.attachment);
activity.addThinking();
}
} else if (reviewConclusion && isRunStillVisible()) {
activity.addThinking();
}
const result = await queuedRun.result();
const finalContent = String(result.content || '').trim() || 'No response received.';
const thinkingTime = result.thinking_time_ms || null;
const thinkingContent = result.thinking_content || null;
const runChatId = resolvedRunChatId;
if (activeJobId) {
activity.detach();
await reloadVisibleChatFromDb(runChatId);
return;
}
// Keep the result available for an immediate switch back into this chat.
runMessages.push({
role: 'ai',
content: String(finalContent || '').trim() || 'Done.',
thinking_time_ms: thinkingTime,
thinking_content: thinkingContent, model: modelName, timestamp: Date.now(), attachment: null,
});
if (Number.isFinite(Number(resolvedRunChatId)) && Number(resolvedRunChatId) > 0) {
aiChatTranscriptCache.set(Number(resolvedRunChatId), serverAgentHistory.clone(runMessages));
}
// If the user navigated away (New Chat or switched chats) while this run
// was generating, do NOT touch whatever thread they navigated to. Tear
// down this run's live bubble/approval boxes so nothing lingers.
if (!isRunStillVisible()) {
activity.detach();
// BUT: the user may have navigated BACK to this run's chat while it was
// still finishing. In that case switchToChat loaded the transcript
// before the assistant reply was persisted, so the chat looks empty.
// Re-load and re-render it now that the run is done so the response
// appears without needing a manual refresh.
if (runChatId && Number(aiCurrentChatId) === runChatId) {
await reloadVisibleChatFromDb(runChatId);
}
return;
}
if (runChatId) {
aiCurrentChatId = runChatId;
}
activity.detach();
pushLocalChatMessage('ai', String(finalContent || '').trim() || 'Done.');
// Reconcile silently with the DB so the saved transcript (with proper
// thinking metadata, model label, etc.) becomes the source of truth and
// the conversation stays persistent across follow-up prompts and refresh.
// This is wrapped so a failure here can never prevent the chats-list
// refresh in the finally block.
try {
if (aiCurrentChatId && isRunStillVisible()) {
const shownCount = aiChatHistory.length;
const data = await loadChatFromDb(aiCurrentChatId);
// Re-check after the await: the user may have navigated away while the
// DB read was in flight. If so, leave their current view untouched.
// adpanel:scheduler-fetch-abort-cache — explicit abort guard (the loop-appropriate equivalent of an early continue): on the sentinel keep the in-memory view (the final answer pushed above); the length comparison below happens to exclude the sentinel today, and this protects that invariant from future edits of the comparison.
if (isRunStillVisible() && !isChatLoadAborted(data)) {
const dbMessages = Array.isArray(data?.messages) ? data.messages : [];
if (dbMessages.length >= shownCount) {
aiChatHistory = serverAgentHistory.fromPage(data, aiCurrentChatId);
renderChatHistory();
}
}
}
} catch (reconcileErr) {
console.error('[ai-chat] reconcile failed:', reconcileErr);
}
} catch (err) {
// Only show the error in the thread if the user is still viewing the chat
// this run belonged to. If they navigated away, just remove the live
// bubble so it does not appear in the chat they switched to.
if (reviewConclusion) {
activity.detach();
await reloadVisibleChatFromDb(runKey).catch(() => {});
} else if (!isRunStillVisible()) {
activity.detach();
} else if (err.name === 'AbortError') {
activity.fail('\u23f9\ufe0f Generation stopped.');
} else {
activity.fail(`Error: ${err.message || 'Failed to start the agent.'}`);
}
} finally {
queuedRun.detach();
aiActiveRuns.delete(runKey);
updateSendButton();
if (!aiActiveRuns.has(Number(aiCurrentChatId) || aiDraftRunKey)) window.adpanelAgentReview?.bind(serverAgentHistory.reviewJobId(aiChatHistory, aiCurrentChatId, bot), aiChatMessages);
settleRun();
try {
await refreshChatsListAfterRun();
} catch (refreshErr) {
console.error('[ai-chat] chats list refresh failed:', refreshErr);
}
}
}
// refreshChatsListAfterRun reloads the chats from the DB and re-renders the
// sidebar list. If the current chat id is not present yet (read-after-write
// lag right after the server created it), it retries a few times with a short
// backoff so the new chat appears immediately.
async function refreshChatsListAfterRun() {
await loadChatsFromDb();
const targetId = Number(aiCurrentChatId);
if (Number.isFinite(targetId) && targetId > 0) {
let attempts = 0;
while (attempts < 6 && !aiChatsList.some((c) => Number(c.id) === targetId)) {
await new Promise((r) => setTimeout(r, 300));
await loadChatsFromDb();
attempts++;
}
}
renderChatsList();
}
// reloadVisibleChatFromDb re-fetches a chat's transcript and renders it as the
// active thread, but only if the user is still viewing that chat. Used when a
// background run finishes for a chat the user has navigated back into (the
// chat looked empty because the assistant reply was not yet persisted when the
// user switched back). It polls briefly to absorb read-after-write lag.
async function reloadVisibleChatFromDb(chatId) {
const targetId = Number(chatId);
if (!Number.isFinite(targetId) || targetId <= 0) return;
const loadToken = aiChatLoadToken;
let data = null;
for (let attempt = 0; attempt < 6; attempt++) {
// Stop if the user navigated away again while we were polling.
if (Number(aiCurrentChatId) !== targetId || aiChatLoadToken !== loadToken) return;
data = await loadChatFromDb(targetId);
// adpanel:scheduler-fetch-abort-cache — inside the loop the sentinel
// would degrade to [] exactly like null (retry), but each retry re-pays
// the 15s abort bound within the same starvation window; break and let
// the final commit's guard below decide.
if (isChatLoadAborted(data)) break;
const msgs = Array.isArray(data?.messages) ? data.messages : [];
const hasAssistant = msgs.some((m) => (m.role === 'assistant' || m.role === 'ai'));
if (hasAssistant) break;
await new Promise((r) => setTimeout(r, 300));
}
if (Number(aiCurrentChatId) !== targetId || aiChatLoadToken !== loadToken) return;
// adpanel:scheduler-fetch-abort-cache — an aborted final read must not
// commit: the sentinel is truthy but has no .messages, so messages would
// be [] and renderChatHistory() would wipe the thread the user is looking
// at. Mirror switchToChat's final commit exactly: keep the current visible
// view (aiChatHistory and the DOM stay as rendered by switchToChat's
// fast/cached path — which already shows the run's in-memory transcript)
// and surface the friendly timeout; generic failures keep the pre-fix
// empty-thread behavior byte-for-byte.
if (isChatLoadAborted(data)) {
showStoreToast('The chat request timed out. Please try again.', 'error', 6000);
} else {
aiChatHistory = serverAgentHistory.fromPage(data, aiCurrentChatId);
renderChatHistory();
}
}
// Renders messages independently of the send flow's explicit, chat-bound saves.
function pushLocalChatMessage(role, content, attachment = null) {
aiChatHistory.push({
role,
content,
thinking_time_ms: null,
thinking_content: null,
model: null,
timestamp: Date.now(),
attachment,
isTyping: false,
});
renderChatHistory({ animateLatest: true });
}
// createAgentActivityMessage builds a live AI message bubble (brand avatar +
// animated "..." typing dots) that streams the agent's natural-language
// narration in real time. Internal tool calls (list_files, write_file, etc.)
// are intentionally NOT shown: the user only sees the AI's own words, plus the
// approval prompts that the stream injects separately.
function createAgentActivityMessage(isVisible = () => true) {
hideTypingIndicator();
const id = `agent-activity-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
let narration = ''; // accumulated assistant narration text
let typing = true; // show the animated dots while the agent is working
const approvalBoxes = []; // inline approve/reject prompts created this run
const ensureEl = () => {
// If the user has navigated to a different chat (or New Chat) while this
// run is still streaming, do NOT (re)create the live bubble. Otherwise the
// ongoing narration re-appends itself into whatever chat is now on screen,
// which is exactly the "in-progress response shows up in my new chat" bug.
if (!isVisible()) return null;
let el = document.getElementById(id);
if (!el && aiChatMessages) {
const wrap = document.createElement('div');
wrap.className = 'ai-message ai ai-enter';
wrap.innerHTML = `
`;
aiChatMessages.appendChild(wrap);
el = document.getElementById(id);
}
return el;
};
const dots = '';
const render = () => {
const el = ensureEl();
if (!el) return;
if (narration) {
el.innerHTML = `
${escapeAgentHtml(narration)}
${typing ? dots : ''}`;
} else {
el.innerHTML = dots;
}
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
};
render(); // show the typing dots immediately when the message is created
return {
id,
// Each assistant_message becomes a new line of live narration.
addNarration(text) {
const t = String(text || '').trim();
if (!t) return;
narration = narration ? `${narration}\n${t}` : t;
typing = true;
render();
},
// No-op shims kept so the event handler stays simple. The animated dots
// already convey "the AI is working", so explicit thinking/tool lines are
// not rendered.
addThinking() { typing = true; render(); },
clearThinking() { /* dots stay until finalize */ },
toolStart() { return null; },
toolResult() { },
toolRejected() { },
// Register an inline approval box so it can be cleaned up when the run ends.
trackApprovalBox(box) { if (box) approvalBoxes.push(box); },
// detach() tears down ALL live DOM this run created: every approve/reject
// box and the live narration bubble itself. Use this right before
// re-rendering the full chat history from memory, so the final answer is
// shown by renderChatHistory (one source of truth) with nothing lingering.
detach() {
typing = false;
while (approvalBoxes.length) {
const box = approvalBoxes.pop();
if (box && box.parentElement) box.parentElement.removeChild(box);
}
const el = document.getElementById(id);
const wrap = el ? el.closest('.ai-message') : null;
if (wrap && wrap.parentElement) wrap.parentElement.removeChild(wrap);
},
finalize(content) {
// Stop the live state and render the agent's REAL final answer. We do
// not fall back to the streamed narration (that would leave the bubble
// showing an intermediate "thinking" line instead of the conclusion).
typing = false;
// Remove every approve/reject prompt now that the agent has fully
// stopped: the decisions are already recorded server-side and the saved
// chat transcript is the source of truth.
while (approvalBoxes.length) {
const box = approvalBoxes.pop();
if (box && box.parentElement) box.parentElement.removeChild(box);
}
const el = ensureEl();
const text = String(content || '').trim() || 'Done.';
if (el) {
el.innerHTML = renderAiMarkdown(text);
bindAiCodeCopyButtons(el.closest('.ai-message-body') || el);
}
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
},
fail(content) { this.finalize(content); },
element: ensureEl,
// Lets callers (e.g. the approval prompt) check whether this run is still
// the one on screen before injecting DOM.
isVisible,
};
}
function escapeAgentHtml(text) {
return String(text == null ? '' : text)
.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
}
// buildAgentDiffHtml renders a colored, line-by-line diff for file-writing
// tools, shown above the Accept/Reject buttons in Ask mode so the user can see
// exactly what will change before approving.
// - edit_file: old_str lines are removed (red, "-"), new_str lines are
// added (green, "+").
// - write_file: the whole file is (re)written, so every content line is
// shown as an addition (green, "+"). We do not fetch the previous content
// (a blocking network call would queue behind the open agent stream).
// Returns '' for tools that do not change file contents.
function buildAgentDiffHtml(name, args) {
const a = args || {};
const MAX_LINES = 400; // guardrail so a huge file does not freeze the panel
const rowsToHtml = (lines, kind) => {
const sign = kind === 'add' ? '+' : '-';
return lines.map((line) => (
`
` +
`${sign}` +
`${escapeAgentHtml(line)}` +
`
`
)).join('');
};
const splitLines = (str) => String(str == null ? '' : str).replace(/\r\n/g, '\n').split('\n');
// An edit_file call can carry either a single old_str/new_str pair or an
// "edits" array of several surgical {old_str,new_str} edits. Normalize to a
// list of edit pairs so the preview shows each change as its own red/green
// hunk instead of one big rewrite.
const editPairs = [];
if (name === 'edit_file') {
if (Array.isArray(a.edits) && a.edits.length) {
a.edits.forEach((e) => {
editPairs.push({ removed: splitLines(e && e.old_str), added: splitLines(e && e.new_str) });
});
} else {
editPairs.push({ removed: splitLines(a.old_str), added: splitLines(a.new_str) });
}
} else if (name === 'write_file') {
editPairs.push({ removed: [], added: splitLines(a.content) });
} else {
return '';
}
let used = 0;
let hidden = 0;
const hunks = [];
editPairs.forEach((pair, idx) => {
let removed = pair.removed || [];
let added = pair.added || [];
const remaining = Math.max(MAX_LINES - used, 0);
const total = removed.length + added.length;
if (remaining <= 0) {
hidden += total;
return;
}
if (total > remaining) {
const keepRemoved = Math.min(removed.length, Math.floor(remaining / 2));
const keepAdded = Math.min(added.length, remaining - keepRemoved);
hidden += total - keepRemoved - keepAdded;
removed = removed.slice(0, keepRemoved);
added = added.slice(0, keepAdded);
}
used += removed.length + added.length;
const hunkBody = rowsToHtml(removed, 'del') + rowsToHtml(added, 'add');
if (!hunkBody) return;
// Separate multiple edit hunks with a faint divider so the user can tell
// the distinct surgical changes apart.
const sep = (editPairs.length > 1 && hunks.length > 0) ? '' : '';
hunks.push(sep + hunkBody);
});
let truncatedNote = '';
if (hidden > 0) {
truncatedNote = `
`;
}
const body = hunks.join('');
if (!body) return '';
const path = escapeAgentHtml(a.path || '');
return (
`
` +
(path ? `
${path}
` : '') +
`
${body}${truncatedNote}
` +
`
`
);
}
function describeAgentTool(name, args) {
const a = args || {};
switch (name) {
case 'write_file': return `Write file ${a.path || ''}`;
case 'create_folder': return `Create folder ${a.path || ''}`;
case 'unarchive': return `Extract archive ${a.path || ''}`;
case 'edit_file': return `Edit file ${a.path || ''}`;
case 'delete_file': return `Delete ${a.isDir ? 'directory' : 'file'} ${a.path || ''}`;
case 'run_command': return `Run command: ${a.command || ''}`;
case 'download_file': return `Download ${a.url || ''} to ${a.path || ''}`;
case 'read_file': return `Read file ${a.path || ''}`;
case 'grep_files': return `Search for "${a.pattern || ''}"${a.path ? ` in ${a.path}` : ''}`;
case 'list_files': return `List ${a.path || '.'}`;
case 'read_console': return 'Read console output';
case 'read_activity': return `Read activity log${a.limit ? ` (${a.limit})` : ''}`;
case 'server_info': return 'Read server info';
case 'create_backup': return `Create a backup${a.name ? ` named "${a.name}"` : ''}`;
case 'start_server': return 'Start the server';
case 'stop_server': return 'Stop the server';
case 'restart_server': return 'Restart the server';
case 'kill_server': return 'Kill the server';
case 'reinstall_server': return 'Reinstall the server (resets it to a fresh install)';
case 'create_planner_item': return `Add planner item${a.title ? ` "${a.title}"` : ''}`;
case 'create_schedule': return `Create schedule${a.name ? ` "${a.name}"` : ''}${a.actionType ? ` (${a.actionType})` : ''}`;
case 'delete_schedule': return `Delete schedule${a.name ? ` "${a.name}"` : (a.taskId ? ` ${a.taskId}` : '')}`;
default: return name;
}
}
// runAgentStream opens the SSE stream, renders live events, handles approval
// prompts, and resolves with the final conclusion text.
async function runAgentStream({ serverName, prompt, provider, model, chatId, askMode, activity, signal, onChatId }) {
const response = await fetch('/api/ai/agent/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverName, prompt, provider, model, chatId, askMode: askMode === 'dont_ask' ? 'dont_ask' : 'ask', timezone: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return ''; } })() }),
signal,
});
if (!response.ok || !response.body) {
let errMsg = 'Failed to start ' + BRAND_NAME + ' Agent.';
try { const j = await response.json(); errMsg = j.error || errMsg; } catch { }
throw new Error(errMsg);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let finalContent = '';
// The server creates the chat row when chatId is null and reports the id in
// BOTH the 'start' and 'done' events. We capture it here and return it so
// the caller can pin aiCurrentChatId to the real server id and refresh the
// chats list. Relying only on a side-effect assignment was racy: if the
// 'start' event was parsed in the same tick as later work, the chats-list
// refresh could read a stale aiCurrentChatId (still null) and skip showing
// the freshly created chat until an unrelated later refresh.
let resolvedChatId = chatId || null;
const handleEvent = async (eventName, payload) => {
if (eventName === 'start') {
// Capture the server-assigned chat id only. Do NOT assign it to
// aiCurrentChatId here as a side effect: if the user clicked New Chat
// while this run was still streaming, aiCurrentChatId now points at the
// new (empty) chat, and overwriting it would drag this background run's
// chat id into the view the user just opened. The caller adopts the id
// safely, guarded by the run's view token.
if (payload.chatId) {
resolvedChatId = Number(payload.chatId);
// Surface the real chat id to the caller the INSTANT the server
// assigns it (not only at 'done'). This lets a brand-new chat's run
// be registered in aiActiveRuns right away, so clicking back into
// that still-generating chat finds the run and waits for it instead
// of rendering a half-empty thread that only fixes on refresh.
if (typeof onChatId === 'function') {
try { onChatId(resolvedChatId); } catch { }
}
}
} else if (eventName === 'event') {
const ev = payload || {};
// Only the AI's own narration is streamed to the user. Internal tool
// calls (tool_start / tool_result / tool_rejected) are deliberately
// ignored here so the chat shows AI words, not a tool log.
if (ev.type === 'assistant_message') {
activity.addNarration(ev.content);
} else if (ev.type === 'tool_result' && ev.ok) {
// When the agent performs a power action (start/stop/restart/kill),
// either through the dedicated power tools or a rerouted run_command,
// refresh the power buttons/state so the UI reflects it immediately
// instead of waiting for the next poll.
const powerToolNames = ['start_server', 'stop_server', 'restart_server', 'kill_server', 'reinstall_server'];
const isPower = powerToolNames.includes(ev.name)
|| (ev.name === 'run_command' && ev.result && ev.result.rerouted && ev.result.action);
if (isPower) {
setTimeout(() => { refreshPowerState({ force: true }).catch(() => { }); }, 250);
}
}
} else if (eventName === 'approval_request') {
await handleApprovalRequest(payload, activity);
} else if (eventName === 'approval_timeout') {
activity.addNarration('Approval timed out; the action was skipped.');
} else if (eventName === 'question_request') {
await handleQuestionRequest(payload, activity);
} else if (eventName === 'question_timeout') {
activity.addNarration('The question timed out without an answer.');
} else if (eventName === 'done') {
finalContent = payload.content || '';
} else if (eventName === 'error') {
throw new Error(payload.error || 'Agent failed.');
}
};
// streamEnded is set when we receive a terminal event ('done' or 'error').
// We then STOP reading and release the connection immediately instead of
// waiting for the server to close the socket. Waiting for the server close
// (the keep-alive ping keeps the response open) is what previously left the
// stream "running": runAgentStream never resolved, aiIsGenerating stayed
// true, the HTTP connection stayed held, and subsequent requests (new chat /
// delete chat / list) appeared to do nothing until a full page refresh.
let streamEnded = false;
let thrownError = null;
try {
while (!streamEnded) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const blocks = buffer.split('\n\n');
buffer = blocks.pop() || '';
for (const block of blocks) {
if (!block.trim() || block.startsWith(':')) continue;
let evName = 'message';
let dataLines = [];
for (const line of block.split('\n')) {
if (line.startsWith('event:')) evName = line.slice(6).trim();
else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
}
let data = {};
try { data = JSON.parse(dataLines.join('\n') || '{}'); } catch { }
if (evName === 'done') {
finalContent = data.content || '';
if (data.chatId) resolvedChatId = Number(data.chatId);
streamEnded = true;
break;
}
if (evName === 'error') { thrownError = new Error(data.error || 'Agent failed.'); streamEnded = true; break; }
await handleEvent(evName, data);
}
}
} finally {
// Always release the network connection so it never blocks later fetches,
// even if an event handler throws mid-stream.
try { await reader.cancel(); } catch { }
}
if (thrownError) throw thrownError;
return { content: finalContent, chatId: resolvedChatId };
}
// handleApprovalRequest shows an inline approve/reject UI and posts the
// decision back to the server, fulfilling the agent's pending tool call.
function handleApprovalRequest(payload, activity) {
return new Promise((resolve) => {
// If the user navigated away from this run's chat, auto-approve nothing and
// do not inject the approval UI into the chat they are now viewing. Resolve
// immediately; the server-side timeout/disconnect handling takes over so
// the background run does not hang.
if (typeof activity.isVisible === 'function' && !activity.isVisible()) {
resolve();
return;
}
const el = activity.element();
const boxId = `approval-${payload.approvalId}`;
const box = document.createElement('div');
box.className = 'ai-agent-approval';
box.id = boxId;
box.innerHTML = `
`;
if (el && el.parentElement) el.parentElement.appendChild(box); else if (aiChatMessages) aiChatMessages.appendChild(box);
if (typeof activity.trackApprovalBox === 'function') activity.trackApprovalBox(box);
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
let settled = false;
const decide = async (approved) => {
if (settled) return;
settled = true;
box.querySelectorAll('button').forEach((b) => { b.disabled = true; });
box.classList.add(approved ? 'approved' : 'rejected');
box.querySelector('.ai-agent-approval-buttons').innerHTML = approved
? ' Approved'
: ' Rejected';
try {
await fetch('/api/ai/agent/approve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ approvalId: payload.approvalId, approved }),
});
} catch { }
resolve();
};
box.querySelector('[data-approve="1"]').addEventListener('click', () => decide(true));
box.querySelector('[data-approve="0"]').addEventListener('click', () => decide(false));
});
}
// handleQuestionRequest shows an inline "Ask Question" bar where the user can
// type an answer (e.g. a download link) and send it back WITHOUT stopping the
// agent. The agent's run stays alive; the typed answer is posted to the same
// /approve endpoint (as a free-text answer) and resolves the pending ask_user
// tool so generation continues.
function handleQuestionRequest(payload, activity) {
return new Promise((resolve) => {
// If the user navigated away from this run's chat, do not inject the bar
// into a different chat. The server-side timeout/disconnect takes over.
if (typeof activity.isVisible === 'function' && !activity.isVisible()) {
resolve();
return;
}
const el = activity.element();
const box = document.createElement('div');
box.className = 'ai-agent-question';
box.id = `question-${payload.approvalId}`;
const question = String(payload.question || 'Can you provide more details?');
box.innerHTML = `
${escapeHtml(BRAND_NAME)} Agent asks:
${escapeAgentHtml(question)}
`;
if (el && el.parentElement) el.parentElement.appendChild(box); else if (aiChatMessages) aiChatMessages.appendChild(box);
// Track it like an approval box so it is cleaned up when the run ends.
if (typeof activity.trackApprovalBox === 'function') activity.trackApprovalBox(box);
if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
const input = box.querySelector('.ai-agent-question-input');
const sendBtn = box.querySelector('.ai-agent-question-send');
if (input) setTimeout(() => { try { input.focus(); } catch { } }, 50);
let settled = false;
const submit = async (answerText) => {
if (settled) return;
const answer = String(answerText == null ? '' : answerText).trim();
if (!answer) { if (input) input.focus(); return; }
settled = true;
if (input) input.disabled = true;
if (sendBtn) sendBtn.disabled = true;
// Replace the bar with the answer the user gave, as a small confirmation.
box.classList.add('answered');
const bar = box.querySelector('.ai-agent-question-bar');
if (bar) bar.innerHTML = ` ${escapeAgentHtml(answer)}`;
try {
await fetch('/api/ai/agent/approve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ approvalId: payload.approvalId, answer }),
});
} catch { }
resolve();
};
if (sendBtn) sendBtn.addEventListener('click', () => submit(input ? input.value : ''));
if (input) input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); submit(input.value); }
});
});
}
async function executeFileOperation(op) {
if (!op || !op.action) {
await addChatMessage('ai', 'Unable to process file operation.');
return;
}
if (!hasPerm('files_read')) {
await addChatMessage('ai', 'You don\'t have permission to access server files.');
return;
}
if (op.action === 'list' || op.action === 'read') {
await executeFileOperationDirect(op);
} else {
if ((op.action === 'write' || op.action === 'create' || op.action === 'mkdir') && !hasPerm('files_create')) {
await addChatMessage('ai', 'You don\'t have permission to create or modify files.');
return;
}
if (op.action === 'delete' && !hasPerm('files_delete')) {
await addChatMessage('ai', 'You don\'t have permission to delete files.');
return;
}
aiPendingFileOperations.push(op);
if (aiPendingFileOperations.length === 1) {
processNextPendingOperation();
}
}
}
async function executeFileOperationDirect(op) {
if (!op || !op.action) {
await addChatMessage('ai', 'Unable to process file operation.');
return;
}
const serverName = document.documentElement.dataset.bot;
const normalizePath = (p) => {
if (!p) return '';
let normalized = String(p).trim();
while (normalized.startsWith('/')) {
normalized = normalized.slice(1);
}
return normalized;
};
const filePath = normalizePath(op.path);
try {
if (op.action === 'read') {
const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`);
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
if (response.status === 502 || (errData.error && errData.error.includes('node'))) {
await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`);
return;
} else if (response.status === 404) {
await addChatMessage('ai', `⚠️ File not found: **${filePath}**`);
return;
}
throw new Error(errData.error || `Failed to read file: ${filePath}`);
}
const data = await response.json();
if (data && data.binary) {
await addChatMessage('ai', `⚠️ **${filePath}** is a binary file — it cannot be displayed or edited as text.`);
return;
}
const fileContent = data.content || '(empty file)';
aiLastReadFileContent = fileContent;
aiLastReadFilePath = filePath;
await addChatMessage('ai', `📄 **${filePath}**:\n\`\`\`\n${fileContent}\n\`\`\`\n\nWhat would you like me to change?`, null, null, null, true);
} else if (op.action === 'write' || op.action === 'create') {
let binaryOriginal = false;
try {
const readResp = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`);
if (readResp.ok) {
const data = await readResp.json();
// A binary original is never stored as text: the mangled utf8 read
// could be written back by the undo flow. binary: true makes the
// undo refuse instead of corrupting the file.
if (data && data.binary) {
// No backup entry for a binary original: the refusal below skips
// the write anyway, and a dead {content:null} entry would be
// consumed by the next undo click just to print "Cannot undo".
binaryOriginal = true;
} else {
aiFileBackups.push({ path: filePath, content: data.content || '', timestamp: Date.now(), action: 'modify' });
}
} else {
aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'create' });
}
} catch {
aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'create' });
}
renderFileChangesBar();
// The binary backup holds no restorable bytes (content: null), so the
// destructive call must not run: the original would be lost with no
// way back, since the undo flow refuses binary restores.
if (binaryOriginal) {
await addChatMessage('ai', `⚠️ **${filePath}** is a binary file — it cannot be edited as text, so the ${op.action} was not performed. Replace the file by re-uploading it if needed.`);
return;
}
const response = await writeServerFileWithActionToken(serverName, filePath, op.content || '');
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
if (response.status === 507 || errData.error === 'disk_limit_exceeded') {
await addChatMessage('ai', `⚠️ **Disk limit exceeded.** ${errData.message || 'Free up space or increase the storage limit.'}`);
return;
}
if (response.status === 502 || (errData.error && errData.error.includes('node'))) {
await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`);
return;
}
throw new Error(errData.error || `Failed to ${op.action} file: ${filePath}`);
}
aiLastReadFileContent = null;
aiLastReadFilePath = null;
const actionWord = op.action === 'create' ? 'Created' : 'Modified';
await addChatMessage('ai', `✅ ${actionWord} **${filePath}**`, op.thinking_time_ms);
showUndoToast();
} else if (op.action === 'mkdir') {
aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'mkdir' });
renderFileChangesBar();
const response = await createServerFolderWithActionToken(serverName, filePath);
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
if (response.status === 502 || (errData.error && errData.error.includes('node'))) {
await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`);
return;
}
throw new Error(errData.error || `Failed to create folder: ${filePath}`);
}
await addChatMessage('ai', `📁 Created folder **${filePath}**`);
showUndoToast();
} else if (op.action === 'list') {
const listPath = filePath || '.';
try {
const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/list?path=${encodeURIComponent(listPath)}`);
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
const errorMsg = errData.error || `HTTP ${response.status}`;
if (response.status === 502 || errorMsg.includes('node') || errorMsg === 'node_offline') {
await addChatMessage('ai', `⚠️ **Cannot connect to server node**\n\nThe server node appears to be offline or unreachable.\n\n**Please check:**\n1. Is the node agent running?\n2. Can the panel reach the node? (check firewall)\n3. Check the server status in the dashboard\n\n*File operations require an active node connection.*`);
return;
} else if (response.status === 404) {
await addChatMessage('ai', `⚠️ Directory not found: **${listPath}**`);
return;
} else if (response.status === 403) {
await addChatMessage('ai', `⚠️ You don't have permission to access files on this server.`);
return;
}
throw new Error(errorMsg);
}
const data = await response.json();
const files = data.entries || data.files || [];
if (files.length === 0) {
await addChatMessage('ai', `📂 **${listPath === '.' ? '/' : listPath}** is empty.`);
} else {
const fileList = files.map(f => {
const isDir = f.isDirectory === true || f.type === 'dir' || f.type === 'directory';
const icon = isDir ? '📁' : '📄';
const size = isDir ? '' : (f.size ? ` (${formatFileSize(f.size)})` : '');
return `${icon} ${f.name}${size}`;
}).join('\n');
// Node listing responses can be capped (truncated): the message
// must not present the prefix as the whole folder.
const truncationNote = data.truncated ? `\n\n_(listing capped at ${files.length} entries — open a subfolder for the rest)_` : '';
await addChatMessage('ai', `📂 Contents of **${listPath === '.' ? '/' : listPath}**:\n\n${fileList}${truncationNote}`, null, null, null, true);
}
} catch (fetchErr) {
await addChatMessage('ai', `⚠️ Failed to list files: ${fetchErr.message || 'Connection error'}`);
return;
}
} else if (op.action === 'delete') {
let binaryOriginal = false;
try {
const readResp = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`);
if (readResp.ok) {
const data = await readResp.json();
// binary: true — the undo flow must not "restore" a binary file
// from mangled utf8 text (see undoFileChangeByIndex).
if (data && data.binary) {
// No backup entry for a binary original (see the write branch):
// the refusal below skips the delete, so a dead entry would only
// be consumed by the next undo click.
binaryOriginal = true;
} else {
aiFileBackups.push({ path: filePath, content: data.content || '', timestamp: Date.now(), action: 'delete' });
}
renderFileChangesBar();
}
} catch { }
// With no restorable backup of a binary original (content: null), a
// delete here would be unrecoverable — the undo flow refuses binary
// restores — so the destructive call is skipped.
if (binaryOriginal) {
await addChatMessage('ai', `⚠️ **${filePath}** is a binary file — its content cannot be backed up for undo, so the delete was not performed. Delete it from the file manager if you are sure.`);
return;
}
const response = await deleteServerPathWithActionToken(serverName, filePath);
if (!response.ok) throw new Error(`Failed to delete: ${filePath}`);
await addChatMessage('ai', `🗑️ Deleted **${filePath}**`);
showUndoToast();
}
} catch (err) {
await addChatMessage('ai', `❌ Error: ${err.message}`);
}
}
// Sole definition of formatFileSize. It must exist exactly once in this
// IIFE: a second declaration hoists over this one (last wins file-wide),
// which is how an unguarded duplicate used to take over every call site.
function formatFileSize(bytes) {
const size = Number(bytes);
if (!Number.isFinite(size) || size < 0) return 'Unknown size';
if (size === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
// Clamp the unit index so sizes >= 1024^4 never read past the last unit.
const i = Math.min(Math.floor(Math.log(size) / Math.log(k)), sizes.length - 1);
return parseFloat((size / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
function sanitizeAiVisibleAssistantText(text) {
let value = String(text || '')
.replace(/[\s\S]*?<\/think>/gi, ' ')
.replace(/[\s\S]*?<\/thinking>/gi, ' ')
.replace(/^\s*(?:thought|thinking|reasoning|analysis)\s*:\s*[\s\S]*$/gim, ' ')
.trim();
if (!value) return '';
if (/^[`'"“”‘’()[\]{}<>.,:;!?*_~\\/\-|+=\s]+$/.test(value)) return '';
const normalized = value.replace(/\s+/g, ' ').trim();
const leakedInstructionTalk = [
/\bwait,\s*the prompt says\b/i,
/\bthe prompt says\b/i,
/\bprevious reply was invalid\b/i,
/\bentire reply must be one\b/i,
//i,
/\bcurrent page server is\b/i,
/\bcurrent page server:\b/i,
/\bthe user wants to\b/i,
/\bi have the\b/i,
/\bi can use\b/i,
/\bi should use\b/i,
/\bi need to use\b/i,
/\blet'?s refine\b/i,
/\brespond with exactly one\b/i,
/\bi need to check\b/i,
/\btool which can be used\b/i
].some((pattern) => pattern.test(normalized));
const leakedToolReference = /\b(?:power_server|start_server|stop_server|kill_server|get_server_status|inspect_server|query_console|send_console_command|list_backups|create_backup|restore_backup|delete_backup)\b/i.test(normalized);
const truncatedReasoning = /(?:i should use the|i can use the|i need to use the)\s*`?$/i.test(normalized);
if (leakedInstructionTalk || (leakedToolReference && /\b(?:the user wants to|i have the|i can use|i should use|i need to use|let'?s refine|i need to check|tool which can be used)\b/i.test(normalized)) || truncatedReasoning) {
return '';
}
return value;
}
function compactAiAssistantReply(text) {
const raw = sanitizeAiVisibleAssistantText(text);
if (!raw) return raw;
return raw;
}
// adpanel:ai-server-name-dedupe — text-level hint extractor only (strips
// wrapping quotes/backticks and trailing punctuation). Deliberately NOT the
// security sanitizer: the name-collision with normalizeAiServerNameCandidate
// (top of file) previously shadowed the sanitizer file-wide via hoisting, so
// power-action targets lost traversal/length/canonicalization guarantees.
function stripServerNameHintWrapper(value) {
const normalized = String(value || '')
.trim()
.replace(/^["'`]+|["'`]+$/g, '')
.replace(/[.,!?;:]+$/g, '')
.trim();
return normalized;
}
function applyAiServerActionState(action, serverName) {
const target = stripServerNameHintWrapper(serverName);
const current = stripServerNameHintWrapper(bot);
if (!target || !current || target.toLowerCase() !== current.toLowerCase()) return;
if (action === 'start' || action === 'restart') {
resetConsoleBuffer();
}
if (action === 'start') setPowerState(POWER_STATE.STARTING);
if (action === 'stop' || action === 'kill') setPowerState(POWER_STATE.STOPPING);
if (action === 'restart') setPowerState(POWER_STATE.STARTING);
if (action === 'start' || action === 'restart') {
attachLogStreamIfRemote({ tail: 0, forceReconnect: true });
}
setTimeout(() => {
refreshPowerState({ force: true }).catch(() => { });
}, 250);
}
async function handleAiClientActions(actions) {
const list = Array.isArray(actions) ? actions : [];
const seenActionKeys = new Set();
for (const action of list) {
const type = String(action && action.type || '').trim().toLowerCase();
const targetServer = stripServerNameHintWrapper(action && action.server);
const actionKey = type === 'refresh_power_state'
? `${type}:${targetServer}:${String(action && action.action || '').trim().toLowerCase()}`
: type === 'console_command_executed'
? `${type}:${targetServer}:${String(action && action.command || '').trim()}:${Number(action && action.sentAt) || 0}`
: `${type}:${targetServer}`;
if (seenActionKeys.has(actionKey)) continue;
seenActionKeys.add(actionKey);
if (type === 'refresh_power_state') {
if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) {
applyAiServerActionState(action.action, targetServer);
}
continue;
}
if (type === 'console_command_executed') {
if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) {
const commandText = String(action.command || '').trim();
const sentAt = Number(action.sentAt) || Date.now();
if (commandText && hasConsoleReadAccess()) {
rememberConsoleCommandEcho(commandText, sentAt);
}
scheduleConsoleHistoryResync(commandText, sentAt);
}
continue;
}
if (type === 'backups_updated') {
if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) {
if (backupsModal && backupsModal.classList.contains('show')) {
await loadBackups().catch(() => { });
}
}
}
}
}
async function callAiApi(message, attachmentInfo = null, abortSignal = null) {
const modelValue = aiModelSelect?.value || '';
const { providerId, modelName } = decodeAiModelSelection(modelValue);
if (!providerId || !modelName) {
throw new Error('Please select a model first.');
}
saveSelectedAiModelToStorage(modelValue);
const config = AI_PROVIDERS[providerId];
if (!config) {
throw new Error('Unknown provider.');
}
const filePatterns = [
/(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)\s+(?:in\s+)?(?:the\s+)?(?:file\s+)?([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))/i,
/(?:in|at)\s+([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))/i,
/([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))\s+(?:and\s+)?(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)/i
];
let targetFile = null;
for (const pattern of filePatterns) {
const match = message.match(pattern);
if (match) {
targetFile = match[1];
break;
}
}
if (targetFile && !aiLastReadFileContent && hasPerm('files_read')) {
try {
const serverName = document.documentElement.dataset.bot;
const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(targetFile)}`);
if (response.ok) {
const data = await response.json();
// binary: true — a binary file is never fed to the AI as mangled text.
if (data.content && !data.binary) {
aiLastReadFileContent = data.content;
aiLastReadFilePath = targetFile;
}
}
} catch (e) {
}
}
let augmentedMessage = message;
if (aiLastReadFileContent && aiLastReadFilePath) {
const modifyIntent = /(?:set|change|modify|edit|update|enable|disable|fix|optimize|turn|make|add|remove)/i.test(message);
if (modifyIntent) {
augmentedMessage = `User request: ${message}
The file "${aiLastReadFilePath}" currently contains:
\`\`\`
${aiLastReadFileContent}
\`\`\`
Apply the user's requested changes. You MUST output the complete modified file using this exact format:
FILE_WRITE:${aiLastReadFilePath}
---FILE_CONTENT_START---
(paste the ENTIRE file with changes applied here)
---FILE_CONTENT_END---`;
}
}
const canReadFiles = hasPerm('files_read');
const canWriteFiles = hasPerm('files_create');
const canDeleteFiles = hasPerm('files_delete');
const canReadConsole = hasPerm('console_read');
const canWriteConsole = hasPerm('console_write');
const canStartServer = hasPerm('server_start');
const canStopServer = hasPerm('server_stop');
const canViewBackups = hasPerm('backups_view');
const canCreateBackups = hasPerm('backups_create');
const canDeleteBackups = hasPerm('backups_delete');
const currentServerName = String(bot || '').trim();
let systemPrompt;
const baseIdentity = `You are ${BRAND_NAME} Agent, an intelligent AI assistant integrated into ${BRAND_NAME} — an enterprise server management panel that lets users host and manage their Docker-based servers (FiveM, Minecraft, and more).
CORE BEHAVIOR:
1. NEVER use diacritical marks, accents, or special unicode characters in ANY language. Write as if you only have a standard US English keyboard.
2. Reply naturally, like a fast voice assistant.
3. Default to one short sentence. Use two short sentences only when needed.
4. Prefer plain text. Use markdown only when it clearly helps.
5. For greetings, answer in 2-6 words.
6. For actions, say what you did or what you need next.
7. Prioritize the user's latest message and the live server context over older chat history if they conflict.
8. Never narrate internal planning, hidden reasoning, or which tool you are about to use.
9. Never say phrases like "The user wants", "I need to", "I should use", "Plan", or "Current page server".`;
const nativeToolLines = [
'Sensitive server actions, console actions, and backup actions are executed through native backend tools.',
`Current server: ${currentServerName || 'current-server'}.`,
'You HAVE dedicated power tools for this server: start_server, stop_server, kill_server, and power_server (restart). They are always available.',
'start_server powers on a server that is currently stopped or offline, so you CAN start a stopped server. stop_server stops a running server, kill_server force kills it, power_server restarts it.',
'NEVER say you can only send console commands to a running server, and NEVER say there is no tool to start a stopped server. That is false: start_server does exactly that.',
'To start, stop, restart, or kill this server, always use these power tools. The console can NEVER power a server, so never send words like "start", "stop", or "kill" to the console to control power.',
'To know if the server is running or stopped, use the status tool (get_server_status); it reports the real live state.',
'Do not explain your internal planning or mention internal tool names in the visible reply.',
'Do not emit SERVER_START, SERVER_STOP, SERVER_RESTART, or SERVER_KILL lines.',
'If backend tools are needed, let the backend orchestrator handle them; never write planning text such as "I need to use inspect_server".',
'Use the current server when the user means this server or current server.',
'Backend permissions are re-checked on every native action, so do not claim success before the tool result confirms it.',
'For live console checks or crash diagnosis, prefer the native console inspection tool.',
'For real console execution, only use the native console command tool when the user explicitly asked to run a command.',
'For backup restore or delete, inspect the available backups first when the reference is unclear.'
].filter(Boolean).join('\n');
if (canReadFiles) {
systemPrompt = `${baseIdentity}
You have access to this server's file system. You can browse, read, create, edit, and manage files directly.
${nativeToolLines}
Use these commands (one per line, no extra formatting):
FILE_LIST:.
FILE_LIST:config
FILE_READ:config/settings.yml
${canWriteFiles ? `FILE_MKDIR:plugins/myfolder` : ''}
${canDeleteFiles ? `FILE_DELETE:old-file.txt` : ''}
${canWriteFiles ? `To create or modify a file:
FILE_CREATE:path/to/file.txt
---FILE_CONTENT_START---
(file content here)
---FILE_CONTENT_END---
To modify an existing file:
FILE_WRITE:path/to/file.yml
---FILE_CONTENT_START---
(complete modified file content)
---FILE_CONTENT_END---` : ''}
IMPORTANT RULES:
1. Put each command on its own line
2. Path comes immediately after the colon (no spaces)
3. Use . for root directory listing
4. Use relative paths (no leading /)
5. Only list files or perform file operations when the user explicitly asks for it
6. When modifying a file, output the COMPLETE file content
7. After completing a task, briefly describe what you did
8. Do NOT automatically list files or show server files unless the user specifically asks to see them
9. When the user greets you or asks general questions, respond conversationally without performing file operations
10. When asked what ${BRAND_NAME} is, explain it is an enterprise Docker server management panel with file management, console, scheduling, backups, store, and AI agent features`;
} else {
systemPrompt = `${baseIdentity}
You do NOT have file system access for this user. Do not attempt to list, read, or modify any server files.
${nativeToolLines}
Instead, provide helpful advice, explain concepts, troubleshoot issues, and guide users on configuring their servers. If the user asks you to manage files, let them know they need file management permissions and suggest contacting their server administrator.`;
}
if (canReadConsole) {
systemPrompt += `\n\nWhen the user shares server logs or console output, analyze them carefully and provide helpful troubleshooting advice. Identify errors, warnings, and suggest specific fixes.`;
}
if (attachmentInfo && attachmentInfo.isImage) {
systemPrompt += `\n\nYou also have vision capabilities. When the user provides an image, analyze it and describe what you see. If the image appears to be a screenshot or configuration, provide helpful insights about it.`;
}
const historyMessages = aiChatHistory.slice(-10).map(m => {
if (m.attachment && m.attachment.isImage) {
return {
role: m.role === 'ai' ? 'assistant' : m.role,
content: m.content,
image: m.attachment.data
};
}
return { role: m.role === 'ai' ? 'assistant' : m.role, content: m.content };
});
if (historyMessages.length > 0 && historyMessages[historyMessages.length - 1].role === 'user') {
if (attachmentInfo && attachmentInfo.isImage) {
historyMessages[historyMessages.length - 1] = { role: 'user', content: augmentedMessage, image: attachmentInfo.data };
} else {
historyMessages[historyMessages.length - 1] = { role: 'user', content: augmentedMessage };
}
}
const messages = [
{ role: 'system', content: systemPrompt },
...historyMessages
];
const result = await callAiBackendProxy(providerId, modelName, messages, abortSignal);
if (result && typeof result.content === 'string') {
result.content = compactAiAssistantReply(sanitizeAiVisibleAssistantText(result.content));
}
if (result && typeof result.message === 'string') {
result.message = compactAiAssistantReply(sanitizeAiVisibleAssistantText(result.message));
}
if (result.fileOperation && result.action === 'write' && aiLastReadFileContent) {
const originalContent = aiLastReadFileContent;
const originalLength = originalContent.length;
const newContent = result.content || '';
const newLength = newContent.length;
if (originalLength > 100 && newLength < originalLength * 0.3) {
const mergedContent = tryMergePartialChange(originalContent, newContent, aiLastReadFilePath);
if (mergedContent) {
result.content = mergedContent;
} else {
const savedPath = aiLastReadFilePath;
aiLastReadFileContent = null;
aiLastReadFilePath = null;
return {
content: `The AI only provided partial content which would corrupt your file. Please try again with a clearer instruction like "in ${savedPath}, change [setting] to [value]".`
};
}
}
aiLastReadFileContent = null;
aiLastReadFilePath = null;
}
return result;
}
function tryMergePartialChange(originalContent, partialContent, filePath) {
const ext = filePath.split('.').pop().toLowerCase();
if (['yml', 'yaml', 'properties'].includes(ext)) {
const lines = partialContent.trim().split('\n');
let modifiedContent = originalContent;
let changesMade = false;
for (const line of lines) {
const yamlMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+)\s*:\s*(.*)$/);
const propsMatch = line.match(/^([a-zA-Z0-9_.-]+)\s*=\s*(.*)$/);
if (yamlMatch) {
const [, indent, key, value] = yamlMatch;
const keyPattern = new RegExp(`^(\\s*)${escapeRegex(key)}\\s*:.*$`, 'gm');
if (keyPattern.test(modifiedContent)) {
modifiedContent = modifiedContent.replace(keyPattern, `$1${key}: ${value}`);
changesMade = true;
}
} else if (propsMatch) {
const [, key, value] = propsMatch;
const keyPattern = new RegExp(`^${escapeRegex(key)}\\s*=.*$`, 'gm');
if (keyPattern.test(modifiedContent)) {
modifiedContent = modifiedContent.replace(keyPattern, `${key}=${value}`);
changesMade = true;
}
}
}
if (changesMade) {
return modifiedContent;
}
}
if (ext === 'json') {
try {
const originalJson = JSON.parse(originalContent);
const partialJson = JSON.parse(partialContent);
const merged = deepMerge(originalJson, partialJson);
return JSON.stringify(merged, null, 2);
} catch {
}
}
return null;
}
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
result[key] = deepMerge(result[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
return result;
}
// adpanel:ai-tool-token-gate — client half: the chat POST carries the
// page's session-bound action tokens for the mutating AI tools whose relay
// twins verify them (backupCreate/backupRestore/backupDelete — the same
// GET /permissions mints those relays consume), so the AI surface enforces
// the same action-token gate as its relay twins. The page's tokens are
// minted for the canonical server this page is bound to (data-bot), which
// is the only server whose mutating tools can verify here. One-time keys
// always re-mint inside ensureServerActionToken, so they run first and the
// repeatable key reuses their fresh perms cache; keys whose mint the user's
// perms exclude are skipped without a fetch (the mint never issues them).
// Every failure degrades to sending without that token — non-mutating chat
// never needs tokens, and a mutating tool fired without one surfaces the
// server's "refresh the page and try again" tool error.
const AI_CHAT_ACTION_TOKEN_KEYS = [
{ tokenKey: 'backupRestore', perm: 'backups_create' },
{ tokenKey: 'backupDelete', perm: 'backups_delete' },
{ tokenKey: 'backupCreate', perm: 'backups_create' }
];
async function collectAiChatActionTokens() {
const tokens = {};
for (const entry of AI_CHAT_ACTION_TOKEN_KEYS) {
try {
if (entry.perm && !hasPerm(entry.perm)) continue;
const token = await ensureServerActionToken(entry.tokenKey);
if (token) tokens[entry.tokenKey] = token;
} catch (e) {
// Token refresh must never block the message send; the tool-level
// gate error tells the user how to recover.
}
}
return tokens;
}
async function callAiBackendProxy(provider, model, messages, abortSignal = null, onChunk = null) {
const actionTokens = await collectAiChatActionTokens();
const fetchOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
provider,
model,
messages,
stream: !!onChunk,
actionTokens,
serverContext: {
currentServer: String(bot || '').trim()
}
})
};
if (abortSignal) {
fetchOptions.signal = abortSignal;
}
const response = await fetch('/api/ai/chat', fetchOptions);
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.error || `API error: ${response.status}`);
}
if (onChunk) {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let done = false;
let buffer = '';
let thinkingTimeMs = null;
let thinkingContent = '';
let fullContent = '';
while (!done) {
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (value) {
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('data: ')) {
if (trimmed === 'data: [DONE]') continue;
try {
const parsed = JSON.parse(trimmed.substring(6));
if (parsed.error) {
throw new Error(parsed.error);
}
if (parsed.chunk) {
fullContent += parsed.chunk;
onChunk(parsed.chunk, fullContent);
}
if (parsed.done) {
thinkingTimeMs = parsed.thinking_time_ms;
thinkingContent = typeof parsed.thinking_content === 'string' ? parsed.thinking_content : thinkingContent;
}
} catch (e) {
}
}
}
}
}
const parsedContent = parseAiResponse(fullContent);
parsedContent.thinking_time_ms = thinkingTimeMs;
parsedContent.thinking_content = thinkingContent;
parsedContent.clientActions = [];
return parsedContent;
} else {
const data = await response.json();
if (!data.ok) {
throw new Error(data.error || 'AI request failed');
}
const result = parseAiResponse(data.content || '');
result.thinking_time_ms = data.thinking_time_ms || null;
result.thinking_content = typeof data.thinking_content === 'string' ? data.thinking_content : '';
result.clientActions = Array.isArray(data.clientActions) ? data.clientActions : [];
// This stored payload has no other consumer, so run the server-queued
// client actions (e.g. backups_updated after the AI creates a backup)
// right here, as soon as the response is parsed. Fire-and-forget with a
// swallowed rejection: a client-actions failure must never break or
// delay the chat rendering that depends on this return value. (The
// streaming branch above never carries client actions.)
try {
if (result.clientActions.length > 0) {
handleAiClientActions(result.clientActions).catch(() => { });
}
} catch (e) { }
return result;
}
}
async function callOpenAiCompatible(endpoint, apiKey, model, messages, providerId) {
return await callAiBackendProxy(providerId, model, messages);
}
async function callGoogleAi(apiKey, model, messages) {
return await callAiBackendProxy('google', model, messages);
}
async function callCohereAi(apiKey, model, messages) {
return await callAiBackendProxy('cohere', model, messages);
}
function parseAiResponse(content) {
if (!content || typeof content !== 'string') {
return { content: content || 'No response received.' };
}
let trimmed = content.trim().replace(/\\n/g, '\n');
const operations = [];
let remainingMessage = trimmed;
const toolCallPattern = /\[TOOL_CALL\]\s*\{tool\s*=>\s*"([^"]+)",\s*args\s*=>\s*\{([^}]*)\}\s*\}\s*\[\/TOOL_CALL\]/gi;
let toolMatch;
while ((toolMatch = toolCallPattern.exec(trimmed)) !== null) {
const toolName = toolMatch[1].toLowerCase();
const argsContent = toolMatch[2];
const pathMatch = argsContent.match(/--path\s+"([^"]+)"/i);
const contentArgMatch = argsContent.match(/--content\s+"([^"]+)"/i);
if (pathMatch) {
const path = pathMatch[1];
const fileContent = contentArgMatch ? contentArgMatch[1] : null;
if (toolName === 'file_mkdir' || toolName === 'mkdir') {
operations.push({ action: 'mkdir', path });
} else if (toolName === 'file_create' || toolName === 'create') {
operations.push({ action: 'create', path, content: fileContent || '' });
} else if (toolName === 'file_write' || toolName === 'write') {
operations.push({ action: 'write', path, content: fileContent || '' });
} else if (toolName === 'file_read' || toolName === 'read') {
operations.push({ action: 'read', path });
} else if (toolName === 'file_list' || toolName === 'list') {
operations.push({ action: 'list', path });
} else if (toolName === 'file_delete' || toolName === 'delete') {
operations.push({ action: 'delete', path });
}
}
remainingMessage = remainingMessage.replace(toolMatch[0], '');
}
const invokePattern = /\s*<(FILE_\w+)>([\s\S]*?)<\/\1>\s*<\/invoke>/gi;
let invokeMatch;
while ((invokeMatch = invokePattern.exec(trimmed)) !== null) {
const action = invokeMatch[1].toLowerCase().replace('file_', '');
const innerContent = invokeMatch[2];
parseXmlOperation(action, innerContent, operations);
remainingMessage = remainingMessage.replace(invokeMatch[0], '');
}
const directPattern = /<(FILE_\w+)>([\s\S]*?)<\/\1>/gi;
let directMatch;
while ((directMatch = directPattern.exec(trimmed)) !== null) {
if (!operations.some(op => op._rawMatch === directMatch[0])) {
const action = directMatch[1].toLowerCase().replace('file_', '');
const innerContent = directMatch[2];
parseXmlOperation(action, innerContent, operations);
remainingMessage = remainingMessage.replace(directMatch[0], '');
}
}
const antlPattern = /]*>([\s\S]*?)<\/antml:invoke>/gi;
let antlMatch;
while ((antlMatch = antlPattern.exec(trimmed)) !== null) {
const action = antlMatch[1].toLowerCase().replace('file_', '');
const innerContent = antlMatch[2];
parseXmlOperation(action, innerContent, operations);
remainingMessage = remainingMessage.replace(antlMatch[0], '');
}
const listPattern = /FILE_LIST:([^\s\n]+)/gi;
let listMatch;
while ((listMatch = listPattern.exec(trimmed)) !== null) {
let path = listMatch[1].trim();
if (path.includes('FILE_')) continue;
if (!operations.some(op => op.action === 'list' && op.path === path)) {
operations.push({ action: 'list', path });
}
remainingMessage = remainingMessage.replace(listMatch[0], '');
}
const readPattern = /FILE_READ:([^\s\n]+)/gi;
let readMatch;
while ((readMatch = readPattern.exec(trimmed)) !== null) {
let path = readMatch[1].trim();
if (path.includes('FILE_')) continue;
if (!operations.some(op => op.action === 'read' && op.path === path)) {
operations.push({ action: 'read', path });
}
remainingMessage = remainingMessage.replace(readMatch[0], '');
}
const mkdirPattern = /FILE_MKDIR:([^\s\n]+)/gi;
let mkdirMatch;
while ((mkdirMatch = mkdirPattern.exec(trimmed)) !== null) {
let path = mkdirMatch[1].trim();
if (path.includes('FILE_')) continue;
if (!operations.some(op => op.action === 'mkdir' && op.path === path)) {
operations.push({ action: 'mkdir', path });
}
remainingMessage = remainingMessage.replace(mkdirMatch[0], '');
}
const deletePattern = /FILE_DELETE:([^\s\n]+)/gi;
let deleteMatch;
while ((deleteMatch = deletePattern.exec(trimmed)) !== null) {
let path = deleteMatch[1].trim();
if (path.includes('FILE_')) continue;
if (!operations.some(op => op.action === 'delete' && op.path === path)) {
operations.push({ action: 'delete', path });
}
remainingMessage = remainingMessage.replace(deleteMatch[0], '');
}
const createPattern = /FILE_CREATE:([^\s\n]+)/i;
const createMatch = trimmed.match(createPattern);
if (createMatch) {
const filePath = createMatch[1].trim();
if (!filePath.includes('FILE_') && !operations.some(op => op.action === 'create' && op.path === filePath)) {
const fileContent = extractFileContent(trimmed, createMatch[0]);
if (fileContent !== null) {
operations.push({ action: 'create', path: filePath, content: fileContent });
remainingMessage = remainingMessage.replace(/FILE_CREATE:[^\n]*[\s\S]*?---FILE_CONTENT_END---/i, '');
remainingMessage = remainingMessage.replace(/FILE_CREATE:[^\n]*[\s\S]*?```[\s\S]*?```/i, '');
}
}
}
const writePattern = /FILE_WRITE:([^\s\n]+)/i;
const writeMatch = trimmed.match(writePattern);
if (writeMatch) {
const filePath = writeMatch[1].trim();
if (!filePath.includes('FILE_') && !operations.some(op => op.action === 'write' && op.path === filePath)) {
const fileContent = extractFileContent(trimmed, writeMatch[0]);
if (fileContent !== null) {
operations.push({ action: 'write', path: filePath, content: fileContent });
remainingMessage = remainingMessage.replace(/FILE_WRITE:[^\n]*[\s\S]*?---FILE_CONTENT_END---/i, '');
remainingMessage = remainingMessage.replace(/FILE_WRITE:[^\n]*[\s\S]*?```[\s\S]*?```/i, '');
} else {
return { content: `I couldn't extract the file content for ${filePath}. Please try again.` };
}
}
}
remainingMessage = remainingMessage
.replace(/---FILE_CONTENT_START---|---FILE_CONTENT_END---/g, '')
.replace(/<\/?antml:[^>]+>/g, '')
.replace(/<\/?invoke>/g, '')
.replace(/<\/?FILE_\w+>/g, '')
.replace(/[^<]*<\/path>/g, '')
.replace(/[\s\S]*?<\/content>/g, '')
.replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, '')
.replace(/SERVER_(?:START|STOP|RESTART|KILL)(?::[^\s\n]+)?/gi, '')
.trim();
if (operations.length > 0) {
const response = { message: remainingMessage || null };
if (operations.length === 1) {
response.fileOperation = true;
Object.assign(response, operations[0]);
} else if (operations.length > 1) {
response.fileOperations = operations;
}
return response;
}
return { content };
}
function parseXmlOperation(action, innerContent, operations) {
let path = null;
let fileContent = null;
const pathMatch = innerContent.match(/([^<]+)<\/path>/i);
if (pathMatch) {
path = pathMatch[1].trim();
}
const contentMatch = innerContent.match(/([\s\S]*?)<\/content>/i);
if (contentMatch) {
fileContent = contentMatch[1].trim();
}
if (!path) {
const plainPath = innerContent.trim().split(/\s+/)[0];
if (plainPath && !plainPath.startsWith('<')) {
path = plainPath;
}
}
if (!path) return;
switch (action) {
case 'list':
operations.push({ action: 'list', path });
break;
case 'read':
operations.push({ action: 'read', path });
break;
case 'mkdir':
operations.push({ action: 'mkdir', path });
break;
case 'delete':
operations.push({ action: 'delete', path });
break;
case 'create':
if (fileContent !== null) {
operations.push({ action: 'create', path, content: fileContent });
}
break;
case 'write':
if (fileContent !== null) {
operations.push({ action: 'write', path, content: fileContent });
}
break;
}
}
function extractFileContent(fullContent, afterMarker) {
const afterIdx = fullContent.indexOf(afterMarker);
if (afterIdx === -1) return null;
const afterWrite = fullContent.slice(afterIdx + afterMarker.length);
const startMarker = '---FILE_CONTENT_START---';
const endMarker = '---FILE_CONTENT_END---';
let startIdx = afterWrite.indexOf(startMarker);
let endIdx = afterWrite.indexOf(endMarker);
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
return afterWrite.slice(startIdx + startMarker.length, endIdx).trim();
}
const codeBlockMatch = afterWrite.match(/```(?:\w*\n)?([\s\S]*?)```/);
if (codeBlockMatch) {
return codeBlockMatch[1].trim();
}
const lines = afterWrite.split('\n');
const contentLines = [];
let foundContent = false;
for (const line of lines) {
const trimLine = line.trim();
if (!foundContent && trimLine === '') continue;
if (trimLine.startsWith('FILE_') || trimLine.startsWith('---')) break;
foundContent = true;
contentLines.push(line);
}
const result = contentLines.join('\n').trim();
return result || null;
}
function renderFileChangesBar() {
if (!aiFileChangesBar || !aiFileChangesList || !aiFileChangesCount) return;
if (aiFileBackups.length === 0) {
aiFileChangesBar.classList.remove('show');
return;
}
aiFileChangesBar.classList.add('show');
aiFileChangesCount.textContent = aiFileBackups.length;
aiFileChangesList.innerHTML = aiFileBackups.map((backup, index) => {
const actionLabel = backup.action === 'create' ? 'Created' :
backup.action === 'mkdir' ? 'Folder Created' :
backup.action === 'delete' ? 'Deleted' : 'Modified';
const iconClass = backup.action === 'create' ? 'create' :
backup.action === 'mkdir' ? 'mkdir' :
backup.action === 'delete' ? 'delete' : 'modify';
const icon = backup.action === 'create' ? 'fa-file-circle-plus' :
backup.action === 'mkdir' ? 'fa-folder-plus' :
backup.action === 'delete' ? 'fa-trash' : 'fa-file-pen';
return `
${escapeHtmlAi(backup.path).replace(/ /g, '')}
${actionLabel}
`;
}).join('');
aiFileChangesList.querySelectorAll('.ai-file-change-accept').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const index = parseInt(btn.dataset.index, 10);
acceptFileChange(index);
});
});
aiFileChangesList.querySelectorAll('.ai-file-change-undo').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const index = parseInt(btn.dataset.index, 10);
undoFileChangeByIndex(index);
});
});
}
function acceptFileChange(index) {
if (index < 0 || index >= aiFileBackups.length) return;
const backup = aiFileBackups[index];
aiFileBackups.splice(index, 1);
renderFileChangesBar();
addChatMessage('ai', `✓ Accepted change to **${backup.path}**`);
}
async function acceptAllFileChanges() {
const count = aiFileBackups.length;
aiFileBackups = [];
renderFileChangesBar();
await addChatMessage('ai', `✓ Accepted all ${count} file change(s)`);
hideUndoToast();
}
async function undoFileChangeByIndex(index) {
if (index < 0 || index >= aiFileBackups.length) return;
const backup = aiFileBackups[index];
aiFileBackups.splice(index, 1);
renderFileChangesBar();
// A text backup of a binary original holds mangled utf8 bytes; writing it
// back would corrupt the file, so the restore is refused.
if (backup.binary) {
await addChatMessage('ai', `↩️ Cannot undo **${backup.path}**: the original file was binary — restore it by re-uploading the file.`);
return;
}
const serverName = document.documentElement.dataset.bot;
try {
if (backup.action === 'create' || backup.action === 'mkdir') {
const response = await deleteServerPathWithActionToken(serverName, backup.path, backup.action === 'mkdir');
if (!response.ok) throw new Error('Failed to delete');
await addChatMessage('ai', `↩️ Undone: Deleted ${backup.path}`);
} else if (backup.action === 'delete') {
const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content);
if (response.status === 507) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.');
}
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Failed to restore file');
}
await addChatMessage('ai', `↩️ Undone: Restored ${backup.path}`);
} else {
const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content);
if (response.status === 507) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.');
}
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Failed to restore file');
}
await addChatMessage('ai', `↩️ Undone: Reverted ${backup.path}`);
}
} catch (err) {
await addChatMessage('ai', `❌ Undo failed: ${err.message}`);
}
}
async function undoAllFileChanges() {
const backupsToUndo = [...aiFileBackups];
for (let i = backupsToUndo.length - 1; i >= 0; i--) {
await undoFileChangeByIndex(0);
}
hideUndoToast();
}
function showConfirmDialog(op) {
if (!aiConfirmDialog) return;
aiCurrentPendingOp = op;
const actionLabels = {
'write': 'Modify File',
'create': 'Create File',
'mkdir': 'Create Folder',
'delete': 'Delete'
};
if (aiConfirmAction) aiConfirmAction.textContent = actionLabels[op.action] || op.action.toUpperCase();
if (aiConfirmPath) aiConfirmPath.textContent = op.path;
if (aiConfirmPreview) {
if ((op.action === 'write' || op.action === 'create') && op.content) {
const preview = op.content.length > 500 ? op.content.slice(0, 500) + '\n... (truncated)' : op.content;
aiConfirmPreview.textContent = preview;
aiConfirmPreview.style.display = 'block';
} else {
aiConfirmPreview.style.display = 'none';
}
}
aiConfirmDialog.classList.add('show');
}
function hideConfirmDialog() {
if (!aiConfirmDialog) return;
aiConfirmDialog.classList.remove('show');
aiCurrentPendingOp = null;
}
async function processNextPendingOperation() {
if (aiPendingFileOperations.length === 0) return;
const op = aiPendingFileOperations[0];
if (op.action === 'list' || op.action === 'read') {
aiPendingFileOperations.shift();
await executeFileOperationDirect(op);
processNextPendingOperation();
} else {
showConfirmDialog(op);
}
}
async function handleConfirmAllow() {
if (!aiCurrentPendingOp) return;
const op = aiCurrentPendingOp;
hideConfirmDialog();
aiPendingFileOperations.shift();
await executeFileOperationDirect(op);
processNextPendingOperation();
}
async function handleConfirmDeny() {
if (!aiCurrentPendingOp) return;
const op = aiCurrentPendingOp;
hideConfirmDialog();
aiPendingFileOperations.shift();
await addChatMessage('ai', `⛔ Operation denied: ${op.action} ${op.path}`);
processNextPendingOperation();
}
let undoToastTimeout = null;
function showUndoToast() {
if (!aiUndoToast) return;
if (undoToastTimeout) {
clearTimeout(undoToastTimeout);
undoToastTimeout = null;
}
aiUndoToast.classList.add('show');
undoToastTimeout = setTimeout(() => {
hideUndoToast();
}, 8000);
}
function hideUndoToast() {
if (!aiUndoToast) return;
if (undoToastTimeout) {
clearTimeout(undoToastTimeout);
undoToastTimeout = null;
}
aiUndoToast.classList.remove('show');
}
async function undoLastFileChange() {
if (aiFileBackups.length === 0) return;
const backup = aiFileBackups.pop();
if (!backup) return;
// A text backup of a binary original holds mangled utf8 bytes; writing it
// back would corrupt the file, so the restore is refused.
if (backup.binary) {
await addChatMessage('ai', `↩️ Cannot undo **${backup.path}**: the original file was binary — restore it by re-uploading the file.`);
return;
}
const serverName = document.documentElement.dataset.bot;
try {
if (backup.action === 'create' || backup.action === 'mkdir') {
const response = await deleteServerPathWithActionToken(serverName, backup.path, backup.action === 'mkdir');
if (!response.ok) throw new Error('Failed to delete');
await addChatMessage('ai', `↩️ Undone: Deleted ${backup.path}`);
} else if (backup.action === 'delete') {
const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content);
if (response.status === 507) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.');
}
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Failed to restore file');
}
await addChatMessage('ai', `↩️ Undone: Restored ${backup.path}`);
} else {
const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content);
if (response.status === 507) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.');
}
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || 'Failed to restore file');
}
await addChatMessage('ai', `↩️ Undone: Reverted ${backup.path}`);
}
hideUndoToast();
} catch (err) {
await addChatMessage('ai', `❌ Undo failed: ${err.message}`);
}
}
function clearAiChat() {
aiChatHistory = [];
localStorage.removeItem(AI_CHAT_HISTORY);
renderChatHistory();
}
if (aiHelpModalClose) {
aiHelpModalClose.addEventListener('click', closeAiHelpModal);
}
if (aiProviderGrid) {
aiProviderGrid.addEventListener('click', (e) => {
const card = e.target.closest('[data-provider]');
if (card) {
showApiKeyForm(card.dataset.provider);
}
});
}
if (aiKeyBack) {
aiKeyBack.addEventListener('click', hideApiKeyForm);
}
if (aiKeyToggle && aiApiKeyInput) {
aiKeyToggle.addEventListener('click', () => {
const isPassword = aiApiKeyInput.type === 'password';
aiApiKeyInput.type = isPassword ? 'text' : 'password';
aiKeyToggle.innerHTML = ``;
});
}
if (aiApiKeyInput) {
aiApiKeyInput.addEventListener('input', () => {
updateAiProviderFormState();
});
}
if (aiBaseUrlInput) {
aiBaseUrlInput.addEventListener('input', () => {
updateAiProviderFormState();
});
}
if (aiKeySave) {
aiKeySave.addEventListener('click', async () => {
if (!aiCurrentProvider) return;
aiKeySave.disabled = true;
aiKeySave.textContent = 'Connecting...';
const result = await saveAiProviderConfig(aiCurrentProvider, {
key: aiApiKeyInput?.value.trim() || '',
baseUrl: aiBaseUrlInput?.value.trim() || ''
});
if (result.ok) {
await updateProviderStatuses();
hideApiKeyForm();
if (hasConfiguredProvider()) {
if (aiHelpSetup) aiHelpSetup.style.display = 'none';
if (aiHelpChat) aiHelpChat.style.display = 'flex';
await populateModelSelector();
await loadChatHistory();
}
} else {
alert(result.error || 'Failed to connect provider');
}
aiKeySave.textContent = 'Save & Connect';
updateAiProviderFormState();
});
}
if (aiModelTrigger) {
aiModelTrigger.addEventListener('click', (e) => {
e.stopPropagation();
if (aiModelTrigger.disabled) return;
const willOpen = !aiModelSelector?.classList.contains('open');
closeAiModelDropdown();
if (willOpen && aiModelSelector) {
aiModelSelector.classList.add('open');
aiModelTrigger.setAttribute('aria-expanded', 'true');
aiModelOptions?.setAttribute('aria-hidden', 'false');
}
});
aiModelTrigger.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
aiModelTrigger.click();
} else if (e.key === 'Escape') {
closeAiModelDropdown();
}
});
}
if (aiModelOptions && aiModelSelect) {
const handleAiModelOptionSelect = (optionButton) => {
if (!optionButton) return;
if (!aiModelSelector?.classList.contains('open')) return;
const nextValue = optionButton.dataset.value || '';
if (!nextValue) return;
aiModelSelect.value = nextValue;
aiModelSelect.dispatchEvent(new Event('change', { bubbles: true }));
updateAiModelSelectorState();
closeAiModelDropdown();
aiModelTrigger?.focus();
};
aiModelOptions.addEventListener('pointerdown', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
e.preventDefault();
handleAiModelOptionSelect(optionButton);
});
aiModelOptions.addEventListener('click', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
handleAiModelOptionSelect(optionButton);
});
}
if (aiModelSelect) {
aiModelSelect.addEventListener('change', () => updateAiModelSelectorState({ persist: true }));
}
document.addEventListener('click', (e) => {
if (!e.target.closest('#aiModelSelector')) {
closeAiModelDropdown();
}
});
// Ask / Don't Ask selector. Mirrors the model selector's open/close +
// option-select behavior. "ask" (default) keeps the per-action approval
// prompts; "dont_ask" tells the server to auto-approve every sensitive tool
// for this run. The choice is persisted in localStorage and sent with each
// agent run as `askMode`.
const ASK_MODE_STORAGE_KEY = 'adpanelAgentAskMode';
const ASK_MODE_LABELS = { ask: 'Ask', dont_ask: "Don't Ask" };
function getAgentAskMode() {
try {
const v = String(localStorage.getItem(ASK_MODE_STORAGE_KEY) || '').trim();
return v === 'dont_ask' ? 'dont_ask' : 'ask';
} catch { return 'ask'; }
}
function updateAskModeSelectorState() {
const mode = getAgentAskMode();
if (aiAskModeCurrent) aiAskModeCurrent.textContent = ASK_MODE_LABELS[mode] || 'Ask';
if (aiAskModeOptions) {
aiAskModeOptions.querySelectorAll('.ai-model-option').forEach((opt) => {
opt.classList.toggle('selected', (opt.dataset.value || '') === mode);
opt.setAttribute('aria-selected', (opt.dataset.value || '') === mode ? 'true' : 'false');
});
}
}
function closeAskModeDropdown() {
if (!aiAskModeSelector || !aiAskModeTrigger) return;
aiAskModeSelector.classList.remove('open');
aiAskModeTrigger.setAttribute('aria-expanded', 'false');
aiAskModeOptions?.setAttribute('aria-hidden', 'true');
}
function setAgentAskMode(mode) {
const next = mode === 'dont_ask' ? 'dont_ask' : 'ask';
try { localStorage.setItem(ASK_MODE_STORAGE_KEY, next); } catch { }
updateAskModeSelectorState();
}
if (aiAskModeTrigger) {
aiAskModeTrigger.addEventListener('click', (e) => {
e.stopPropagation();
const willOpen = !aiAskModeSelector?.classList.contains('open');
closeAskModeDropdown();
if (willOpen && aiAskModeSelector) {
aiAskModeSelector.classList.add('open');
aiAskModeTrigger.setAttribute('aria-expanded', 'true');
aiAskModeOptions?.setAttribute('aria-hidden', 'false');
}
});
aiAskModeTrigger.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
aiAskModeTrigger.click();
} else if (e.key === 'Escape') {
closeAskModeDropdown();
}
});
}
if (aiAskModeOptions) {
const handleAskModeOptionSelect = (optionButton) => {
if (!optionButton) return;
if (!aiAskModeSelector?.classList.contains('open')) return;
const nextValue = optionButton.dataset.value || '';
if (!nextValue) return;
setAgentAskMode(nextValue);
closeAskModeDropdown();
aiAskModeTrigger?.focus();
};
aiAskModeOptions.addEventListener('pointerdown', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
e.preventDefault();
handleAskModeOptionSelect(optionButton);
});
aiAskModeOptions.addEventListener('click', (e) => {
const optionButton = e.target.closest('.ai-model-option');
if (!optionButton) return;
handleAskModeOptionSelect(optionButton);
});
}
document.addEventListener('click', (e) => {
if (!e.target.closest('#aiAskModeSelector')) {
closeAskModeDropdown();
}
});
updateAskModeSelectorState();
if (aiChatInput) {
aiChatInput.addEventListener('input', () => {
updateSendButton();
aiChatInput.style.height = 'auto';
aiChatInput.style.height = Math.min(aiChatInput.scrollHeight, 120) + 'px';
});
aiChatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!e.repeat) sendAiMessage();
}
});
aiChatInput.addEventListener('paste', (e) => {
const clipboardItems = e.clipboardData?.items;
if (!clipboardItems) return;
for (const item of clipboardItems) {
if (item.type.startsWith('image/')) {
e.preventDefault();
const file = item.getAsFile();
if (file) {
handleFileAttachment(file);
}
return;
}
}
});
}
if (aiChatSend) {
aiChatSend.addEventListener('click', (e) => e.detail < 2 && sendAiMessage());
}
syncAiModelSelectorFromNative();
updateSendButton();
if (aiChatAttach && aiFileInput) {
aiChatAttach.addEventListener('click', () => {
aiFileInput.click();
});
aiFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) handleFileAttachment(file);
});
}
if (aiChatClear) {
aiChatClear.addEventListener('click', async () => {
if (await storeConfirm('Start a new chat?')) startNewChat();
});
}
const handleAiSettingsClick = async () => {
const isSetupVisible = aiHelpSetup && aiHelpSetup.style.display === 'flex';
if (isSetupVisible && hasConfiguredProvider()) {
if (aiHelpSetup) aiHelpSetup.style.display = 'none';
if (aiHelpChat) aiHelpChat.style.display = 'flex';
await populateModelSelector();
await loadChatHistory();
} else {
if (aiHelpChat) aiHelpChat.style.display = 'none';
if (aiHelpSetup) aiHelpSetup.style.display = 'flex';
if (aiApiKeyForm) aiApiKeyForm.style.display = 'none';
if (aiProviderGrid) aiProviderGrid.style.display = 'grid';
await updateProviderStatuses();
}
};
if (aiHelpSettingsBtn) {
aiHelpSettingsBtn.addEventListener('click', handleAiSettingsClick);
}
if (aiSetupSettingsBtn) {
aiSetupSettingsBtn.addEventListener('click', handleAiSettingsClick);
}
const aiNewChatBtn = document.getElementById('aiNewChatBtn');
if (aiNewChatBtn) {
aiNewChatBtn.addEventListener('click', startNewChat);
}
// Ensure delegated click handling for the chats list (switch/delete) is wired
// up at startup, independent of the first render path.
bindAiChatsListDelegation();
const aiSidebarToggle = document.getElementById('aiSidebarToggle');
if (aiSidebarToggle) {
aiSidebarToggle.addEventListener('click', () => {
const sidebar = document.getElementById('aiChatSidebar');
if (sidebar) {
sidebar.classList.toggle('collapsed');
}
});
}
const aiSidebarExpand = document.getElementById('aiSidebarExpand');
if (aiSidebarExpand) {
aiSidebarExpand.addEventListener('click', () => {
const sidebar = document.getElementById('aiChatSidebar');
if (sidebar) {
sidebar.classList.remove('collapsed');
}
});
}
// aiHelpBtn and dockAiHelp are intentionally NOT bound here: both carry
// data-action="open-ai-help" and the registry handler (with its
// disabled/perms gate) already covers them — each extra unconditional
// listener made the AI-help button open the modal once per binding.
if (aiUndoBtn) {
aiUndoBtn.addEventListener('click', undoLastFileChange);
}
if (aiUndoDismiss) {
aiUndoDismiss.addEventListener('click', hideUndoToast);
}
if (aiAcceptAllChanges) {
aiAcceptAllChanges.addEventListener('click', acceptAllFileChanges);
}
if (aiUndoAllChanges) {
aiUndoAllChanges.addEventListener('click', undoAllFileChanges);
}
if (aiFileChangesToggle && aiFileChangesBar) {
aiFileChangesToggle.addEventListener('click', () => {
aiFileChangesBar.classList.toggle('collapsed');
});
}
if (aiConfirmAllow) {
aiConfirmAllow.addEventListener('click', handleConfirmAllow);
}
if (aiConfirmDeny) {
aiConfirmDeny.addEventListener('click', handleConfirmDeny);
}
window.openAiHelpModal = openAiHelpModal;
window.closeAiHelpModal = closeAiHelpModal;
const reinstallController = window.ADPanelReinstall.createReinstallController({
document, serverName: bot, hasPerm, fetchWithServerActionToken, showModalElement, animateClose,
});
})();