/**
* Chahuadev Hybrid Diagnostic Dashboard - Terminal + GUI
*/
class DiagnosticDashboard {
constructor() {
this.selectedLog = null;
this.currentTab = 'details';
this.maxLogs = 1000;
this.init();
}
async init() {
console.log(' เริ่มต้น Hybrid Diagnostic Dashboard...');
// ตั้งค่า global reference สำหรับการเรียกใช้จาก HTML
window.diagnosticDashboard = this;
// ตรวจสอบ DEV MODE
try {
// เรียก API จาก Backend เพื่อตรวจสอบโหมดการทำงาน
const runMode = await window.electronAPI.getRunMode();
if (runMode && runMode.isDevMode) {
console.log(' Running in Developer Mode');
document.body.classList.add('dev-mode');
} else {
console.log(' Running in User Mode');
document.body.classList.remove('dev-mode');
}
} catch (error) {
console.warn(' ไม่สามารถตรวจสอบโหมดการทำงานได้', error);
}
this.setupTerminal();
this.setupEventListeners();
this.startRealTimeUpdates();
console.log(' Hybrid Diagnostic Dashboard พร้อมใช้งาน');
}
// [เวอร์ชันใหม่] ตั้งค่า Log Viewer ของเราเอง
setupTerminal() {
// เราจะเรียกใช้ฟังก์ชันนี้ใน init() เหมือนเดิม
// แต่ตอนนี้มันแค่เตรียมพร้อม ไม่ได้สร้าง Terminal ที่ซับซ้อน
this.logViewer = document.getElementById('log-viewer');
if (this.logViewer) {
this.logViewer.innerHTML = ''; // ล้าง Log เก่าตอนเริ่มต้น
this.writeLog({
message: '===== Chahuadev Diagnostic Log (Raw HTML) =====',
type: 'debug'
});
this.writeLog({
message: 'Real-time logs will appear here...',
type: 'info'
});
} else {
console.error('Log viewer container not found!');
}
}
// ไม่ต้องมี resizeTerminal() อีกต่อไป เพราะ CSS จัดการให้แล้ว!
/**
* Throttle function เพื่อจำกัดการเรียกฟังก์ชัน
*/
throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
setupEventListeners() {
// Tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
this.setActiveTab(e.target.dataset.tab);
});
});
// Project Inspector buttons
document.getElementById('scanSelfBtn')?.addEventListener('click', async () => {
await this.handleProjectScan('self');
});
document.getElementById('scanPluginsBtn')?.addEventListener('click', async () => {
await this.handleProjectScan('plugins');
});
document.getElementById('exportIssuesBtn')?.addEventListener('click', async () => {
await this.handleExportIssues();
});
// E2E Testing button
document.getElementById('runE2eTestsBtn')?.addEventListener('click', async () => {
this.writeln('\x1b[1;36m กำลังเริ่มการทดสอบ E2E ทั้งระบบ...\x1b[0m');
try {
const result = await window.electronAPI.diagnostics.runE2eTests();
if (result.success) {
this.writeln('\x1b[1;32m การทดสอบ E2E เสร็จสิ้น\x1b[0m');
if (result.message) {
this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
}
} else {
this.writeln(`\x1b[1;31m การทดสอบ E2E ล้มเหลว: ${result.error}\x1b[0m`);
}
} catch (error) {
this.writeln(`\x1b[1;31m ไม่สามารถเริ่มการทดสอบได้: ${error.message}\x1b[0m`);
}
});
// Open Test Report button
document.getElementById('openTestReportBtn')?.addEventListener('click', async () => {
this.writeln('\x1b[1;33m กำลังเปิดรายงานผลการทดสอบ...\x1b[0m');
try {
const result = await window.electronAPI.diagnostics.openTestReport();
if (result.success) {
this.writeln('\x1b[1;32m เปิดรายงานผลการทดสอบแล้ว\x1b[0m');
if (result.message) {
this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
}
} else {
this.writeln(`\x1b[1;31m ไม่สามารถเปิดรายงานได้: ${result.error}\x1b[0m`);
}
} catch (error) {
this.writeln(`\x1b[1;31m เกิดข้อผิดพลาด: ${error.message}\x1b[0m`);
}
});
}
/**
* จัดการการสแกนโปรเจกต์
* @param {'self' | 'plugins'} target - เป้าหมายที่จะสแกน
*/
async handleProjectScan(target) {
try {
let projectPath = null; // เริ่มต้นเป็น null
let targetName = '';
// ปรับปรุงตรรกะการเลือก Path
if (target === 'self') {
targetName = 'โปรเจกต์หลัก (Framework)';
// ขอ Path ของโปรแกรมปัจจุบันจาก Backend
projectPath = await window.electronAPI.system.getCwd();
} else if (target === 'plugins') {
targetName = 'ปลั๊กอินทั้งหมด';
// ไม่ต้องส่ง Path! เพื่อให้ main process ใช้ default path ของ plugins
projectPath = undefined; // ให้ Backend เลือก plugins directory เอง
} else {
this.writeln(`\x1b[1;31m ข้อผิดพลาด: ไม่รู้จักเป้าหมายการสแกน '${target}'\x1b[0m`);
return;
}
this.writeln(`\x1b[1;33m กำลังเริ่มวิเคราะห์: ${targetName}...\x1b[0m`);
if (projectPath) {
this.writeln(`\x1b[1;36m Path: ${projectPath}\x1b[0m`);
} else {
this.writeln(`\x1b[1;36m ใช้ Path เริ่มต้นของปลั๊กอิน\x1b[0m`);
}
// ปิดการใช้งานปุ่มขณะสแกน
const scanSelfBtn = document.getElementById('scanSelfBtn');
const scanPluginsBtn = document.getElementById('scanPluginsBtn');
const exportBtn = document.getElementById('exportIssuesBtn');
if (scanSelfBtn) scanSelfBtn.disabled = true;
if (scanPluginsBtn) scanPluginsBtn.disabled = true;
// ซ่อนปุ่ม export ขณะสแกน
if (exportBtn) {
exportBtn.style.display = 'none';
exportBtn.disabled = true;
}
if (window.electronAPI && window.electronAPI.project) {
// เรียก API โดยส่ง path ที่อาจจะเป็น undefined สำหรับ plugins
const result = await window.electronAPI.project.analyze(projectPath);
if (result.success) {
const scanInfo = result.scanTarget ? ` (${result.scanTarget})` : '';
this.writeln(`\x1b[1;32m วิเคราะห์สำเร็จ${scanInfo}: พบ ${result.analysis.totalIssues} ปัญหาใน ${result.analysis.totalFiles} ไฟล์\x1b[0m`);
// แสดงรายละเอียดเพิ่มเติม
if (result.analysis.totalFiles === 0) {
this.writeln(`\x1b[1;33m ไม่พบไฟล์ในโฟลเดอร์นี้ หรือไฟล์ทั้งหมดถูกคัดกรองออกโดย exclusion rules\x1b[0m`);
}
// แสดงผลลัพธ์ใน Inspector tab
this.displayAnalysisResults(result.analysis);
} else {
this.writeln(`\x1b[1;31m วิเคราะห์ล้มเหลว: ${result.error}\x1b[0m`);
// แสดงปุ่ม export แม้ว่าจะล้มเหลว เผื่อมีข้อมูลบางส่วน
if (exportBtn) {
exportBtn.style.display = 'inline-block';
exportBtn.disabled = false;
}
}
} else {
this.writeln('\x1b[1;31m ข้อผิดพลาด: ไม่พบ Project Inspector API\x1b[0m');
}
} catch (error) {
this.writeln(`\x1b[1;31m ข้อผิดพลาดในการสแกน: ${error.message}\x1b[0m`);
} finally {
// คืนสถานะปุ่ม
const scanSelfBtn = document.getElementById('scanSelfBtn');
const scanPluginsBtn = document.getElementById('scanPluginsBtn');
if (scanSelfBtn) scanSelfBtn.disabled = false;
if (scanPluginsBtn) scanPluginsBtn.disabled = false;
}
}
/**
* แสดงผลลัพธ์การวิเคราะห์
*/
displayAnalysisResults(analysis) {
// อัปเดตสถิติ
document.getElementById('totalFiles').textContent = analysis.totalFiles || 0;
document.getElementById('totalIssues').textContent = analysis.totalIssues || 0;
document.getElementById('totalErrors').textContent = analysis.stats?.syntaxErrors || 0;
document.getElementById('totalWarnings').textContent =
(analysis.stats?.missingFiles || 0) +
(analysis.stats?.unusedFiles || 0) +
(analysis.stats?.circularDependencies || 0);
// แสดงส่วนสถิติและฟิลเตอร์
document.getElementById('inspectorStats').style.display = 'block';
document.getElementById('inspectorFilters').style.display = 'block';
// แสดงรายการปัญหา
this.displayIssuesList(analysis.issues || []);
// เก็บข้อมูลสำหรับการ export
this.currentAnalysis = analysis;
// แสดงปุ่ม Export JSON หลังจากมีผลลัพธ์ (ไม่ว่าจะพบปัญหาหรือไม่)
const exportBtn = document.getElementById('exportIssuesBtn');
if (exportBtn) {
exportBtn.style.display = 'inline-block';
exportBtn.disabled = false;
// แจ้งเตือนเมื่อพบปัญหา
if (analysis.issues && analysis.issues.length > 0) {
this.writeln('\x1b[1;36m คลิกปุ่ม "ส่งออก JSON" เพื่อบันทึกผลการวิเคราะห์\x1b[0m');
} else {
this.writeln('\x1b[1;36m ผลการวิเคราะห์พร้อมส่งออก (ไม่พบปัญหา)\x1b[0m');
}
}
// แสดง notification แทนการเปลี่ยนแท็บอัตโนมัติ
this.writeln('\x1b[1;33m ผลการวิเคราะห์พร้อมแล้ว! ไปดูในแท็บ "Inspector" ด้านบน\x1b[0m');
}
/**
* แสดงรายการปัญหา
*/
displayIssuesList(issues) {
const resultsContainer = document.getElementById('inspectorResults');
if (!issues || issues.length === 0) {
resultsContainer.innerHTML = `
ไม่พบปัญหา
โปรเจกต์ของคุณไม่มีปัญหาที่ตรวจพบ
`;
return;
}
let html = '';
issues.forEach((issue, index) => {
const severityClass = issue.severity === 'error' ? 'stat-error' : 'stat-warning';
const severityIcon = issue.severity === 'error' ? 'fas fa-times-circle' : 'fas fa-exclamation-triangle';
const severityText = issue.severity === 'error' ? 'ข้อผิดพลาด' : 'คำเตือน';
const codeSnippetId = `code-snippet-${index}`;
html += `
${issue.type}
${issue.file}:${issue.line}:${issue.column}
${severityText.toUpperCase()}
${issue.message}
${issue.codeSnippet ? `
บริบทของโค้ด
${this.escapeHtml(issue.codeSnippet)}
` : ''}
${issue.suggestion ? `
${issue.suggestion}
` : ''}
`;
});
html += '
';
resultsContainer.innerHTML = html;
// เพิ่ม syntax highlighting
this.applySyntaxHighlighting();
// เพิ่ม filter functionality
this.setupIssueFilters(issues);
}
/**
* หลีกเลี่ยงการแสดง HTML tags ในโค้ด
*/
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* ใช้ syntax highlighting กับ code snippets
*/
applySyntaxHighlighting() {
const codeBlocks = document.querySelectorAll('.code-snippet code');
codeBlocks.forEach(block => {
this.highlightJavaScript(block);
});
}
/**
* Syntax highlighting สำหรับ JavaScript
*/
highlightJavaScript(codeElement) {
let code = codeElement.textContent;
// Keywords
code = code.replace(/\b(const|let|var|function|class|if|else|for|while|return|import|export|from|require|try|catch|throw|async|await|new|this|super|extends|static|null|undefined|true|false)\b/g,
'$1');
// Strings
code = code.replace(/(["'`])((?:\\.|(?!\1)[^\\])*?)\1/g,
'$1$2$1');
// Numbers
code = code.replace(/\b(\d+(?:\.\d+)?)\b/g,
'$1');
// Comments
code = code.replace(/\/\/(.*$)/gm,
'//$1');
code = code.replace(/\/\*([\s\S]*?)\*\//g,
'/*$1*/');
// Function calls
code = code.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,
'$1(');
// Problem line highlight (line starting with >)
code = code.replace(/^(>\s*\d+\s*\|)(.*$)/gm,
'$1$2');
codeElement.innerHTML = code;
}
/**
* คัดลอกโค้ดไปยังคลิปบอร์ด
*/
copyCodeSnippet(snippetId) {
const element = document.getElementById(snippetId);
if (element) {
const text = element.textContent;
navigator.clipboard.writeText(text).then(() => {
// แสดงการแจ้งเตือนสั้นๆ
const copyBtn = element.parentElement.querySelector('.copy-code-btn');
const originalText = copyBtn.innerHTML;
copyBtn.innerHTML = ' คัดลอกแล้ว!';
copyBtn.style.color = '#10b981';
setTimeout(() => {
copyBtn.innerHTML = originalText;
copyBtn.style.color = '#9ca3af';
}, 2000);
}).catch(err => {
console.error('ไม่สามารถคัดลอกได้: ', err);
});
}
}
/**
* ตั้งค่าระบบกรองปัญหา
*/
setupIssueFilters(issues) {
const typeFilter = document.getElementById('typeFilter');
const severityFilter = document.getElementById('severityFilter');
if (typeFilter) {
typeFilter.addEventListener('change', () => {
this.filterIssues(issues);
});
}
if (severityFilter) {
severityFilter.addEventListener('change', () => {
this.filterIssues(issues);
});
}
}
/**
* กรองปัญหาตามเงื่อนไข
*/
filterIssues(allIssues) {
const typeFilter = document.getElementById('typeFilter')?.value || 'all';
const severityFilter = document.getElementById('severityFilter')?.value || 'all';
let filteredIssues = allIssues;
if (typeFilter !== 'all') {
filteredIssues = filteredIssues.filter(issue => issue.type === typeFilter);
}
if (severityFilter !== 'all') {
filteredIssues = filteredIssues.filter(issue => issue.severity === severityFilter);
}
this.displayIssuesList(filteredIssues);
}
/**
* จัดการการ export ปัญหา
*/
async handleExportIssues() {
if (!this.currentAnalysis) {
this.writeln('\x1b[1;33m ไม่มีข้อมูลการวิเคราะห์สำหรับส่งออก\x1b[0m');
return;
}
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `การวิเคราะห์โปรเจกต์-${timestamp}.json`;
// ใช้ Electron dialog API เพื่อให้ผู้ใช้เลือกที่บันทึก
if (window.electronAPI && window.electronAPI.dialog) {
const result = await window.electronAPI.dialog.showSaveDialog({
defaultPath: filename,
filters: [
{ name: 'ไฟล์ JSON', extensions: ['json'] },
{ name: 'ไฟล์ทั้งหมด', extensions: ['*'] }
]
});
if (!result.canceled && result.filePath) {
await window.electronAPI.file.write(result.filePath, JSON.stringify(this.currentAnalysis, null, 2));
this.writeln(`\x1b[1;32m ส่งออกการวิเคราะห์เรียบร้อย: ${result.filePath}\x1b[0m`);
} else {
this.writeln('\x1b[1;33m ยกเลิกการส่งออก\x1b[0m');
}
} else {
// Fallback: สร้างลิงก์ดาวน์โหลด
const dataStr = JSON.stringify(this.currentAnalysis, null, 2);
const dataBlob = new Blob([dataStr], {type:'application/json'});
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
this.writeln(`\x1b[1;32m เริ่มดาวน์โหลดไฟล์: ${filename}\x1b[0m`);
}
} catch (error) {
this.writeln(`\x1b[1;31m ข้อผิดพลาดในการส่งออก: ${error.message}\x1b[0m`);
}
}
setActiveTab(tab) {
this.currentTab = tab;
// อัปเดต tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tab);
});
// อัปเดต tab content
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.toggle('active', content.id === tab + 'Tab');
});
// โหลดข้อมูลเฉพาะ tab
if (tab === 'workflows') {
this.requestWorkflowsUpdate();
}
}
// [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เราควบคุมได้ 100%
writeLog(logData) {
if (!this.logViewer) return;
const timestamp = logData.timestamp ? new Date(logData.timestamp) : new Date();
const time = timestamp.toLocaleTimeString('th-TH', { hour12: false });
// สร้าง Element ใหม่สำหรับแต่ละบรรทัด Log
const logLine = document.createElement('span');
logLine.className = `log-line log-${logData.type || 'info'}`;
// สร้างข้อความ Log
logLine.textContent = `[${time}] ${logData.message}\n`;
// เพิ่มบรรทัดใหม่ลงใน Log Viewer
this.logViewer.appendChild(logLine);
// เลื่อนหน้าจอไปที่บรรทัดล่าสุดเสมอ
this.logViewer.scrollTop = this.logViewer.scrollHeight;
}
// Helper function เพื่อความง่ายในการแทนที่ terminal.writeln()
writeln(message, type = 'info') {
// ลบ ANSI color codes ออกจากข้อความ
const cleanMessage = message.replace(/\x1b\[[0-9;]*m/g, '');
// แปลงสีจาก ANSI codes เป็นประเภท Log
let messageType = type;
if (message.includes('\x1b[1;32m')) messageType = 'success'; // เขียว
else if (message.includes('\x1b[1;31m')) messageType = 'error'; // แดง
else if (message.includes('\x1b[1;33m')) messageType = 'warning'; // เหลือง
else if (message.includes('\x1b[1;36m')) messageType = 'debug'; // ฟ้า
this.writeLog({
message: cleanMessage,
type: messageType,
timestamp: new Date().toISOString()
});
}
// [เวอร์ชันใหม่] อัปเดต Event Listener ให้เรียกใช้ฟังก์ชันใหม่
startRealTimeUpdates() {
if (window.electronAPI && window.electronAPI.onTerminalMessage) {
window.electronAPI.onTerminalMessage((logData) => {
// logData คือ { message, type, timestamp } ที่ส่งมาจาก Backend
// เรียกใช้ฟังก์ชันเขียน Log ใหม่ของเราโดยตรง
this.writeLog(logData);
});
console.log(' Raw HTML Log listener enabled.');
} else {
console.error(' Could not set up real-time log listener.');
}
}
updateRunningWorkflows(workflowsData) {
const container = document.getElementById('runningWorkflows');
if (!container) return;
if (!workflowsData || workflowsData.length === 0) {
container.innerHTML = `
ไม่มีเวิร์กโฟลว์ที่กำลังทำงาน
ใช้คำสั่ง workflows ในเทอร์มินัลเพื่อดูข้อมูลล่าสุด
`;
return;
}
container.innerHTML = '';
workflowsData.forEach(workflow => {
const workflowElement = this.createWorkflowElement(workflow);
container.appendChild(workflowElement);
});
}
createWorkflowElement(workflow) {
const div = document.createElement('div');
div.className = 'workflow-item';
const statusClass = `status-${workflow.status}`;
const progress = workflow.completedNodes || 0;
const total = workflow.totalNodes || 0;
const percentage = total > 0 ? Math.round((progress / total) * 100) : 0;
div.innerHTML = `
${progress}/${total} nodes
${percentage}% complete
`;
return div;
}
updateWorkflowsTab(workflowsData) {
this.updateRunningWorkflows(workflowsData);
}
formatUptime(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`;
} else if (minutes > 0) {
return `${minutes}m ${secs}s`;
} else {
return `${secs}s`;
}
}
async requestWorkflowsUpdate() {
try {
if (window.electronAPI && window.electronAPI.diagnostics) {
const workflows = await window.electronAPI.diagnostics.getWorkflows();
this.updateRunningWorkflows(workflows);
}
} catch (error) {
console.error('ไม่สามารถดึงข้อมูล workflows ได้:', error);
}
}
}
// เริ่มต้น Dashboard เมื่อ DOM พร้อม
document.addEventListener('DOMContentLoaded', () => {
window.diagnosticDashboard = new DiagnosticDashboard();
});
// Export สำหรับใช้ใน console
window.DiagnosticDashboard = DiagnosticDashboard;