diff --git a/app.js b/app.js index abaf574..4b2c32e 100644 --- a/app.js +++ b/app.js @@ -2,6 +2,7 @@ // Map const stationPool = new Map(); const reconnectTimers = new Map(); +const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; // Variáveis de compatibilidade legada let ws = null; @@ -532,6 +533,112 @@ function getAuthToken() { } } +function getRefreshToken() { + try { + return localStorage.getItem('maestri_refresh_token') || null; + } catch (e) { + return null; + } +} + +function setAuthSession(token, refreshToken, user) { + try { + if (token) localStorage.setItem('maestri_auth_token', token); + if (refreshToken) localStorage.setItem('maestri_refresh_token', refreshToken); + if (user) localStorage.setItem('maestri_user', JSON.stringify(user)); + } catch (e) {} +} + +function clearAuthSession() { + try { + localStorage.removeItem('maestri_auth_token'); + localStorage.removeItem('maestri_refresh_token'); + localStorage.removeItem('maestri_user'); + } catch (e) {} + currentAuthUser = null; +} + +let activeRefreshPromise = null; + +async function refreshAuthSession() { + const refreshToken = getRefreshToken(); + if (!refreshToken) { + return false; + } + + // Deduplicação: reaproveita a Promise se já houver uma renovação silenciosa em andamento + if (activeRefreshPromise) { + return activeRefreshPromise; + } + + activeRefreshPromise = (async () => { + try { + const res = await fetch(`${getApiBaseUrl()}/api/auth/refresh`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ refreshToken }) + }); + + if (res.ok) { + const data = await res.json(); + if (data && data.token) { + setAuthSession(data.token, data.refreshToken || refreshToken, data.user); + if (data.user) { + updateUserBadge(data.user); + } + return true; + } + } + + // 401 ou 403 indica que o refresh token expirou ou foi revogado + if (res.status === 401 || res.status === 403) { + console.warn('[Auth] Refresh token inválido ou expirado. Sessão encerrada.'); + clearAuthSession(); + return false; + } + + // Erro transitório de rede ou servidor + return false; + } catch (err) { + console.warn('[Auth] Falha de rede ao tentar renovar sessão:', err.message); + return false; + } finally { + activeRefreshPromise = null; + } + })(); + + return activeRefreshPromise; +} + +async function fetchWithAuth(url, options = {}) { + let token = getAuthToken(); + const headers = { ...(options.headers || {}) }; + if (token) { + headers['Authorization'] = `Bearer ${token}`; + } + + let res; + try { + res = await fetch(url, { ...options, headers }); + } catch (netErr) { + throw netErr; + } + + if (res.status === 401 && getRefreshToken()) { + const refreshed = await refreshAuthSession(); + if (refreshed) { + const newToken = getAuthToken(); + const retryHeaders = { ...(options.headers || {}) }; + if (newToken) { + retryHeaders['Authorization'] = `Bearer ${newToken}`; + } + return await fetch(url, { ...options, headers: retryHeaders }); + } + } + + return res; +} + function getSavedAuthUser() { try { const raw = localStorage.getItem('maestri_user'); @@ -583,14 +690,12 @@ function updateUserBadge(user) { } async function syncStationToServer(method, pathSuffix, body) { - const token = getAuthToken(); - if (!token) return null; + if (!getAuthToken() && !getRefreshToken()) return null; try { - const res = await fetch(`${getApiBaseUrl()}${pathSuffix}`, { + const res = await fetchWithAuth(`${getApiBaseUrl()}${pathSuffix}`, { method, headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${token}` + 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); @@ -608,12 +713,9 @@ async function syncStationToServer(method, pathSuffix, body) { } async function syncStationsFromServer() { - const token = getAuthToken(); - if (!token) return getSavedStations(); + if (!getAuthToken() && !getRefreshToken()) return getSavedStations(); try { - const res = await fetch(`${getApiBaseUrl()}/api/stations`, { - headers: { 'Authorization': `Bearer ${token}` } - }); + const res = await fetchWithAuth(`${getApiBaseUrl()}/api/stations`); if (res.status === 401) { logoutUser(); return []; @@ -811,21 +913,18 @@ async function startGoogleLogin() { }; activeAuthPollCleanup = cleanup; - const finalizeSuccess = async (token, user) => { + const finalizeSuccess = async (token, user, refreshToken) => { if (finished) return; finished = true; cleanup(); - try { - localStorage.setItem('maestri_auth_token', token); - localStorage.setItem('maestri_user', JSON.stringify(user || {})); - } catch (e) {} + setAuthSession(token, refreshToken, user); await completeAuthenticatedStartup(user); }; const onWindowMessage = (event) => { const data = event?.data; if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) { - finalizeSuccess(data.token, data.user); + finalizeSuccess(data.token, data.user, data.refreshToken); } }; @@ -842,7 +941,7 @@ async function startGoogleLogin() { if (!pollRes.ok) return; const data = await pollRes.json(); if (data.status === 'completed' && data.token) { - await finalizeSuccess(data.token, data.user); + await finalizeSuccess(data.token, data.user, data.refreshToken); } else if (data.status === 'expired') { finished = true; cleanup(); @@ -2737,10 +2836,10 @@ function formatElapsed(startTime) { } function extractLatestAction(terminalText) { - if (!terminalText || typeof terminalText !== 'string') return 'Processando solicitação...'; + if (!terminalText || typeof terminalText !== 'string') return ''; const clean = cleanTerminalOutput(terminalText).trim(); const lines = clean.split('\n').map(l => l.trim()).filter(Boolean); - if (!lines.length) return 'Processando solicitação...'; + if (!lines.length) return ''; for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i]; @@ -2749,6 +2848,11 @@ function extractLatestAction(terminalText) { if (/usage limit reached|continuing automatically at|limit resets|5-hour limit|rate limit reached|quota exceeded/i.test(line)) continue; // Ignora menções de código ou CSS para evitar falsos positivos if (/\.thinking|\#f59e0b|isThinking/i.test(line)) continue; + // Ignora prompts de shell do sistema (PowerShell, CMD, Bash e fragmentos wrapped) + if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|(?:[\w.-]+@[\w.-]+:.*?[#$])|bash-|\$|#|PS\s*>)/i.test(line)) continue; + if (line.endsWith('>') && /(?:\\|\/|PS\s+|[A-Za-z]:|Reader>|Prompt>|[a-zA-Z0-9_.-]+>)/i.test(line)) continue; + if (/Windows PowerShell|Copyright \(C\) Microsoft|Microsoft Windows \[Version/i.test(line)) continue; + if (/(?:running command|generating|percolating|analyzing|working|building|compiling|thinking\.\.\.)/i.test(line)) { return line.slice(0, 50); } @@ -2760,7 +2864,14 @@ function extractLatestAction(terminalText) { } } + // Se a última linha for um prompt de shell ou prompt fragmentado (ex: apeReader>), não exibe como ação const lastLine = lines[lines.length - 1]; + if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|[\w.-]+@[\w.-]+:|\$|#|PS\s*>)/i.test(lastLine) || + lastLine.endsWith('>') || + /Windows PowerShell|Microsoft Windows/i.test(lastLine)) { + return ''; + } + return lastLine.length > 50 ? lastLine.slice(0, 47) + '...' : lastLine; } @@ -2786,7 +2897,6 @@ function stopThinkingTimer() { thinkingStartTime = null; } -const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; const RE_HORIZONTAL_FOOTER = /(?:ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|←\/?→\s*(?:Effort|(?:to\s+)?(?:select|navigate)))/i; const RE_TUI_FOOTER = /(?:Keyboard:\s*(?:↑\/↓\s*Navigate|←\/→\s*Effort)|←\/→\s*Effort|↑\/?↓\s*to navigate|↵\s*to select|enter\s+Select|esc\s+Go Back|esc\s+to\s+close|esc\s+to\s+go\s+back|Enter to confirm\s*·\s*Esc to cancel|space to select|to navigate\s*·\s*↵\s*to select|ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|Connect provider ctrl\+a|Favorite ctrl\+f|ctrl\+t variants|tab to switch panels|at top for controls)/i; const RE_APPROVAL_HEADER = /\brequires approval\b|\bDo you want to proceed\?|\bPermission required\b|\bAlways allow\b|\bSelect model\b|\bSelect variant\b|\bSwitch Model\b|\bSet Effort\b|tab to switch panels/i; @@ -3701,8 +3811,12 @@ function detectAgentThinking(terminalText, isWaiting = false) { return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; } - const raw = terminalText.trim(); - const lastChunk = raw.slice(-800); + const clean = terminalText.replace(RE_ANSI, '').trim(); + if (!clean) { + return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; + } + + const lastChunk = clean.slice(-800); // 0. Detecção de Limite de Cota / Rate Limit / Pausa de Agente const isUsageLimit = /(?:usage limit reached|limit resets|continuing automatically at|you've hit your \d+-hour limit|rate limit reached|quota exceeded)/i.test(lastChunk); @@ -3730,13 +3844,30 @@ function detectAgentThinking(terminalText, isWaiting = false) { }; } - // 1. PRECEDÊNCIA MÁXIMA: Se o terminal está no prompt ocioso de entrada de IA - const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean); + // 1. PRECEDÊNCIA MÁXIMA: Prompts de Shell do Sistema e Prompts Ociosos de IA + const lines = clean.split(/\r?\n/).map(l => l.trim()).filter(Boolean); const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''; const prevLine = lines.length > 1 ? lines[lines.length - 2] : ''; const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : ''; + const combinedLast2 = prevLine ? `${prevLine}${lastLine}` : lastLine; + const combinedLast3 = lines.slice(-3).join(''); - const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(raw.slice(-300)); + const isShellPrompt = + /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(lastLine) || + /(?:^|\n)\s*PS\s*>\s*$/m.test(lastLine) || + /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(lastLine) || + /(?:^|\n)\s*(?:(?:\([\w.-]+\)\s*)?[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$\s*|#\s*)$/m.test(lastLine) || + /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(combinedLast2) || + /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(combinedLast2) || + /(?:^|\n)\s*PS\s+.*?>\s*$/m.test(combinedLast3) || + /^\s*PS\s+.*?>\s*$/i.test(lastLine) || + (lastLine.endsWith('>') && (/Windows PowerShell|PowerShell 7|Microsoft Windows/i.test(clean) || /PS\s+[A-Za-z]:/i.test(clean))); + + if (isShellPrompt) { + return { isThinking: false, isPaused: false, label: 'Pronto' }; + } + + const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(clean.slice(-300)); const hasActiveSubagentOrToolOnPrev = hasExplicitActiveSubagents || (/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) || @@ -3805,7 +3936,7 @@ function detectAgentThinking(terminalText, isWaiting = false) { } // 6. Sessão com IA ativa em andamento fora do prompt ocioso de entrada - if (!isAtIdlePrompt && /(?:Antigravity CLI|\? for shortcuts|● Ran \(|● Explored |● Edited |Claude Code|Kiro CLI|kiro>|Gemini CLI|Aider)/i.test(lastChunk)) { + if (!isAtIdlePrompt && !isShellPrompt && /(?:Antigravity CLI|\? for shortcuts|● Ran \(|● Explored |● Edited |Claude Code|Kiro CLI|kiro>|Gemini CLI|Aider)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' }; } @@ -3814,9 +3945,10 @@ function detectAgentThinking(terminalText, isWaiting = false) { return { isThinking: true, isPaused: false, label: 'Agente está pensando...' }; } - return { isThinking: false, isPaused: false, label: '' }; + return { isThinking: false, isPaused: false, label: 'Pronto' }; } window.detectAgentThinking = detectAgentThinking; +window.extractLatestAction = extractLatestAction; function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) { const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean') @@ -5261,11 +5393,9 @@ function logoutUser() { }); stationPool.clear(); - localStorage.removeItem('maestri_auth_token'); - localStorage.removeItem('maestri_user'); + clearAuthSession(); localStorage.removeItem('maestri_pin'); localStorage.removeItem('maestri_stations'); - currentAuthUser = null; currentPin = null; ws = null; @@ -5434,9 +5564,11 @@ async function initApp() { } initOtaChecker(); - // Gate obrigatório de autenticação Google SSO - const token = getAuthToken(); - if (!token) { + // Gate obrigatório de autenticação Google SSO com renovação silenciosa via refresh token + let token = getAuthToken(); + const refreshToken = getRefreshToken(); + + if (!token && !refreshToken) { if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } @@ -5444,10 +5576,36 @@ async function initApp() { return; } + // Se o access token está ausente mas temos refresh token, tenta renovação silenciosa imediata + if (!token && refreshToken) { + const refreshed = await refreshAuthSession(); + if (refreshed) { + token = getAuthToken(); + } else { + if (pinFromUrl && pinFromUrl.length >= 4) { + try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} + } + showAuthScreen(); + return; + } + } + try { - const meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, { + let meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, { headers: { 'Authorization': `Bearer ${token}` } }); + + // Se respondeu 401, tenta renovação silenciosa via refresh token antes de deslogar + if (meRes.status === 401 && getRefreshToken()) { + const refreshed = await refreshAuthSession(); + if (refreshed) { + token = getAuthToken(); + meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, { + headers: { 'Authorization': `Bearer ${token}` } + }); + } + } + if (meRes.ok) { const data = await meRes.json(); if (data && data.user) { @@ -5460,8 +5618,7 @@ async function initApp() { } } if (meRes.status === 401) { - localStorage.removeItem('maestri_auth_token'); - localStorage.removeItem('maestri_user'); + clearAuthSession(); if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } @@ -5483,6 +5640,34 @@ async function initApp() { } } +// Listener para renovação proativa quando o app volta do background +const checkTokenExpiryAndRefresh = async () => { + const currentToken = getAuthToken(); + const currentRefresh = getRefreshToken(); + if (!currentToken || !currentRefresh) return; + try { + const parts = currentToken.split('.'); + if (parts.length === 3) { + const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/'))); + const nowSec = Math.floor(Date.now() / 1000); + if (typeof payload.exp === 'number' && payload.exp - nowSec < 300) { + await refreshAuthSession(); + } + } + } catch (e) {} +}; + +document.addEventListener('visibilitychange', () => { + if (!document.hidden) checkTokenExpiryAndRefresh(); +}); +window.addEventListener('focus', checkTokenExpiryAndRefresh); +window.addEventListener('resume', checkTokenExpiryAndRefresh); + +window.logoutUser = logoutUser; +window.getRefreshToken = getRefreshToken; +window.refreshAuthSession = refreshAuthSession; +window.fetchWithAuth = fetchWithAuth; + if (document.readyState === 'loading') { window.addEventListener('DOMContentLoaded', initApp); } else { diff --git a/package.json b/package.json index 6459ec5..ebdd435 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "maestri-remote-agent", - "version": "1.0.31", + "version": "1.0.32", "type": "module", "description": "Gateway Local do Maestri Remote para estações de trabalho", "bin": { diff --git a/public/app.js b/public/app.js index 586ea2e..4b2c32e 100644 --- a/public/app.js +++ b/public/app.js @@ -2,6 +2,7 @@ // Map const stationPool = new Map(); const reconnectTimers = new Map(); +const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; // Variáveis de compatibilidade legada let ws = null; @@ -2835,10 +2836,10 @@ function formatElapsed(startTime) { } function extractLatestAction(terminalText) { - if (!terminalText || typeof terminalText !== 'string') return 'Processando solicitação...'; + if (!terminalText || typeof terminalText !== 'string') return ''; const clean = cleanTerminalOutput(terminalText).trim(); const lines = clean.split('\n').map(l => l.trim()).filter(Boolean); - if (!lines.length) return 'Processando solicitação...'; + if (!lines.length) return ''; for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i]; @@ -2847,6 +2848,11 @@ function extractLatestAction(terminalText) { if (/usage limit reached|continuing automatically at|limit resets|5-hour limit|rate limit reached|quota exceeded/i.test(line)) continue; // Ignora menções de código ou CSS para evitar falsos positivos if (/\.thinking|\#f59e0b|isThinking/i.test(line)) continue; + // Ignora prompts de shell do sistema (PowerShell, CMD, Bash e fragmentos wrapped) + if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|(?:[\w.-]+@[\w.-]+:.*?[#$])|bash-|\$|#|PS\s*>)/i.test(line)) continue; + if (line.endsWith('>') && /(?:\\|\/|PS\s+|[A-Za-z]:|Reader>|Prompt>|[a-zA-Z0-9_.-]+>)/i.test(line)) continue; + if (/Windows PowerShell|Copyright \(C\) Microsoft|Microsoft Windows \[Version/i.test(line)) continue; + if (/(?:running command|generating|percolating|analyzing|working|building|compiling|thinking\.\.\.)/i.test(line)) { return line.slice(0, 50); } @@ -2858,7 +2864,14 @@ function extractLatestAction(terminalText) { } } + // Se a última linha for um prompt de shell ou prompt fragmentado (ex: apeReader>), não exibe como ação const lastLine = lines[lines.length - 1]; + if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|[\w.-]+@[\w.-]+:|\$|#|PS\s*>)/i.test(lastLine) || + lastLine.endsWith('>') || + /Windows PowerShell|Microsoft Windows/i.test(lastLine)) { + return ''; + } + return lastLine.length > 50 ? lastLine.slice(0, 47) + '...' : lastLine; } @@ -2884,7 +2897,6 @@ function stopThinkingTimer() { thinkingStartTime = null; } -const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; const RE_HORIZONTAL_FOOTER = /(?:ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|←\/?→\s*(?:Effort|(?:to\s+)?(?:select|navigate)))/i; const RE_TUI_FOOTER = /(?:Keyboard:\s*(?:↑\/↓\s*Navigate|←\/→\s*Effort)|←\/→\s*Effort|↑\/?↓\s*to navigate|↵\s*to select|enter\s+Select|esc\s+Go Back|esc\s+to\s+close|esc\s+to\s+go\s+back|Enter to confirm\s*·\s*Esc to cancel|space to select|to navigate\s*·\s*↵\s*to select|ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|Connect provider ctrl\+a|Favorite ctrl\+f|ctrl\+t variants|tab to switch panels|at top for controls)/i; const RE_APPROVAL_HEADER = /\brequires approval\b|\bDo you want to proceed\?|\bPermission required\b|\bAlways allow\b|\bSelect model\b|\bSelect variant\b|\bSwitch Model\b|\bSet Effort\b|tab to switch panels/i; @@ -3799,8 +3811,12 @@ function detectAgentThinking(terminalText, isWaiting = false) { return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; } - const raw = terminalText.trim(); - const lastChunk = raw.slice(-800); + const clean = terminalText.replace(RE_ANSI, '').trim(); + if (!clean) { + return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; + } + + const lastChunk = clean.slice(-800); // 0. Detecção de Limite de Cota / Rate Limit / Pausa de Agente const isUsageLimit = /(?:usage limit reached|limit resets|continuing automatically at|you've hit your \d+-hour limit|rate limit reached|quota exceeded)/i.test(lastChunk); @@ -3828,13 +3844,30 @@ function detectAgentThinking(terminalText, isWaiting = false) { }; } - // 1. PRECEDÊNCIA MÁXIMA: Se o terminal está no prompt ocioso de entrada de IA - const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean); + // 1. PRECEDÊNCIA MÁXIMA: Prompts de Shell do Sistema e Prompts Ociosos de IA + const lines = clean.split(/\r?\n/).map(l => l.trim()).filter(Boolean); const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''; const prevLine = lines.length > 1 ? lines[lines.length - 2] : ''; const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : ''; + const combinedLast2 = prevLine ? `${prevLine}${lastLine}` : lastLine; + const combinedLast3 = lines.slice(-3).join(''); - const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(raw.slice(-300)); + const isShellPrompt = + /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(lastLine) || + /(?:^|\n)\s*PS\s*>\s*$/m.test(lastLine) || + /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(lastLine) || + /(?:^|\n)\s*(?:(?:\([\w.-]+\)\s*)?[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$\s*|#\s*)$/m.test(lastLine) || + /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(combinedLast2) || + /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(combinedLast2) || + /(?:^|\n)\s*PS\s+.*?>\s*$/m.test(combinedLast3) || + /^\s*PS\s+.*?>\s*$/i.test(lastLine) || + (lastLine.endsWith('>') && (/Windows PowerShell|PowerShell 7|Microsoft Windows/i.test(clean) || /PS\s+[A-Za-z]:/i.test(clean))); + + if (isShellPrompt) { + return { isThinking: false, isPaused: false, label: 'Pronto' }; + } + + const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(clean.slice(-300)); const hasActiveSubagentOrToolOnPrev = hasExplicitActiveSubagents || (/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) || @@ -3903,7 +3936,7 @@ function detectAgentThinking(terminalText, isWaiting = false) { } // 6. Sessão com IA ativa em andamento fora do prompt ocioso de entrada - if (!isAtIdlePrompt && /(?:Antigravity CLI|\? for shortcuts|● Ran \(|● Explored |● Edited |Claude Code|Kiro CLI|kiro>|Gemini CLI|Aider)/i.test(lastChunk)) { + if (!isAtIdlePrompt && !isShellPrompt && /(?:Antigravity CLI|\? for shortcuts|● Ran \(|● Explored |● Edited |Claude Code|Kiro CLI|kiro>|Gemini CLI|Aider)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' }; } @@ -3912,9 +3945,10 @@ function detectAgentThinking(terminalText, isWaiting = false) { return { isThinking: true, isPaused: false, label: 'Agente está pensando...' }; } - return { isThinking: false, isPaused: false, label: '' }; + return { isThinking: false, isPaused: false, label: 'Pronto' }; } window.detectAgentThinking = detectAgentThinking; +window.extractLatestAction = extractLatestAction; function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) { const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean') diff --git a/public/bundles/bundle-1.0.32.zip b/public/bundles/bundle-1.0.32.zip new file mode 100644 index 0000000..c0012b2 Binary files /dev/null and b/public/bundles/bundle-1.0.32.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index 2bcfe1c..c0012b2 100644 Binary files a/public/bundles/bundle-latest.zip and b/public/bundles/bundle-latest.zip differ diff --git a/public/bundles/manifest.json b/public/bundles/manifest.json index de56b45..642582f 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { - "version": "1.0.31", - "buildId": "58d9c94c", - "releasedAt": "2026-11-22T15:34:43.243Z", - "bundleUrl": "/bundles/bundle-1.0.31.zip", + "version": "1.0.32", + "buildId": "b00e32c7", + "releasedAt": "2026-11-22T15:59:03.064Z", + "bundleUrl": "/bundles/bundle-1.0.32.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "32f6f2b500796a5da1019d302e454e008bc058094a56c1ac3e4c8dafbe612eed", - "sizeBytes": 75171 + "checksum": "2dc1bc3ec93d41b021d417937322e08e14b12efd20bbb700fb7fb84a0973f01a", + "sizeBytes": 75807 } \ No newline at end of file diff --git a/public/maestri-agent.zip b/public/maestri-agent.zip index 7df40fd..50b1a0b 100644 Binary files a/public/maestri-agent.zip and b/public/maestri-agent.zip differ diff --git a/src/utils/activity-detector.js b/src/utils/activity-detector.js index f1a6acb..5a0ec3c 100644 --- a/src/utils/activity-detector.js +++ b/src/utils/activity-detector.js @@ -7,10 +7,10 @@ */ // Padrões de prompt de shell puro do sistema operacional (final da saída) -const RE_PS_PROMPT = /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]).*?>\s*$/m; +const RE_PS_PROMPT = /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m; const RE_PS_GENERIC = /(?:^|\n)\s*PS\s*>\s*$/m; const RE_CMD_PROMPT = /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m; -const RE_BASH_PROMPT = /(?:^|\n)\s*(?:[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$\s*)$/m; +const RE_BASH_PROMPT = /(?:^|\n)\s*(?:(?:\([\w.-]+\)\s*)?[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$\s*|#\s*)$/m; // Padrões de cabeçalho inicial de shell puro const RE_PS_HEADER = /Windows PowerShell|PowerShell 7|Copyright \(C\) Microsoft Corporation/i; @@ -807,15 +807,54 @@ export function detectTerminalActivity(rawOutput) { }; } - // Analisa os últimos 3000 caracteres para determinar o estado atual em foreground - const tail = trimmed.slice(-3000); - const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean); - const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''; + // Remove códigos ANSI de cor e estilo para análise limpa e determinística do buffer + const clean = rawOutput.replace(RE_ANSI, ''); + const cleanTrimmed = clean.trim(); + if (!cleanTrimmed) { + return { + hasAiActivity: false, + aiType: null, + shellType: 'empty', + isThinking: false, + isPaused: false, + pauseReason: null, + pauseResetTime: null, + hasInteractiveMenu: false, + interactiveMenu: null, + details: 'Terminal em branco' + }; + } + + // Analisa os últimos 3000 caracteres para determinar o estado atual em foreground + const tail = cleanTrimmed.slice(-3000); + const lines = cleanTrimmed.split(/\r?\n/).map(l => l.trim()).filter(Boolean); + const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''; + const prevLine = lines.length > 1 ? lines[lines.length - 2] : ''; + const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : ''; + const combinedLast2 = prevLine ? `${prevLine}${lastLine}` : lastLine; + const combinedLast3 = lines.slice(-3).join(''); + + // 1. Verifica se a última linha (ou o conjunto de linhas finais quebradas/wrapped) é um prompt de shell do sistema + const isLastLinePS = + RE_PS_PROMPT.test(lastLine) || + RE_PS_GENERIC.test(lastLine) || + RE_PS_PROMPT.test(combinedLast2) || + RE_PS_PROMPT.test(combinedLast3) || + /^\s*PS\s+.*?>\s*$/i.test(lastLine) || + (lastLine.endsWith('>') && (RE_PS_HEADER.test(tail) || /PS\s+[A-Za-z]:/i.test(tail))); + + const isLastLineCmd = !isLastLinePS && ( + RE_CMD_PROMPT.test(lastLine) || + RE_CMD_PROMPT.test(combinedLast2) || + RE_CMD_PROMPT.test(combinedLast3) || + (lastLine.endsWith('>') && (RE_CMD_HEADER.test(tail) || /[A-Za-z]:\\/i.test(tail))) + ); + + const isLastLineBash = !isLastLinePS && !isLastLineCmd && ( + RE_BASH_PROMPT.test(lastLine) || + RE_BASH_PROMPT.test(combinedLast2) + ); - // 1. Verifica se a última linha é claramente um prompt de shell do sistema - const isLastLinePS = RE_PS_PROMPT.test(lastLine) || RE_PS_GENERIC.test(lastLine); - const isLastLineCmd = !isLastLinePS && RE_CMD_PROMPT.test(lastLine); - const isLastLineBash = !isLastLinePS && !isLastLineCmd && RE_BASH_PROMPT.test(lastLine); const isEndingInShellPrompt = isLastLinePS || isLastLineCmd || isLastLineBash; // Se a última linha for um prompt de shell puro (ex: "PS C:\Users> " ou "C:\> " ou "user@host:~$ "), @@ -875,9 +914,6 @@ export function detectTerminalActivity(rawOutput) { } // 3. Verifica assinaturas de agentes de IA e execução em andamento - const prevLine = lines.length > 1 ? lines[lines.length - 2] : ''; - const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : ''; - const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(tail.slice(-300)); const hasActiveSubagentOrToolOnPrev = @@ -908,8 +944,13 @@ export function detectTerminalActivity(rawOutput) { if (timeMatch) pauseResetTime = timeMatch[1]; } - // Se o agente está no prompt ocioso de entrada ou pausado por limite de uso/cota, NÃO está pensando - const hasExplicitIndicator = RE_SPINNERS.test(tail) || RE_RUNNING_WORDS.test(tail) || hasActiveSubagentOrToolOnPrev || (RE_CLAUDE_GLYPHS.test(tail) && !/done|completed/i.test(lastLine)); + // Indicadores explícitos de execução ativa de IA + const hasExplicitAiExecution = + RE_SPINNERS.test(tail) || + RE_RUNNING_WORDS.test(tail) || + hasActiveSubagentOrToolOnPrev || + (RE_CLAUDE_GLYPHS.test(tail) && !/done|completed/i.test(lastLine)); + const isThinking = !isUsageLimit && !isEndingInAiIdlePrompt; if (RE_AGY.test(tail)) { @@ -917,7 +958,7 @@ export function detectTerminalActivity(rawOutput) { hasAiActivity: true, aiType: 'agy', shellType: null, - isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && isThinking, + isThinking: !isUsageLimit && !isEndingInAiIdlePrompt, isPaused: isUsageLimit, pauseReason: isUsageLimit ? 'usage_limit' : null, pauseResetTime, @@ -997,7 +1038,8 @@ export function detectTerminalActivity(rawOutput) { }; } - if (isThinking) { + // Agente de IA genérico: SOMENTE quando houver evidência explícita e inequívoca de IA executando + if (hasExplicitAiExecution && isThinking) { return { hasAiActivity: true, aiType: 'generic_ai', @@ -1012,8 +1054,8 @@ export function detectTerminalActivity(rawOutput) { }; } - // 4. Fallback: Se não há indicador de IA, verifica se o corpo contém padrões de shell - if (RE_PS_HEADER.test(tail) || RE_PS_PROMPT.test(tail)) { + // 4. Fallback: Sem evidência de IA ativa, verifica se o corpo ou prompt indica shell do sistema + if (RE_PS_HEADER.test(tail) || RE_PS_PROMPT.test(tail) || lastLine.endsWith('>') || isLastLinePS) { return { hasAiActivity: false, aiType: null, @@ -1028,7 +1070,7 @@ export function detectTerminalActivity(rawOutput) { }; } - if (RE_CMD_HEADER.test(tail) || RE_CMD_PROMPT.test(tail)) { + if (RE_CMD_HEADER.test(tail) || RE_CMD_PROMPT.test(tail) || isLastLineCmd) { return { hasAiActivity: false, aiType: null, @@ -1043,7 +1085,7 @@ export function detectTerminalActivity(rawOutput) { }; } - if (RE_BASH_PROMPT.test(tail)) { + if (RE_BASH_PROMPT.test(tail) || isLastLineBash || /[$#]\s*$/.test(lastLine)) { return { hasAiActivity: false, aiType: null, diff --git a/test/activity-detector.test.js b/test/activity-detector.test.js index 816615b..671fb42 100644 --- a/test/activity-detector.test.js +++ b/test/activity-detector.test.js @@ -824,4 +824,52 @@ $ git status assert.strictEqual(r4.isThinking, true, 'Comando em execução sem prompt final de repouso deve manter isThinking = true estável'); assert.strictEqual(r4.details, 'Antigravity CLI ativo'); }); + + await t.test('26. Eliminação de Falsos-Positivos de Thinking em Terminais de Shell Comum (PowerShell, CMD, Bash, ANSI e Wraps)', () => { + // 26.1 PowerShell com prompt longo do usuário (ex: TapeReader) + const psTapeReader = `Windows PowerShell\nCopyright (C) Microsoft Corporation.\n\nPS C:\\Users\\user\\source\\repos\\MqlBots\\B3_TapeReader> `; + const r1 = detectTerminalActivity(psTapeReader); + assert.strictEqual(r1.hasAiActivity, false, 'PowerShell comum não deve ter hasAiActivity'); + assert.strictEqual(r1.isThinking, false, 'PowerShell comum não deve ficar em thinking'); + assert.strictEqual(r1.shellType, 'powershell'); + + // 26.2 PowerShell com sequências de escape ANSI no prompt + const psAnsiPrompt = `\x1b[32mPS C:\\Users\\user\\MqlBots\\B3_TapeReader>\x1b[0m `; + const r2 = detectTerminalActivity(psAnsiPrompt); + assert.strictEqual(r2.hasAiActivity, false, 'Prompt com ANSI não deve ter hasAiActivity'); + assert.strictEqual(r2.isThinking, false, 'Prompt com ANSI não deve ficar em thinking'); + assert.strictEqual(r2.shellType, 'powershell'); + + // 26.3 Prompt quebrado em múltiplas linhas por largura de terminal (ex: apeReader>) + const psWrappedPrompt = `Windows PowerShell\nPS C:\\Users\\user\\MqlBots\\B3_T\napeReader>`; + const r3 = detectTerminalActivity(psWrappedPrompt); + assert.strictEqual(r3.hasAiActivity, false, 'Prompt quebrado não deve ter hasAiActivity'); + assert.strictEqual(r3.isThinking, false, 'Prompt quebrado não deve ficar em thinking'); + assert.strictEqual(r3.shellType, 'powershell'); + + // 26.4 Prompt fragmentado isolado terminando em > sem IA + const promptFragmentOnly = `apeReader>`; + const r4 = detectTerminalActivity(promptFragmentOnly); + assert.strictEqual(r4.hasAiActivity, false, 'Prompt fragmentado isolado sem IA não deve ter hasAiActivity'); + assert.strictEqual(r4.isThinking, false, 'Prompt fragmentado isolado não deve ficar em thinking'); + + // 26.5 Prompt DOS/CMD comum e Bash comum + const cmdPrompt = `C:\\Users\\user\\MqlBots\\B3_TapeReader> `; + const r5 = detectTerminalActivity(cmdPrompt); + assert.strictEqual(r5.hasAiActivity, false); + assert.strictEqual(r5.isThinking, false); + assert.strictEqual(r5.shellType, 'cmd'); + + const bashPrompt = `developer@linux:~/MqlBots/B3_TapeReader$ `; + const r6 = detectTerminalActivity(bashPrompt); + assert.strictEqual(r6.hasAiActivity, false); + assert.strictEqual(r6.isThinking, false); + assert.strictEqual(r6.shellType, 'bash'); + + // 26.6 Texto genérico sem marcadores de IA nem spinners + const genericTerminalText = `Compilando projeto concluído com sucesso.\nTotal de arquivos: 42.\nLinha final sem prompt nem spinner.`; + const r7 = detectTerminalActivity(genericTerminalText); + assert.strictEqual(r7.hasAiActivity, false, 'Texto sem IA não deve ter hasAiActivity'); + assert.strictEqual(r7.isThinking, false, 'Texto sem IA não deve ficar em thinking'); + }); }); diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js index 11ff8d5..fd98676 100644 --- a/test/frontend-app.test.js +++ b/test/frontend-app.test.js @@ -3451,4 +3451,39 @@ Também verificamos running command e compiling no buffer. freshDom.window.close(); } }); + + test('31. Eliminação de falso-positivo de thinking e captura indevida de prompt de shell no frontend mobile', async () => { + // 1. detectAgentThinking com prompts comuns de PowerShell / Bash / CMD + const psPrompt = 'Windows PowerShell\nCopyright (C) Microsoft Corporation.\n\nPS C:\\Users\\user\\MqlBots\\B3_TapeReader> '; + const resPs = window.detectAgentThinking(psPrompt, false); + assert.strictEqual(resPs.isThinking, false, 'PowerShell comum deve ter isThinking = false'); + assert.strictEqual(resPs.label, 'Pronto'); + + const psAnsiPrompt = '\x1b[32mPS C:\\Users\\user\\MqlBots\\B3_TapeReader>\x1b[0m '; + const resAnsi = window.detectAgentThinking(psAnsiPrompt, false); + assert.strictEqual(resAnsi.isThinking, false, 'PowerShell com ANSI deve ter isThinking = false'); + + const psWrappedPrompt = 'Windows PowerShell\nPS C:\\Users\\user\\MqlBots\\B3_T\napeReader>'; + const resWrapped = window.detectAgentThinking(psWrappedPrompt, false); + assert.strictEqual(resWrapped.isThinking, false, 'Prompt quebrado não deve ter isThinking = true'); + + const bashPrompt = 'user@linux:~/MqlBots/B3_TapeReader$ '; + const resBash = window.detectAgentThinking(bashPrompt, false); + assert.strictEqual(resBash.isThinking, false, 'Bash comum deve ter isThinking = false'); + + // 2. extractLatestAction não deve capturar prompts de shell como ação + assert.strictEqual(typeof window.extractLatestAction, 'function', 'extractLatestAction deve estar exposto em window'); + const actionPs = window.extractLatestAction(psPrompt); + assert.strictEqual(actionPs, '', 'Prompt do PowerShell não deve ser extraído como ação'); + + const actionWrapped = window.extractLatestAction(psWrappedPrompt); + assert.strictEqual(actionWrapped, '', 'Fragmento de prompt apeReader> não deve ser extraído como ação'); + + const actionCmd = window.extractLatestAction('C:\\Users\\user\\MqlBots\\B3_TapeReader> '); + assert.strictEqual(actionCmd, '', 'Prompt do CMD não deve ser extraído como ação'); + + // 3. extractLatestAction deve extrair ações reais quando presentes + const realAction = window.extractLatestAction('Antigravity CLI\n● Ran (npm test)\nExecutando testes'); + assert.match(realAction, /Ran \(npm test\)|Executando testes/, 'Ação real deve ser extraída normalmente'); + }); });