chahuadev-framework-en / debugger.js
chahuadev
Update README
857cdcf
/**
* 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 = `
<div class="no-selection">
<i class="fas fa-check-circle" style="color: #10b981;"></i>
<h3>ไม่พบปัญหา</h3>
<p>โปรเจกต์ของคุณไม่มีปัญหาที่ตรวจพบ</p>
</div>
`;
return;
}
let html = '<div class="issues-list">';
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 += `
<div class="issue-item" style="background: #2a2a2a; border-radius: 6px; padding: 12px; margin-bottom: 10px; border-left: 3px solid ${issue.severity === 'error' ? '#ef4444' : '#f59e0b'};">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
<div>
<span class="${severityClass}" style="font-weight: bold;">
<i class="${severityIcon}"></i> ${issue.type}
</span>
<span style="color: #9ca3af; margin-left: 10px; font-size: 12px;">
${issue.file}:${issue.line}:${issue.column}
</span>
</div>
<span style="background: #1a1a1a; color: #9ca3af; padding: 2px 6px; border-radius: 3px; font-size: 11px;">
${severityText.toUpperCase()}
</span>
</div>
<div style="color: #e0e0e0; margin-bottom: 12px;">${issue.message}</div>
${issue.codeSnippet ? `
<div class="code-snippet-container" style="margin-bottom: 12px;">
<div style="display: flex; align-items: center; justify-content: space-between; background: #1a1a1a; padding: 6px 10px; border-radius: 4px 4px 0 0; border-bottom: 1px solid #3a3a3a;">
<span style="color: #9ca3af; font-size: 12px; font-weight: 500;">
<i class="fas fa-code" style="margin-right: 5px;"></i>
บริบทของโค้ด
</span>
<button class="copy-code-btn" onclick="window.diagnosticDashboard.copyCodeSnippet('${codeSnippetId}')"
style="background: none; border: none; color: #9ca3af; cursor: pointer; font-size: 12px; padding: 2px 5px; border-radius: 2px;">
<i class="fas fa-copy"></i> คัดลอก
</button>
</div>
<pre id="${codeSnippetId}" class="code-snippet" style="background: #0d1117; color: #c9d1d9; margin: 0; padding: 12px; border-radius: 0 0 4px 4px; overflow-x: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px; line-height: 1.4;"><code class="language-javascript">${this.escapeHtml(issue.codeSnippet)}</code></pre>
</div>
` : ''}
${issue.suggestion ? `<div style="color: #4fc3f7; font-size: 13px; font-style: italic;"> ${issue.suggestion}</div>` : ''}
</div>
`;
});
html += '</div>';
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,
'<span style="color: #ff7b72;">$1</span>');
// Strings
code = code.replace(/(["'`])((?:\\.|(?!\1)[^\\])*?)\1/g,
'<span style="color: #a5d6ff;">$1$2$1</span>');
// Numbers
code = code.replace(/\b(\d+(?:\.\d+)?)\b/g,
'<span style="color: #79c0ff;">$1</span>');
// Comments
code = code.replace(/\/\/(.*$)/gm,
'<span style="color: #8b949e; font-style: italic;">//$1</span>');
code = code.replace(/\/\*([\s\S]*?)\*\//g,
'<span style="color: #8b949e; font-style: italic;">/*$1*/</span>');
// Function calls
code = code.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,
'<span style="color: #d2a8ff;">$1</span>(');
// Problem line highlight (line starting with >)
code = code.replace(/^(>\s*\d+\s*\|)(.*$)/gm,
'<span style="background: rgba(248, 81, 73, 0.1); display: block; margin: 0 -12px; padding: 0 12px;"><span style="color: #f85149; font-weight: bold;">$1</span>$2</span>');
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 = '<i class="fas fa-check"></i> คัดลอกแล้ว!';
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 = `
<div class="no-selection">
<i class="fas fa-pause-circle"></i>
<h3>ไม่มีเวิร์กโฟลว์ที่กำลังทำงาน</h3>
<p>ใช้คำสั่ง <code>workflows</code> ในเทอร์มินัลเพื่อดูข้อมูลล่าสุด</p>
</div>
`;
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 = `
<div class="workflow-header">
<span class="workflow-name">${workflow.name}</span>
<span class="workflow-status ${statusClass}">${workflow.status}</span>
</div>
<div class="workflow-progress">
<span>${progress}/${total} nodes</span>
<span>${percentage}% complete</span>
</div>
`;
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;