modify main.js to English

This commit is contained in:
xiangjinyu 2025-03-10 16:24:07 +08:00
parent 81b9bb3660
commit 110213a29f

View File

@ -5,7 +5,7 @@ function createTask() {
const prompt = promptInput.value.trim(); const prompt = promptInput.value.trim();
if (!prompt) { if (!prompt) {
alert("请输入有效的提示内容"); alert("Please enter a valid prompt");
promptInput.focus(); promptInput.focus();
return; return;
} }
@ -16,7 +16,7 @@ function createTask() {
} }
const container = document.getElementById('task-container'); const container = document.getElementById('task-container');
container.innerHTML = '<div class="loading">任务初始化中...</div>'; container.innerHTML = '<div class="loading">Initializing task...</div>';
document.getElementById('input-container').classList.add('bottom'); document.getElementById('input-container').classList.add('bottom');
fetch('/tasks', { fetch('/tasks', {
@ -28,20 +28,20 @@ function createTask() {
}) })
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
return response.json().then(err => { throw new Error(err.detail || '请求失败') }); return response.json().then(err => { throw new Error(err.detail || 'Request failed') });
} }
return response.json(); return response.json();
}) })
.then(data => { .then(data => {
if (!data.task_id) { if (!data.task_id) {
throw new Error('无效的任务ID'); throw new Error('Invalid task ID');
} }
setupSSE(data.task_id); setupSSE(data.task_id);
loadHistory(); loadHistory();
}) })
.catch(error => { .catch(error => {
container.innerHTML = `<div class="error">错误: ${error.message}</div>`; container.innerHTML = `<div class="error">Error: ${error.message}</div>`;
console.error('创建任务失败:', error); console.error('Failed to create task:', error);
}); });
} }
@ -67,7 +67,7 @@ function setupSSE(taskId) {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('轮询失败:', error); console.error('Polling failed:', error);
}); });
}, 10000); }, 10000);
@ -92,9 +92,9 @@ function setupSSE(taskId) {
stepContainer = container.querySelector('.step-container'); stepContainer = container.querySelector('.step-container');
} }
// 保存result内容 // Save result content
if (data.steps && data.steps.length > 0) { if (data.steps && data.steps.length > 0) {
// 遍历所有步骤找到最后一个result类型 // Iterate through all steps, find the last result type
for (let i = data.steps.length - 1; i >= 0; i--) { for (let i = data.steps.length - 1; i >= 0; i--) {
if (data.steps[i].type === 'result') { if (data.steps[i].type === 'result') {
lastResultContent = data.steps[i].result; lastResultContent = data.steps[i].result;
@ -123,11 +123,11 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
} catch (e) { } catch (e) {
console.error('状态更新失败:', e); console.error('Status update failed:', e);
} }
}); });
// 添加对think事件的处理 // Add handler for think event
eventSource.addEventListener('think', (event) => { eventSource.addEventListener('think', (event) => {
clearInterval(heartbeatTimer); clearInterval(heartbeatTimer);
try { try {
@ -158,21 +158,21 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
// 更新任务状态 // Update task status
fetch(`/tasks/${taskId}`) fetch(`/tasks/${taskId}`)
.then(response => response.json()) .then(response => response.json())
.then(task => { .then(task => {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('状态更新失败:', error); console.error('Status update failed:', error);
}); });
} catch (e) { } catch (e) {
console.error('思考事件处理失败:', e); console.error('Think event handling failed:', e);
} }
}); });
// 添加对tool事件的处理 // Add handler for tool event
eventSource.addEventListener('tool', (event) => { eventSource.addEventListener('tool', (event) => {
clearInterval(heartbeatTimer); clearInterval(heartbeatTimer);
try { try {
@ -203,21 +203,21 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
// 更新任务状态 // Update task status
fetch(`/tasks/${taskId}`) fetch(`/tasks/${taskId}`)
.then(response => response.json()) .then(response => response.json())
.then(task => { .then(task => {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('状态更新失败:', error); console.error('Status update failed:', error);
}); });
} catch (e) { } catch (e) {
console.error('工具事件处理失败:', e); console.error('Tool event handling failed:', e);
} }
}); });
// 添加对act事件的处理 // Add handler for act event
eventSource.addEventListener('act', (event) => { eventSource.addEventListener('act', (event) => {
clearInterval(heartbeatTimer); clearInterval(heartbeatTimer);
try { try {
@ -248,22 +248,21 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
// 更新任务状态 // Update task status
fetch(`/tasks/${taskId}`) fetch(`/tasks/${taskId}`)
.then(response => response.json()) .then(response => response.json())
.then(task => { .then(task => {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('状态更新失败:', error); console.error('Status update failed:', error);
}); });
} catch (e) { } catch (e) {
console.error('执行事件处理失败:', e); console.error('Act event handling failed:', e);
} }
}); });
// 添加对run事件的处理 // Add handler for log event
// 添加对log事件的处理
eventSource.addEventListener('log', (event) => { eventSource.addEventListener('log', (event) => {
clearInterval(heartbeatTimer); clearInterval(heartbeatTimer);
try { try {
@ -294,17 +293,17 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
// 更新任务状态 // Update task status
fetch(`/tasks/${taskId}`) fetch(`/tasks/${taskId}`)
.then(response => response.json()) .then(response => response.json())
.then(task => { .then(task => {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('状态更新失败:', error); console.error('Status update failed:', error);
}); });
} catch (e) { } catch (e) {
console.error('日志事件处理失败:', e); console.error('Log event handling failed:', e);
} }
}); });
@ -338,17 +337,17 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
// 更新任务状态 // Update task status
fetch(`/tasks/${taskId}`) fetch(`/tasks/${taskId}`)
.then(response => response.json()) .then(response => response.json())
.then(task => { .then(task => {
updateTaskStatus(task); updateTaskStatus(task);
}) })
.catch(error => { .catch(error => {
console.error('状态更新失败:', error); console.error('Status update failed:', error);
}); });
} catch (e) { } catch (e) {
console.error('运行事件处理失败:', e); console.error('Run event handling failed:', e);
} }
}); });
@ -391,7 +390,7 @@ function setupSSE(taskId) {
behavior: 'smooth' behavior: 'smooth'
}); });
} catch (e) { } catch (e) {
console.error('消息处理失败:', e); console.error('Message handling failed:', e);
} }
}); });
@ -403,13 +402,13 @@ function setupSSE(taskId) {
clearInterval(pollInterval); clearInterval(pollInterval);
container.innerHTML += ` container.innerHTML += `
<div class="complete"> <div class="complete">
<div> 任务完成</div> <div> Task completed</div>
<pre>${lastResultContent}</pre> <pre>${lastResultContent}</pre>
</div> </div>
`; `;
eventSource.close(); eventSource.close();
currentEventSource = null; currentEventSource = null;
lastResultContent = ''; // 清空结果内容 lastResultContent = ''; // Clear result content
}); });
eventSource.addEventListener('error', (event) => { eventSource.addEventListener('error', (event) => {
@ -419,13 +418,13 @@ function setupSSE(taskId) {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
container.innerHTML += ` container.innerHTML += `
<div class="error"> <div class="error">
错误: ${data.message} Error: ${data.message}
</div> </div>
`; `;
eventSource.close(); eventSource.close();
currentEventSource = null; currentEventSource = null;
} catch (e) { } catch (e) {
console.error('错误处理失败:', e); console.error('Error handling failed:', e);
} }
}); });
} }
@ -440,7 +439,7 @@ function setupSSE(taskId) {
return; return;
} }
console.error('SSE连接错误:', err); console.error('SSE connection error:', err);
clearInterval(heartbeatTimer); clearInterval(heartbeatTimer);
clearInterval(pollInterval); clearInterval(pollInterval);
eventSource.close(); eventSource.close();
@ -449,14 +448,14 @@ function setupSSE(taskId) {
retryCount++; retryCount++;
container.innerHTML += ` container.innerHTML += `
<div class="warning"> <div class="warning">
连接中断${retryDelay/1000}秒后重试 (${retryCount}/${maxRetries})... Connection lost, retrying in ${retryDelay/1000} seconds (${retryCount}/${maxRetries})...
</div> </div>
`; `;
setTimeout(connect, retryDelay); setTimeout(connect, retryDelay);
} else { } else {
container.innerHTML += ` container.innerHTML += `
<div class="error"> <div class="error">
连接中断请尝试刷新页面 Connection lost, please try refreshing the page
</div> </div>
`; `;
} }
@ -474,50 +473,36 @@ function getEventIcon(eventType) {
case 'result': return '🏁'; case 'result': return '🏁';
case 'error': return '❌'; case 'error': return '❌';
case 'complete': return '✅'; case 'complete': return '✅';
case 'warning': return '⚠️';
case 'log': return '📝'; case 'log': return '📝';
default: return '⚡'; case 'run': return '⚙️';
default: return '';
} }
} }
function getEventLabel(eventType) { function getEventLabel(eventType) {
switch(eventType) { switch(eventType) {
case 'think': return '思考'; case 'think': return 'Thinking';
case 'tool': return '工具执行'; case 'tool': return 'Using Tool';
case 'act': return '执行'; case 'act': return 'Action';
case 'result': return '结果'; case 'result': return 'Result';
case 'error': return '错误'; case 'error': return 'Error';
case 'complete': return '完成'; case 'complete': return 'Complete';
case 'warning': return '警告'; case 'log': return 'Log';
case 'log': return '日志'; case 'run': return 'Running';
default: return '步骤'; default: return 'Info';
} }
} }
function formatContent(content) {
// Remove timestamp and log level prefixes
content = content.replace(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} \| [A-Z]+\s*\| /gm, '');
// Format the remaining content
return content
.replace(/\n/g, '<br>')
.replace(/ /g, '&nbsp;&nbsp;')
.replace(/✨ Manus's thoughts:/g, '')
.replace(/🛠️ Manus selected/g, '')
.replace(/🧰 Tools being prepared:/g, '')
.replace(/🔧 Activating tool:/g, '')
.replace(/🎯 Tool/g, '')
.replace(/📝 Oops!/g, '')
.replace(/🏁 Special tool/g, '');
}
function updateTaskStatus(task) { function updateTaskStatus(task) {
const taskCard = document.querySelector(`.task-card[data-task-id="${task.id}"]`); const statusBar = document.getElementById('status-bar');
if (taskCard) { if (!statusBar) return;
const statusEl = taskCard.querySelector('.task-meta .status');
if (statusEl) { if (task.status === 'completed') {
statusEl.className = `status-${task.status ? task.status.toLowerCase() : 'unknown'}`; statusBar.innerHTML = `<span class="status-complete">✅ Task completed</span>`;
statusEl.textContent = task.status || '未知状态'; } else if (task.status === 'failed') {
} statusBar.innerHTML = `<span class="status-error">❌ Task failed: ${task.error || 'Unknown error'}</span>`;
} else {
statusBar.innerHTML = `<span class="status-running">⚙️ Task running: ${task.status}</span>`;
} }
} }
@ -525,61 +510,186 @@ function loadHistory() {
fetch('/tasks') fetch('/tasks')
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
return response.text().then(text => { throw new Error('Failed to load history');
throw new Error(`请求失败: ${response.status} - ${text.substring(0, 100)}`);
});
} }
return response.json(); return response.json();
}) })
.then(tasks => { .then(tasks => {
const listContainer = document.getElementById('task-list'); const historyContainer = document.getElementById('history-container');
listContainer.innerHTML = tasks.map(task => ` if (!historyContainer) return;
<div class="task-card" data-task-id="${task.id}">
<div>${task.prompt}</div> historyContainer.innerHTML = '';
<div class="task-meta">
${new Date(task.created_at).toLocaleString()} - if (tasks.length === 0) {
<span class="status status-${task.status ? task.status.toLowerCase() : 'unknown'}"> historyContainer.innerHTML = '<div class="history-empty">No recent tasks</div>';
${task.status || '未知状态'} return;
</span> }
const historyList = document.createElement('div');
historyList.className = 'history-list';
tasks.forEach(task => {
const taskItem = document.createElement('div');
taskItem.className = `history-item ${task.status}`;
taskItem.innerHTML = `
<div class="history-prompt">${task.prompt}</div>
<div class="history-meta">
<span class="history-time">${new Date(task.created_at).toLocaleString()}</span>
<span class="history-status">${getStatusIcon(task.status)}</span>
</div> </div>
</div> `;
`).join(''); taskItem.addEventListener('click', () => {
loadTask(task.id);
});
historyList.appendChild(taskItem);
});
historyContainer.appendChild(historyList);
}) })
.catch(error => { .catch(error => {
console.error('加载历史记录失败:', error); console.error('Failed to load history:', error);
const listContainer = document.getElementById('task-list'); const historyContainer = document.getElementById('history-container');
listContainer.innerHTML = `<div class="error">加载失败: ${error.message}</div>`; if (historyContainer) {
historyContainer.innerHTML = `<div class="error">Failed to load history: ${error.message}</div>`;
}
}); });
} }
document.addEventListener('DOMContentLoaded', function() { function getStatusIcon(status) {
const welcomeMessage = document.querySelector('.welcome-message'); switch(status) {
if (welcomeMessage) { case 'completed': return '✅';
welcomeMessage.style.display = 'flex'; case 'failed': return '❌';
case 'running': return '⚙️';
default: return '⏳';
}
} }
// 监听任务容器显示状态 function loadTask(taskId) {
const taskContainer = document.getElementById('task-container'); if (currentEventSource) {
if (taskContainer) { currentEventSource.close();
const observer = new MutationObserver((mutations) => { currentEventSource = null;
mutations.forEach(mutation => { }
if (mutation.attributeName === 'class') {
const container = document.getElementById('task-container');
container.innerHTML = '<div class="loading">Loading task...</div>';
document.getElementById('input-container').classList.add('bottom');
fetch(`/tasks/${taskId}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to load task');
}
return response.json();
})
.then(task => {
if (task.status === 'running') {
setupSSE(taskId);
} else {
displayTask(task);
}
})
.catch(error => {
console.error('Failed to load task:', error);
container.innerHTML = `<div class="error">Failed to load task: ${error.message}</div>`;
});
}
function displayTask(task) {
const container = document.getElementById('task-container');
container.innerHTML = '';
container.classList.add('active');
const welcomeMessage = document.querySelector('.welcome-message'); const welcomeMessage = document.querySelector('.welcome-message');
if (taskContainer.classList.contains('active')) {
if (welcomeMessage) { if (welcomeMessage) {
welcomeMessage.style.display = 'none'; welcomeMessage.style.display = 'none';
} }
} else {
if (welcomeMessage) { const stepContainer = document.createElement('div');
welcomeMessage.style.display = 'block'; stepContainer.className = 'step-container';
}
} if (task.steps && task.steps.length > 0) {
} task.steps.forEach(step => {
const stepItem = document.createElement('div');
stepItem.className = `step-item ${step.type || 'step'}`;
const content = step.result;
const timestamp = new Date(step.timestamp || task.created_at).toLocaleTimeString();
stepItem.innerHTML = `
<div class="log-line">
<span class="log-prefix">${getEventIcon(step.type)} [${timestamp}] ${getEventLabel(step.type)}:</span>
<pre>${content}</pre>
</div>
`;
stepContainer.appendChild(stepItem);
}); });
} else {
stepContainer.innerHTML = '<div class="no-steps">No steps recorded for this task</div>';
}
container.appendChild(stepContainer);
if (task.status === 'completed') {
let lastResultContent = '';
if (task.steps && task.steps.length > 0) {
for (let i = task.steps.length - 1; i >= 0; i--) {
if (task.steps[i].type === 'result') {
lastResultContent = task.steps[i].result;
break;
}
}
}
container.innerHTML += `
<div class="complete">
<div> Task completed</div>
<pre>${lastResultContent}</pre>
</div>
`;
} else if (task.status === 'failed') {
container.innerHTML += `
<div class="error">
Error: ${task.error || 'Unknown error'}
</div>
`;
}
updateTaskStatus(task);
}
// Initialize the app when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
loadHistory();
// Set up event listeners
document.getElementById('create-task-btn').addEventListener('click', createTask);
document.getElementById('prompt-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
createTask();
}
}); });
observer.observe(taskContainer, { // Show history button functionality
attributes: true const historyToggle = document.getElementById('history-toggle');
if (historyToggle) {
historyToggle.addEventListener('click', () => {
const historyPanel = document.getElementById('history-panel');
if (historyPanel) {
historyPanel.classList.toggle('open');
historyToggle.classList.toggle('active');
}
});
}
// Clear button functionality
const clearButton = document.getElementById('clear-btn');
if (clearButton) {
clearButton.addEventListener('click', () => {
document.getElementById('prompt-input').value = '';
document.getElementById('prompt-input').focus();
}); });
} }
}); });