Refactor agent.user.js to enhance debug functionality and server management. Introduce new debug state handling, update logging mechanisms, and improve popup menu commands for better user interaction. Ensure consistent formatting and code readability throughout the script.

This commit is contained in:
thuanle
2025-08-02 03:08:17 +07:00
parent 02a8f030b6
commit eb01157804

View File

@@ -27,13 +27,13 @@ if (window.top !== window) {
GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.'); GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
(async () => { (async () => {
'use strict'; 'use strict';
// ====== CONFIGURATION ====== // ====== CONFIGURATION ======
const CONFIG = { const CONFIG = {
heartbeat_interval: 10000, heartbeat_interval: 10000,
task_poll_interval: 10000, task_poll_interval: 10000,
is_debug: true,
servers: { servers: {
local: { label: '🏠 Local', url: 'http://localhost:3000' }, local: { label: '🏠 Local', url: 'http://localhost:3000' },
prod: { label: '🌐 Prod', url: 'https://baf.thuanle.me' }, prod: { label: '🌐 Prod', url: 'https://baf.thuanle.me' },
@@ -47,6 +47,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
// Server configuration // Server configuration
server_type: 'prod', server_type: 'prod',
server_url: null, server_url: null,
server_last_seen: null,
// Page state // Page state
current_page: null, current_page: null,
@@ -67,7 +68,12 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
// Popup state // Popup state
popup_position: 4, // 1: top-left, 2: top-right, 3: bottom-left, 4: bottom-right popup_position: 4, // 1: top-left, 2: top-right, 3: bottom-left, 4: bottom-right
popup_visible: true popup_visible: true,
// Debug state
is_debug: true
}; };
this.observers = new Map(); this.observers = new Map();
@@ -85,6 +91,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
this.data.bot_status = await STORAGE.getBotStatus(); this.data.bot_status = await STORAGE.getBotStatus();
this.data.popup_position = await STORAGE.getPopupPosition(); this.data.popup_position = await STORAGE.getPopupPosition();
this.data.popup_visible = await STORAGE.getPopupVisible(); this.data.popup_visible = await STORAGE.getPopupVisible();
this.data.is_debug = await STORAGE.getDebug();
// Detect current page and login state // Detect current page and login state
this.data.current_page = BINANCE.detectPage(); this.data.current_page = BINANCE.detectPage();
@@ -152,6 +159,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
key_navigation_state: 'baf-navigation-state', key_navigation_state: 'baf-navigation-state',
key_popup_position: 'baf-popup-position', key_popup_position: 'baf-popup-position',
key_popup_visible: 'baf-popup-visible', key_popup_visible: 'baf-popup-visible',
key_debug: 'baf-debug',
getToken: () => GM_getValue(STORAGE.key_token, ''), getToken: () => GM_getValue(STORAGE.key_token, ''),
setToken: token => GM_setValue(STORAGE.key_token, String(token || '').trim().replace(/^Bearer\s+/i, '')), setToken: token => GM_setValue(STORAGE.key_token, String(token || '').trim().replace(/^Bearer\s+/i, '')),
@@ -182,12 +190,15 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
setPopupPosition: (position) => GM_setValue(STORAGE.key_popup_position, position), setPopupPosition: (position) => GM_setValue(STORAGE.key_popup_position, position),
getPopupVisible: () => GM_getValue(STORAGE.key_popup_visible, true), getPopupVisible: () => GM_getValue(STORAGE.key_popup_visible, true),
setPopupVisible: (visible) => GM_setValue(STORAGE.key_popup_visible, visible) setPopupVisible: (visible) => GM_setValue(STORAGE.key_popup_visible, visible),
getDebug: () => GM_getValue(STORAGE.key_debug, true),
setDebug: (debug) => GM_setValue(STORAGE.key_debug, debug)
}; };
// ====== UTILITY MODULE ====== // ====== UTILITY MODULE ======
const TL = { const TL = {
debug: (tag, msg, ...args) => CONFIG.is_debug && GM_log(`[TL] [${tag}]\n${msg}`, ...args), debug: (tag, msg, ...args) => APP_STATE.getData().is_debug && GM_log(`[TL] [${tag}]\n${msg}`, ...args),
log: (tag, msg, ...args) => GM_log(`[TL] [${tag}]\n${msg}`, ...args), log: (tag, msg, ...args) => GM_log(`[TL] [${tag}]\n${msg}`, ...args),
warn: (tag, msg, ...args) => GM_log(`[TL] [WARN] [${tag}] ⚠️\n${msg}`, ...args), warn: (tag, msg, ...args) => GM_log(`[TL] [WARN] [${tag}] ⚠️\n${msg}`, ...args),
error: (tag, msg, ...args) => GM_log(`[TL] [ERROR] [${tag}] ❌\n${msg}`, ...args), error: (tag, msg, ...args) => GM_log(`[TL] [ERROR] [${tag}] ❌\n${msg}`, ...args),
@@ -375,7 +386,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
const BINANCE = { const BINANCE = {
detectPage: () => { detectPage: () => {
if (!SafetyGuard.check('detectPage')) return BINANCE_PAGES.IGNORE; if (!SafetyGuard.check('detectPage')) return BINANCE_PAGES.IGNORE;
const { hostname, pathname } = window.location; const { hostname, pathname } = window.location;
if (window.top !== window) { if (window.top !== window) {
TL.debug('BINANCE-PAGE-DETECT', 'Call from iframe ❌'); TL.debug('BINANCE-PAGE-DETECT', 'Call from iframe ❌');
@@ -394,7 +405,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
// Check patterns in order (most specific first) // Check patterns in order (most specific first)
for (const pattern of hostConfig.patterns) { for (const pattern of hostConfig.patterns) {
if (pathname.includes(pattern.includes)) { if (pathname.includes(pattern.includes)) {
TL.debug('PAGE_DETECT', msg + TL.debug('PAGE_DETECT', msg +
`Matched pattern: ${pattern.includes} -> ${pattern.page}`); `Matched pattern: ${pattern.includes} -> ${pattern.page}`);
return pattern.page; return pattern.page;
@@ -417,25 +428,25 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
detectLoginState: () => { detectLoginState: () => {
if (!SafetyGuard.check('detectLoginState')) return null; if (!SafetyGuard.check('detectLoginState')) return null;
if (window.top !== window) { if (window.top !== window) {
TL.debug('BINANCE-LOGIN', 'In iframe - cannot determine login state'); TL.debug('BINANCE-LOGIN', 'In iframe - cannot determine login state');
return null; return null;
} }
if (BINANCE.isOnLoginPage()) { if (BINANCE.isOnLoginPage()) {
return false; return false;
} }
// otherwise // otherwise
// if (BINANCE.isOnAlphaSwapPage()) { // if (BINANCE.isOnAlphaSwapPage()) {
// Method 1: Check for login/register buttons (indicates NOT logged in) // Method 1: Check for login/register buttons (indicates NOT logged in)
const loginBtn = document.querySelector('#toLoginPage, [data-testid="login-button"], .login-btn'); const loginBtn = document.querySelector('#toLoginPage, [data-testid="login-button"], .login-btn');
const regBtn = document.querySelector('#toRegisterPage, [data-testid="register-button"], .register-btn'); const regBtn = document.querySelector('#toRegisterPage, [data-testid="register-button"], .register-btn');
let msg = `loginBtn: ${TL.dom.isVisible?.(loginBtn)} regBtn: ${TL.dom.isVisible?.(regBtn)}\n`; let msg = `loginBtn: ${TL.dom.isVisible?.(loginBtn)} regBtn: ${TL.dom.isVisible?.(regBtn)}\n`;
// If login/register buttons are visible, definitely not logged in // If login/register buttons are visible, definitely not logged in
if (TL.dom.isVisible?.(loginBtn) || TL.dom.isVisible?.(regBtn)) { if (TL.dom.isVisible?.(loginBtn) || TL.dom.isVisible?.(regBtn)) {
TL.debug('BINANCE-LOGIN', msg + 'Login/Register buttons visible -> NOT logged in'); TL.debug('BINANCE-LOGIN', msg + 'Login/Register buttons visible -> NOT logged in');
@@ -450,9 +461,9 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
const isDashboardVisible = dashboardLink && TL.dom.isVisible?.(dashboardLink); const isDashboardVisible = dashboardLink && TL.dom.isVisible?.(dashboardLink);
const isAccountIconVisible = !!accountIcon; const isAccountIconVisible = !!accountIcon;
const isWalletVisible = walletBtn && TL.dom.isVisible?.(walletBtn); const isWalletVisible = walletBtn && TL.dom.isVisible?.(walletBtn);
// msg += `dashboard: ${dashboardLink}, accountIcon: ${accountIcon}, walletBtn: ${walletBtn}\n`; // msg += `dashboard: ${dashboardLink}, accountIcon: ${accountIcon}, walletBtn: ${walletBtn}\n`;
msg += `Visible: dashboard: ${isDashboardVisible? '✓' : '✗'}, accountIcon: ${isAccountIconVisible? '✓' : '✗'}, walletBtn: ${isWalletVisible? '✓' : '✗'}\n`; msg += `Visible: dashboard: ${isDashboardVisible ? '✓' : '✗'}, accountIcon: ${isAccountIconVisible ? '✓' : '✗'}, walletBtn: ${isWalletVisible ? '✓' : '✗'}\n`;
// If we see user account elements, likely logged in // If we see user account elements, likely logged in
if (isDashboardVisible && isAccountIconVisible && isWalletVisible) { if (isDashboardVisible && isAccountIconVisible && isWalletVisible) {
@@ -897,7 +908,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
// Execute current step // Execute current step
async executeCurrentStep() { async executeCurrentStep() {
if (!SafetyGuard.check('executeCurrentStep')) return; if (!SafetyGuard.check('executeCurrentStep')) return;
const data = APP_STATE.getData(); const data = APP_STATE.getData();
if (!data.current_task || !this.context) { if (!data.current_task || !this.context) {
TL.debug('STEP', 'No current task or context available'); TL.debug('STEP', 'No current task or context available');
@@ -1196,7 +1207,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
}, },
async checkForNewTasks() { async checkForNewTasks() {
if (!SafetyGuard.check('checkForNewTasks')) return; if (!SafetyGuard.check('checkForNewTasks')) return;
try { try {
const data = APP_STATE.getData(); const data = APP_STATE.getData();
if (data.bot_status !== BOT_STATUS.WAITING && data.bot_status !== BOT_STATUS.RUNNING) { if (data.bot_status !== BOT_STATUS.WAITING && data.bot_status !== BOT_STATUS.RUNNING) {
@@ -1346,7 +1357,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
const data = APP_STATE.getData(); const data = APP_STATE.getData();
const curSrv = data.server_url; const curSrv = data.server_url;
GM_registerMenuCommand(`Server: ${curSrv.label} (${curSrv.url})`, async () => { GM_registerMenuCommand(`🌐 Server: ${curSrv.label} (${curSrv.url})`, async () => {
try { try {
const next = (data.server_type === 'local') ? 'prod' : 'local'; const next = (data.server_type === 'local') ? 'prod' : 'local';
await APP_STATE.update({ server_type: next }); await APP_STATE.update({ server_type: next });
@@ -1361,7 +1372,7 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
} }
}); });
GM_registerMenuCommand('Token', async () => { GM_registerMenuCommand('🔑 Token', async () => {
try { try {
const curToken = await STORAGE.getToken(); const curToken = await STORAGE.getToken();
const input = prompt('Bearer token:', curToken || ''); const input = prompt('Bearer token:', curToken || '');
@@ -1382,96 +1393,16 @@ GM_log('[TL] 🏁 Welcome to Binance Alpha Farm Agent.');
} }
}); });
// Bot Status Menu với icon và tên task
const getStatusDisplay = () => {
const data = APP_STATE.getData();
const taskName = data.current_task?.type || '';
switch (data.bot_status) {
case BOT_STATUS.WAITING:
return `💤 Waiting for new task`;
case BOT_STATUS.RUNNING:
return `▶️ Running: ${taskName}`;
case BOT_STATUS.PAUSED:
return `⏸️ Paused: ${taskName}`;
case BOT_STATUS.STOPPED:
return `⏹️ Stopped`;
default:
return `❓ Unknown status`;
}
};
// Popup toggle menu // Popup toggle menu
const popupData = APP_STATE.getData(); GM_registerMenuCommand("👁️ Toggle Popup", () => {
const popupStatus = popupData.popup_visible ? '👁️ Hide Popup' : '👁️ Show Popup';
GM_registerMenuCommand(popupStatus, () => {
UI.statusOverlay.toggle(); UI.statusOverlay.toggle();
}); });
// Debug tools
GM_registerMenuCommand('🔍 Current Status', () => {
const detectedPage = APP_STATE.getData().current_page;
const isLoggedIn = APP_STATE.getData().is_logged_in;
const currentUrl = window.location.href;
const status = `Page: ${detectedPage}\nLogin: ${isLoggedIn ? 'Yes' : 'No'}\nURL: ${currentUrl}`;
console.log('Current Status:', status);
alert(status);
});
GM_registerMenuCommand('🔐 Debug Login State', () => {
const isInIframe = window.top !== window;
const loginState = BINANCE.detectLoginState();
// Check all possible login indicators
const loginIndicators = {
'In iframe': isInIframe,
'Login button visible': TL.dom.isVisible?.(document.querySelector('#toLoginPage')),
'Register button visible': TL.dom.isVisible?.(document.querySelector('#toRegisterPage')),
'Account icon found': !!document.querySelector('.header-account-icon'),
'Deposit button found': !!document.querySelector('.deposit-btn'),
'Wallet button found': !!document.querySelector('#ba-wallet'),
'User menu found': !!document.querySelector('.header-dropdown-menu'),
'Dashboard link found': !!document.querySelector('a[href*="/my/dashboard"]'),
'Detected login state': loginState
};
const debugInfo = Object.entries(loginIndicators)
.map(([key, value]) => `${key}: ${value}`)
.join('\n');
console.log('=== LOGIN STATE DEBUG ===');
console.log(debugInfo);
alert(`Login State Debug:\n\n${debugInfo}`);
});
GM_registerMenuCommand('🔍 Debug URL Sources', () => {
const mainUrl = window.location.href;
const frames = Array.from(document.querySelectorAll('iframe')).map(frame => frame.src);
const popups = window.opener ? window.opener.location.href : null;
const debugInfo = `
Main Window: ${mainUrl}
Frames: ${frames.length > 0 ? frames.join('\n') : 'None'}
Popup Opener: ${popups || 'None'}
`;
console.log('=== URL SOURCES DEBUG ===');
console.log(debugInfo);
alert(`URL Sources Debug:\n\n${debugInfo}`);
});
} }
// ====== HEARTBEAT ====== // ====== HEARTBEAT ======
async function heartbeat_report() { async function heartbeat_report() {
if (!SafetyGuard.check('heartbeat_report')) return null; if (!SafetyGuard.check('heartbeat_report')) return null;
try { try {
const data = APP_STATE.getData(); const data = APP_STATE.getData();
const status = { const status = {
@@ -1484,7 +1415,11 @@ Popup Opener: ${popups || 'None'}
}; };
// TL.debug(`HEARTBEAT`, `${JSON.stringify(status, null, 2)}`); // TL.debug(`HEARTBEAT`, `${JSON.stringify(status, null, 2)}`);
await BAF.ping(status); const res = await BAF.ping(status);
if (res.ok) {
APP_STATE.update({ server_last_seen: new Date() });
}
return status; return status;
} catch (e) { } catch (e) {
TL.error('HEARTBEAT', e.message); TL.error('HEARTBEAT', e.message);
@@ -1593,7 +1528,6 @@ Popup Opener: ${popups || 'None'}
// Update overlay content // Update overlay content
updateContent: () => { updateContent: () => {
if (!UI.statusOverlay.element) return;
const data = APP_STATE.getData(); const data = APP_STATE.getData();
const taskName = data.current_task?.type || 'No task'; const taskName = data.current_task?.type || 'No task';
@@ -1620,27 +1554,36 @@ Popup Opener: ${popups || 'None'}
// Get server info // Get server info
const serverLabel = data.server_url?.label || 'Unknown'; const serverLabel = data.server_url?.label || 'Unknown';
// data.server_last_seen < 1min == connected
const serverConnected = data.server_last_seen && new Date() - data.server_last_seen < 60000 ? '🟢' : '🔴';
// Get page info // Get page info
const pageDisplay = data.current_page || 'unknown'; const pageDisplay = data.current_page || 'unknown';
// Get login status // Get login status
const loginStatus = data.is_logged_in ? '✅ Logged in' : '❌ Not logged in'; const loginStatus = data.is_logged_in ? '✅' : '❌';
// Get SafetyGuard status // Get SafetyGuard status
const safetyStatus = SafetyGuard.getStatus(); const safetyStatus = SafetyGuard.getStatus();
const safetyDisplay = safetyStatus.enabled ? '🛡️ Safe' : '🚨 Blocked';
// Build content // Build content
const content = ` const content = `
<div style="margin-bottom: 8px;"> <div style="margin-bottom: 8px;"><strong>BAF Agent Status</strong></div>
<strong>BAF Agent Status</strong>
<div style="margin-bottom: 4px;">
<span id="safety-toggle-btn" style="color: ${safetyStatus.enabled ? '#28a745' : '#dc3545'}; cursor: pointer; padding: 2px 4px; border-radius: 3px; border: 1px solid ${safetyStatus.enabled ? '#28a745' : '#dc3545'}; background: ${safetyStatus.enabled ? 'rgba(40, 167, 69, 0.1)' : 'rgba(220, 53, 69, 0.1)'}; transition: all 0.2s ease;" title="Click to toggle safety status">🛟 Safety: ${safetyStatus.enabled ? '🛡️ Safe' : '🚨 Blocked'}</span>
</div> </div>
<div style="margin-bottom: 4px;"> <div style="margin-bottom: 4px;">
<span style="color: #007bff;">${statusDisplay}</span> <span id="debug-toggle-btn" style="color: ${data.is_debug ? '#17a2b8' : '#6c757d'}; cursor: pointer; padding: 2px 4px; border-radius: 3px; border: 1px solid ${data.is_debug ? '#17a2b8' : '#6c757d'}; background: ${data.is_debug ? 'rgba(23, 162, 184, 0.1)' : 'rgba(108, 117, 125, 0.1)'}; transition: all 0.2s ease;" title="Click to toggle debug mode">🐛 Debug: ${data.is_debug ? '✔️ ON' : '❌ OFF'}</span>
</div> </div>
<div style="margin-bottom: 4px;"> <div style="margin-bottom: 4px;">
<span style="color: #28a745;">${safetyDisplay}</span> <span style="color: #007bff;">Bot Status: ${statusDisplay}</span>
</div>
<div style="margin-bottom: 4px;">
<span style="color: #e83e8c;">🌐 Server: ${serverLabel} ${serverConnected}</span>
</div>
<div style="margin-bottom: 4px;">
<span style="color: #fd7e14;">👤 Login:${loginStatus}</span>
</div> </div>
<div style="margin-bottom: 4px;"> <div style="margin-bottom: 4px;">
<span style="color: #ffc107;">Task: ${taskName}</span> <span style="color: #ffc107;">Task: ${taskName}</span>
@@ -1651,24 +1594,46 @@ Popup Opener: ${popups || 'None'}
<div style="margin-bottom: 4px;"> <div style="margin-bottom: 4px;">
<span style="color: #6f42c1;">Page: ${pageDisplay}</span> <span style="color: #6f42c1;">Page: ${pageDisplay}</span>
</div> </div>
<div style="margin-bottom: 4px;">
<span style="color: #fd7e14;">${loginStatus}</span>
</div>
<div style="margin-bottom: 4px;">
<span style="color: #e83e8c;">Server: ${serverLabel}</span>
</div>
${data.error_message ? `<div style="color: #dc3545; margin-top: 4px;">Error: ${data.error_message}</div>` : ''} ${data.error_message ? `<div style="color: #dc3545; margin-top: 4px;">Error: ${data.error_message}</div>` : ''}
`; `;
// Update content (excluding position button) // Update content (excluding position button)
const contentDiv = UI.statusOverlay.element.querySelector('.baf-content') || const contentDiv = UI.statusOverlay.element.querySelector('.baf-content') || document.createElement('div');
document.createElement('div');
contentDiv.className = 'baf-content'; contentDiv.className = 'baf-content';
contentDiv.innerHTML = content; contentDiv.innerHTML = content;
if (!UI.statusOverlay.element.querySelector('.baf-content')) { if (!UI.statusOverlay.element.querySelector('.baf-content')) {
UI.statusOverlay.element.appendChild(contentDiv); UI.statusOverlay.element.appendChild(contentDiv);
} }
// Add event listener for safety toggle button
const toggleBtn = contentDiv.querySelector('#safety-toggle-btn');
if (toggleBtn) {
toggleBtn.onclick = () => {
const currentStatus = SafetyGuard.getStatus();
if (currentStatus.enabled) {
SafetyGuard.disable();
} else {
SafetyGuard.enable();
}
// Update the content to reflect the change
UI.statusOverlay.updateContent();
};
}
// Add event listener for debug toggle button
const debugToggleBtn = contentDiv.querySelector('#debug-toggle-btn');
if (debugToggleBtn) {
debugToggleBtn.onclick = () => {
const currentData = APP_STATE.getData();
const newDebugState = !currentData.is_debug;
APP_STATE.update({ is_debug: newDebugState });
STORAGE.setDebug(newDebugState);
// Update the content to reflect the change
UI.statusOverlay.updateContent();
};
}
}, },
// Show status overlay // Show status overlay
@@ -1816,7 +1781,7 @@ Popup Opener: ${popups || 'None'}
// ====== INITIALIZATION ====== // ====== INITIALIZATION ======
const APP_STATE = new AppState(); const APP_STATE = new AppState();
async function initialize() { async function initialize() {
// Initialize state // Initialize state
await APP_STATE.initialize(); await APP_STATE.initialize();