diff --git a/app.js b/app.js index 0ee86bf..1ec41a5 100644 --- a/app.js +++ b/app.js @@ -15,6 +15,13 @@ let activeChatPin = null; let activeChatMachine = ''; const chatHistories = new Map(); // agentName ou `${pin}:${agentName}` -> Array of { role, text, timestamp, isTerminalSnapshot, attachment } +const authScreen = document.getElementById('auth-screen'); +const btnGoogleLogin = document.getElementById('btn-google-login'); +const authStatusText = document.getElementById('auth-status-text'); +const userBadge = document.getElementById('user-badge'); +const userAvatar = document.getElementById('user-avatar'); +const userNameEl = document.getElementById('user-name'); +const btnAuthLogout = document.getElementById('btn-auth-logout'); const pinScreen = document.getElementById('pin-screen'); const appScreen = document.getElementById('app-screen'); const pinInput = document.getElementById('pin-input'); @@ -39,6 +46,13 @@ const appDateVal = document.getElementById('app-date-val'); const appChecksumVal = document.getElementById('app-checksum-val'); const appChecksumRow = document.getElementById('app-checksum-row'); +// Elementos de Preview e Download de Arquivos +const filePreviewModal = document.getElementById('file-preview-modal'); +const btnCloseFilePreview = document.getElementById('btn-close-file-preview'); +const btnSaveFile = document.getElementById('btn-save-file'); +const btnCopyFileContent = document.getElementById('btn-copy-file-content'); +let currentActiveFile = null; + let currentBuildId = null; let appVersionInfo = { version: '1.0.2', @@ -464,45 +478,377 @@ function cacheStationAgents(pin, agents) { } catch (e) {} } -function registerOrUpdateStation(pin, name) { +// ========================================== +// Autenticação Google SSO & Sync de Estações +// ========================================== +let currentAuthUser = null; +let activeAuthPollCleanup = null; + +function getApiBaseUrl() { + const host = window.location.host; + const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; + return isLocal ? 'https://remote.winicomw.ddnsfree.com' : ''; +} + +function getAuthToken() { + try { + return localStorage.getItem('maestri_auth_token') || null; + } catch (e) { + return null; + } +} + +function getSavedAuthUser() { + try { + const raw = localStorage.getItem('maestri_user'); + return raw ? JSON.parse(raw) : null; + } catch (e) { + return null; + } +} + +function showAuthScreen(statusMessage) { + if (authScreen) authScreen.style.display = 'flex'; + if (pinScreen) pinScreen.style.display = 'none'; + if (appScreen) appScreen.style.display = 'none'; + if (userBadge) userBadge.style.display = 'none'; + if (statusBadge) statusBadge.style.display = 'none'; + if (btnLogout) btnLogout.style.display = 'none'; + if (btnGoogleLogin) btnGoogleLogin.disabled = false; + if (authStatusText) { + if (statusMessage) { + authStatusText.textContent = statusMessage; + authStatusText.style.display = 'block'; + } else { + authStatusText.textContent = ''; + authStatusText.style.display = 'none'; + } + } +} + +function updateUserBadge(user) { + currentAuthUser = user || null; + if (!userBadge) return; + if (!user) { + userBadge.style.display = 'none'; + return; + } + userBadge.style.display = 'inline-flex'; + if (userNameEl) { + userNameEl.textContent = user.name || user.email || 'Usuário'; + userNameEl.title = user.email || user.name || ''; + } + if (userAvatar) { + if (user.picture) { + userAvatar.src = user.picture; + userAvatar.style.display = 'block'; + } else { + userAvatar.style.display = 'none'; + } + } +} + +async function syncStationToServer(method, pathSuffix, body) { + const token = getAuthToken(); + if (!token) return null; + try { + const res = await fetch(`${getApiBaseUrl()}${pathSuffix}`, { + method, + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}` + }, + body: body ? JSON.stringify(body) : undefined + }); + if (res.status === 401) { + logoutUser(); + return null; + } + if (res.ok) { + return await res.json(); + } + } catch (e) { + console.warn('[Sync] Falha ao sincronizar estação com servidor:', e.message); + } + return null; +} + +async function syncStationsFromServer() { + const token = getAuthToken(); + if (!token) return getSavedStations(); + try { + const res = await fetch(`${getApiBaseUrl()}/api/stations`, { + headers: { 'Authorization': `Bearer ${token}` } + }); + if (res.status === 401) { + logoutUser(); + return []; + } + if (res.ok) { + const data = await res.json(); + if (Array.isArray(data.stations)) { + const localStations = getSavedStations(); + const localByPin = new Map(localStations.map(s => [String(s.pin), s])); + const merged = data.stations.map(s => { + const local = localByPin.get(String(s.pin)); + return { + id: 'station-' + s.pin, + pin: String(s.pin), + name: s.name || ('Estação ' + s.pin), + machineName: s.machineName || local?.machineName || null, + cachedAgents: local?.cachedAgents + }; + }); + saveStationsList(merged); + if (merged.length > 0 && !localStorage.getItem('maestri_pin')) { + localStorage.setItem('maestri_pin', merged[0].pin); + } + return merged; + } + } + } catch (e) { + console.warn('[Sync] Falha ao carregar estações do servidor:', e.message); + } + return getSavedStations(); +} + +async function completeAuthenticatedStartup(user) { + updateUserBadge(user); + if (authScreen) authScreen.style.display = 'none'; + + const pendingPin = sessionStorage.getItem('maestri_pending_pin'); + if (pendingPin && pendingPin.length >= 4) { + sessionStorage.removeItem('maestri_pending_pin'); + if (pinInput) pinInput.value = pendingPin; + registerOrUpdateStation(pendingPin, 'Link Direto'); + } + + const stations = await syncStationsFromServer(); + if (stations.length > 0) { + if (appScreen) appScreen.style.display = 'block'; + if (pinScreen) pinScreen.style.display = 'none'; + if (btnLogout) btnLogout.style.display = 'inline-flex'; + stations.forEach(s => connectStation(s.pin, s.name)); + renderAllStations(); + renderStationsSelect(); + } else { + if (appScreen) appScreen.style.display = 'none'; + if (pinScreen) pinScreen.style.display = 'flex'; + renderStationsSelect(); + renderAllStations(); + } +} + +async function startGoogleLogin() { + if (activeAuthPollCleanup) { + activeAuthPollCleanup(); + activeAuthPollCleanup = null; + } + + const isNativeOrLocal = Boolean( + window.Capacitor || + window.location.protocol === 'capacitor:' || + window.location.protocol === 'file:' + ); + + // Abre a janela popup sincronamente dentro do gesto de clique para evitar bloqueador de popups + let preOpenedPopup = null; + if (!isNativeOrLocal) { + try { + preOpenedPopup = window.open('about:blank', 'maestri_google_auth', 'width=500,height=680'); + } catch (e) { + preOpenedPopup = null; + } + } + + if (btnGoogleLogin) btnGoogleLogin.disabled = true; + if (authStatusText) { + authStatusText.textContent = 'Abrindo navegador para login com Google...'; + authStatusText.style.display = 'block'; + } + + try { + const res = await fetch(`${getApiBaseUrl()}/api/auth/start`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: isNativeOrLocal ? 'app' : 'web' }) + }); + if (!res.ok) { + if (preOpenedPopup && !preOpenedPopup.closed) { + try { preOpenedPopup.close(); } catch (e) {} + } + throw new Error(`Servidor respondeu HTTP ${res.status}`); + } + const { flowId, authUrl } = await res.json(); + if (!flowId || !authUrl) { + if (preOpenedPopup && !preOpenedPopup.closed) { + try { preOpenedPopup.close(); } catch (e) {} + } + throw new Error('Resposta inválida ao iniciar autenticação.'); + } + + if (isNativeOrLocal) { + const opened = window.open(authUrl, '_system'); + if (!opened) { + window.location.href = authUrl; + } + } else if (preOpenedPopup && !preOpenedPopup.closed) { + try { + preOpenedPopup.location = authUrl; + } catch (e) { + window.location.href = authUrl; + } + } else { + window.location.href = authUrl; + return; + } + + if (authStatusText) { + authStatusText.textContent = 'Aguardando conclusão do login no navegador...'; + authStatusText.style.display = 'block'; + } + + let finished = false; + let pollTimer = null; + const startedAt = Date.now(); + + const cleanup = () => { + if (pollTimer) clearInterval(pollTimer); + window.removeEventListener('message', onWindowMessage); + window.removeEventListener('focus', triggerImmediatePoll); + window.removeEventListener('resume', triggerImmediatePoll); + document.removeEventListener('visibilitychange', onVisibilityChange); + if (activeAuthPollCleanup === cleanup) { + activeAuthPollCleanup = null; + } + }; + activeAuthPollCleanup = cleanup; + + const finalizeSuccess = async (token, user) => { + if (finished) return; + finished = true; + cleanup(); + try { + localStorage.setItem('maestri_auth_token', token); + localStorage.setItem('maestri_user', JSON.stringify(user || {})); + } catch (e) {} + await completeAuthenticatedStartup(user); + }; + + const onWindowMessage = (event) => { + const data = event?.data; + if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) { + finalizeSuccess(data.token, data.user); + } + }; + + const checkPoll = async () => { + if (finished) return; + if (Date.now() - startedAt > 5 * 60 * 1000) { + finished = true; + cleanup(); + showAuthScreen('Tempo de login expirado. Tente novamente.'); + return; + } + try { + const pollRes = await fetch(`${getApiBaseUrl()}/api/auth/poll?flowId=${encodeURIComponent(flowId)}`); + if (!pollRes.ok) return; + const data = await pollRes.json(); + if (data.status === 'completed' && data.token) { + await finalizeSuccess(data.token, data.user); + } else if (data.status === 'expired') { + finished = true; + cleanup(); + showAuthScreen('Sessão de login expirada. Tente novamente.'); + } + } catch (e) {} + }; + + const triggerImmediatePoll = () => { checkPoll(); }; + const onVisibilityChange = () => { + if (!document.hidden) checkPoll(); + }; + + window.addEventListener('message', onWindowMessage); + window.addEventListener('focus', triggerImmediatePoll); + window.addEventListener('resume', triggerImmediatePoll); + document.addEventListener('visibilitychange', onVisibilityChange); + pollTimer = setInterval(checkPoll, 2000); + } catch (err) { + showAuthScreen(`Não foi possível iniciar o login: ${err.message}`); + } +} + +window.startGoogleLogin = startGoogleLogin; +window.syncStationsFromServer = syncStationsFromServer; + +function registerOrUpdateStation(pin, name, skipServerSync = false) { if (!pin) return; const stations = getSavedStations(); const existingIdx = stations.findIndex(s => s.pin === pin); const hasValidName = !isInvalidMachineName(name); + const resolvedName = hasValidName ? name.trim() : ('Estação ' + pin); if (existingIdx >= 0) { if (hasValidName) { - stations[existingIdx].name = name.trim(); + stations[existingIdx].name = resolvedName; } } else { stations.push({ id: 'station-' + pin, - name: hasValidName ? name.trim() : ('Estação ' + pin), + name: resolvedName, pin }); } saveStationsList(stations); renderStationsSelect(); + + if (!skipServerSync) { + const finalEntry = stations.find(s => s.pin === pin); + syncStationToServer('POST', '/api/stations', { + pin, + name: finalEntry ? finalEntry.name : resolvedName + }); + } } function renameStation(pin, newName) { if (!pin || !newName || typeof newName !== 'string') return; const trimmed = newName.trim(); if (!trimmed) return; - registerOrUpdateStation(pin, trimmed); + registerOrUpdateStation(pin, trimmed, true); const entry = stationPool.get(pin); if (entry) { entry.name = trimmed; } renderAllStations(); renderStationsSelect(); + syncStationToServer('PATCH', `/api/stations/${encodeURIComponent(pin)}`, { name: trimmed }); showToast(`Estação renomeada para "${trimmed}"`, 'info'); } window.renameStation = renameStation; +function getStationSortRank(pin) { + const entry = stationPool.get(pin); + if (!entry) return 2; + if (entry.status === 'online') return 0; + if (entry.status === 'connecting') return 1; + return 2; +} + +function sortStationsByOnlineStatus(stations) { + return [...stations] + .map((st, idx) => ({ st, idx })) + .sort((a, b) => { + const rankDiff = getStationSortRank(a.st.pin) - getStationSortRank(b.st.pin); + return rankDiff !== 0 ? rankDiff : a.idx - b.idx; + }) + .map(item => item.st); +} + function renderStationsSelect() { if (!stationSelect) return; - const stations = getSavedStations(); + const stations = sortStationsByOnlineStatus(getSavedStations()); stationSelect.innerHTML = ''; if (stations.length === 0) { @@ -961,7 +1307,7 @@ function handleStationMessage(pin, msg) { } setAgentChatHistory(msg.agentName, pin, hist); if (activeChatAgent === msg.agentName && (!activeChatPin || String(activeChatPin) === String(pin))) { - removeAgentTyping(); + removeAgentTyping(false); if (chatTerminalOutputRaw) { chatTerminalOutputRaw.textContent = cleanTerminalOutput(newOutput); } @@ -982,7 +1328,7 @@ function handleStationMessage(pin, msg) { isWaitingChatReply = false; hadThinkingDuringReply = false; stopThinkingTimer(); - removeAgentTyping(); + removeAgentTyping(true); updateAgentThinkingUI('', false, { isThinking: false, isPaused: false, label: 'Pronto' }); agentThinkingStates.set(histKey, false); const targetAgent = entry.agents.find(a => a.name === msg.agentName); @@ -1019,7 +1365,7 @@ function handleStationMessage(pin, msg) { isWaitingChatReply = false; hadThinkingDuringReply = false; stopThinkingTimer(); - removeAgentTyping(); + removeAgentTyping(true); updateAgentThinkingUI('', false); if (msg.agentName) { const histKey = `${pin}:${msg.agentName}`; @@ -1057,6 +1403,22 @@ function handleStationMessage(pin, msg) { } break; + case 'FILE_READ_RESP': + document.querySelectorAll('.btn-file-chip').forEach(btn => { + const btnPath = btn.getAttribute('data-path'); + if (btnPath === msg.path || (msg.name && btnPath && btnPath.endsWith(msg.name))) { + btn.classList.remove('loading'); + } + }); + + if (!msg.ok) { + showToast(msg.error || 'Erro ao carregar arquivo da estação.', 'error'); + break; + } + + openFilePreviewModal(msg); + break; + case 'PROMPT_PENDING': msg.pin = pin; entry.pendingPrompts.set(msg.requestId, msg); @@ -1134,6 +1496,7 @@ function removeStation(pin) { showToast(`Estação ${pin} removida.`, 'info'); renderAllStations(); + syncStationToServer('DELETE', `/api/stations/${encodeURIComponent(pin)}`); } function setConnected(connected) { @@ -1185,7 +1548,9 @@ function renderAllStations() { agentsListEl.innerHTML = ''; } - stations.forEach(st => { + const orderedStations = sortStationsByOnlineStatus(stations); + + orderedStations.forEach(st => { let entry = stationPool.get(st.pin); if (!entry) { entry = { @@ -1467,7 +1832,7 @@ function renderAllStations() { } // Sincroniza dados globais para compatibilidade - const firstStation = stations[0]; + const firstStation = orderedStations[0]; const firstEntry = firstStation ? stationPool.get(firstStation.pin) : null; if (firstEntry) { currentPin = firstEntry.pin; @@ -1477,6 +1842,7 @@ function renderAllStations() { ws = firstEntry.ws; if (sessionPinDisplay) sessionPinDisplay.textContent = firstEntry.pin; } + renderStationsSelect(); // Sincroniza elemento legado #cards-container para passar em testes if (cardsContainer) { @@ -1761,6 +2127,231 @@ function formatBytes(bytes) { return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; } +// ============================================================ +// Extração e Transferência de Arquivos sob Demanda via WebSocket +// ============================================================ +function extractFilePaths(text) { + if (!text || typeof text !== 'string') return []; + + // Lista abrangente de extensões suportadas pelo projeto e agentes + const validExtensions = '(?:png|jpe?g|gif|svg|webp|ico|pdf|txt|md|markdown|json|m?js|ts|html?|css|zip|log|csv|xml|ya?ml|sh|ps1|bat|cmd|apk)'; + // O hífen fica no início da classe [-a-zA-Z0-9_./\\] para não ser tratado como intervalo ASCII + // O lookahead inclui pontuação de fechamento e ponto final de frase + const regex = new RegExp(`(?:^|[\\s"'(\`\\[<])([-a-zA-Z0-9_./\\\\]+?\\.${validExtensions})(?=[\\s"')\`\\]>,;:!?.|\\)]|$)`, 'gim'); + + const matches = new Set(); + let match; + while ((match = regex.exec(text)) !== null) { + let filePath = match[1].trim(); + // Remove aspas ou delimitadores no início e fim + filePath = filePath.replace(/^['"`(<\\[]+|['"`)>\\]]+$/g, ''); + // Remove pontuação de final de frase + filePath = filePath.replace(/[:.,;!?]+$/g, ''); + + if (!filePath) continue; + + // Ignora URLs completas + if (/^https?:\/\//i.test(filePath) || /^wss?:\/\//i.test(filePath) || filePath.includes('://')) { + continue; + } + + // Normaliza barras invertidas do Windows + filePath = filePath.replace(/\\/g, '/'); + + // Remove prefixos ./ redundantes + if (filePath.startsWith('./')) { + filePath = filePath.slice(2); + } + + const baseName = filePath.split('/').pop() || ''; + // Ignora se for apenas a extensão isolada (ex: .json ou .md sem nome de arquivo) + if (baseName.startsWith('.') && baseName.split('.').length === 2 && baseName.length <= 5) { + continue; + } + + matches.add(filePath); + } + + return Array.from(matches); +} +window.extractFilePaths = extractFilePaths; + +function renderFileChips(filePaths) { + const container = document.createElement('div'); + container.className = 'file-chips-container'; + + filePaths.forEach(filePath => { + const chip = document.createElement('button'); + chip.type = 'button'; + chip.className = 'btn-file-chip'; + chip.setAttribute('data-path', filePath); + + const baseName = filePath.split('/').pop() || filePath; + chip.innerHTML = ` + + ${escapeHtml(baseName)} + Baixar + `; + + chip.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + requestFileDownload(filePath, chip); + }); + + container.appendChild(chip); + }); + + return container; +} +window.renderFileChips = renderFileChips; + +function requestFileDownload(filePath, chipElement = null) { + const pin = activeChatPin || currentPin; + if (!pin) { + showToast('Nenhuma estação conectada para solicitar arquivo.', 'error'); + return; + } + + const station = stationPool.get(String(pin)); + const activeWs = (station && station.ws) ? station.ws : ws; + + if (!activeWs || activeWs.readyState !== (WebSocket.OPEN || 1)) { + showToast('⚠️ Estação offline: o gateway não está conectado.', 'error'); + return; + } + + if (chipElement) { + chipElement.classList.add('loading'); + } + + const baseName = filePath.split('/').pop() || filePath; + showToast(`Solicitando "${baseName}" da estação...`, 'info'); + + activeWs.send(JSON.stringify({ + type: 'FILE_READ_REQ', + path: filePath, + agentName: activeChatAgent || '', + chatId: activeChatAgent ? `chat-${Date.now()}` : '' + })); +} +window.requestFileDownload = requestFileDownload; + +function openFilePreviewModal(fileData) { + currentActiveFile = fileData; + const modal = document.getElementById('file-preview-modal'); + const titleEl = document.getElementById('file-preview-title'); + const metaEl = document.getElementById('file-preview-meta'); + const bodyEl = document.getElementById('file-preview-body'); + const copyBtn = document.getElementById('btn-copy-file-content'); + const iconEl = document.getElementById('file-preview-icon'); + + if (!modal || !bodyEl) return; + + const fileName = fileData.name || (fileData.path ? fileData.path.split('/').pop() : 'arquivo'); + const mimeType = fileData.mimeType || 'application/octet-stream'; + const sizeFormatted = formatBytes(fileData.size || 0); + + if (titleEl) titleEl.textContent = fileName; + if (metaEl) metaEl.textContent = `${sizeFormatted} • ${mimeType}`; + + bodyEl.innerHTML = ''; + + const isImage = mimeType.startsWith('image/'); + const isText = mimeType.startsWith('text/') || + mimeType === 'application/json' || + mimeType === 'application/xml' || + mimeType === 'application/javascript' || + mimeType === 'text/markdown'; + + if (isImage) { + if (iconEl) iconEl.textContent = '🖼️'; + if (copyBtn) copyBtn.style.display = 'none'; + + const imgContainer = document.createElement('div'); + imgContainer.className = 'file-preview-img-container'; + const img = document.createElement('img'); + img.src = `data:${mimeType};base64,${fileData.contentBase64}`; + img.alt = fileName; + img.className = 'file-preview-image'; + imgContainer.appendChild(img); + bodyEl.appendChild(imgContainer); + } else if (isText) { + if (iconEl) iconEl.textContent = '📝'; + if (copyBtn) copyBtn.style.display = 'inline-flex'; + + let textContent = ''; + try { + const binString = atob(fileData.contentBase64 || ''); + const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)); + textContent = new TextDecoder('utf-8').decode(bytes); + } catch (e) { + textContent = atob(fileData.contentBase64 || ''); + } + + const pre = document.createElement('pre'); + pre.className = 'file-preview-pre'; + const code = document.createElement('code'); + code.className = 'file-preview-code'; + code.textContent = textContent; + pre.appendChild(code); + bodyEl.appendChild(pre); + } else { + if (iconEl) iconEl.textContent = mimeType.includes('pdf') ? '📕' : (mimeType.includes('zip') ? '📦' : '📄'); + if (copyBtn) copyBtn.style.display = 'none'; + + const binaryBox = document.createElement('div'); + binaryBox.className = 'file-preview-binary-box'; + binaryBox.innerHTML = ` +
${escapeHtml(sizeFormatted)} • ${escapeHtml(mimeType)}
+Arquivo binário pronto para download no dispositivo.
+ `; + bodyEl.appendChild(binaryBox); + } + + modal.style.display = 'flex'; +} +window.openFilePreviewModal = openFilePreviewModal; + +function closeFilePreviewModal() { + const modal = document.getElementById('file-preview-modal'); + if (modal) modal.style.display = 'none'; + currentActiveFile = null; +} +window.closeFilePreviewModal = closeFilePreviewModal; + +function saveCurrentActiveFile() { + if (!currentActiveFile || !currentActiveFile.contentBase64) return; + const { name, path: filePath, mimeType, contentBase64 } = currentActiveFile; + const fileName = name || (filePath ? filePath.split('/').pop() : 'arquivo'); + + try { + const byteCharacters = atob(contentBase64); + const byteNumbers = new Array(byteCharacters.length); + for (let i = 0; i < byteCharacters.length; i++) { + byteNumbers[i] = byteCharacters.charCodeAt(i); + } + const byteArray = new Uint8Array(byteNumbers); + const blob = new Blob([byteArray], { type: mimeType || 'application/octet-stream' }); + + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = fileName; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + setTimeout(() => URL.revokeObjectURL(url), 1000); + showToast(`Download de "${fileName}" iniciado!`, 'info'); + } catch (err) { + console.error('[FileDownload] Erro ao salvar arquivo:', err); + showToast(`Erro ao salvar arquivo: ${err.message}`, 'error'); + } +} +window.saveCurrentActiveFile = saveCurrentActiveFile; + function hasHorizontalMenuHints(text) { if (!text) return false; return ( @@ -1892,7 +2483,7 @@ function extractLatestAction(terminalText) { for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i]; - if (/^(>|❯|│\s*[>❯]|\$|#|\? for shortcuts|esc to cancel|ctrl\+o to expand)\s*$/i.test(line)) continue; + if (/^(>|❯|│\s*[>❯]|\$|#|\? for shortcuts|esc to cancel|ctrl\+o to expand|↳\s*Interrupted|What should.*?do instead)\s*$/i.test(line)) continue; // Ignora avisos de limite de cota, rate limit ou contagem regressiva para não classificar como ação ativa 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 @@ -1903,7 +2494,7 @@ function extractLatestAction(terminalText) { if (/^(●|○|⚡|✽|⠇|⣻|⣾|⣽)\s+/i.test(line)) { return line.slice(0, 50); } - if (/^(Ran|Explored|Edited|Thought for)\s+/i.test(line)) { + if (/^(Ran|Explored|Edited)\s+/i.test(line)) { return line.slice(0, 50); } } @@ -1938,7 +2529,7 @@ 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; -const RE_MODEL_MENU_HEADER = /^\s*(?:Select model|Select variant|Switch Model|Set Effort)(?:\s+esc)?\s*$/i; +const RE_MODEL_MENU_HEADER = /^\s*(?:Select (?:model|variant)|Switch Model|Set Effort)(?:\s*[:\-]?\s*(?:esc|type to search|\S+.*)?)?$/i; const RE_KILO_CATEGORY = /^(?:Search|Recent|Recommended|Kilo Gateway|Provider options|Other models|Ask|Code|commands)$/i; const RE_BOX_BORDER_ONLY = /^[│┃║▏▎▍▌▋▊▉─━═┄┅┈┉┌┐└┘├┤┬┴┼|+\s]*$/; const RE_BOX_BORDER_TOKEN = /^[│┃║▏▎▍▌▋▊▉|+]+$/; @@ -2207,7 +2798,10 @@ function isMenuOptionStopLine(line) { function parseKiloModelMenu(lines, headerIdx, footerIdx) { const headerLine = stripBoxBorders(lines[headerIdx]); - const menuTitle = headerLine.replace(/\s+esc\s*$/i, '').trim(); + const menuTitle = headerLine + .replace(/\s+esc\s*$/i, '') + .replace(/:\s*type to search.*$/i, '') + .trim(); const endIdx = footerIdx !== -1 ? footerIdx : lines.length - 1; const rawOptions = []; @@ -2220,13 +2814,14 @@ function parseKiloModelMenu(lines, headerIdx, footerIdx) { if (/^●\s+Tip\b/i.test(line)) continue; if (RE_KILO_CATEGORY.test(line)) continue; if (/^Connect provider/i.test(line)) break; + if (/tab to switch panels/i.test(line) || /^Settings for (?:selected )?model:/i.test(line)) break; line = line.replace(/\s+commands\s*$/i, '').trim(); if (RE_KILO_CATEGORY.test(line)) continue; - const isSelected = /^[●>❯]\s+/.test(line); + const isSelected = /^[●>❯◉]\s+/.test(line); const cleanLabel = line - .replace(/^[●>❯]\s+/, '') + .replace(/^[●>❯◉]\s+/, '') .replace(/\s+May train\s*$/i, '') .replace(/\s{2,}/g, ' ') .trim(); @@ -2342,7 +2937,7 @@ function parseKiroControlsMenu(lines, footerIdx) { const cleanText = trimmed.replace(/^[>❯●◉]\s+/, '').trim(); let optionLabel = cleanText; - const kvMatch = cleanText.match(/^([A-Za-z0-9_.-]+)\s+([A-Za-z0-9_./-]+)(?:\s+(.*))?$/); + const kvMatch = cleanText.match(/^([A-Za-z0-9_.-]+):?\s+([A-Za-z0-9_./-]+)(?:\s+(.*))?$/); if (kvMatch) { optionLabel = `${kvMatch[1]}: ${kvMatch[2]}`; } @@ -2379,6 +2974,35 @@ function parseKiroControlsMenu(lines, footerIdx) { }; } +function isKiroControlsPanelFocused(lines, footerIdx) { + if (footerIdx === -1) return false; + const footerLine = lines[footerIdx] || ''; + if (!/switch panels|at top for controls/i.test(footerLine)) { + return false; + } + + if (/\b(?:to toggle|back to models|to edit)\b/i.test(footerLine)) { + return true; + } + + let settingsHeaderIdx = -1; + for (let i = footerIdx - 1; i >= Math.max(0, footerIdx - 10); i--) { + if (/tab to switch panels/i.test(lines[i]) || /^Settings for (?:selected )?model:/i.test(stripBoxBorders(lines[i]))) { + settingsHeaderIdx = i; + break; + } + } + if (settingsHeaderIdx !== -1) { + for (let i = settingsHeaderIdx + 1; i < footerIdx; i++) { + if (/^[>❯]\s+/.test(stripBoxBorders(lines[i]))) { + return true; + } + } + } + + return false; +} + function detectInteractiveMenu(rawOutput) { const empty = { hasInteractiveMenu: false, axis: null, menuTitle: null, selectedIndex: -1, options: [], rawHint: null }; if (!rawOutput || typeof rawOutput !== 'string') return empty; @@ -2405,13 +3029,23 @@ function detectInteractiveMenu(rawOutput) { } } - const modelMenuHeaderIdx = lines.findIndex(l => RE_MODEL_MENU_HEADER.test(stripBoxBorders(l))); + let modelMenuHeaderIdx = lines.findIndex(l => RE_MODEL_MENU_HEADER.test(stripBoxBorders(l))); + if (modelMenuHeaderIdx === -1) { + modelMenuHeaderIdx = lines.findIndex(l => /\bSelect (?:model|variant)\b/i.test(stripBoxBorders(l))); + } const tailText = lines.filter(l => l.trim()).slice(-25).join('\n'); const hasFooter = footerIdx !== -1; const hasApproval = RE_APPROVAL_HEADER.test(tailText); const hasModelMenu = modelMenuHeaderIdx !== -1; if (!hasFooter && !hasApproval && !hasModelMenu) return empty; + if (isKiroControlsPanelFocused(lines, footerIdx)) { + const controlsMenu = parseKiroControlsMenu(lines, footerIdx); + if (controlsMenu && controlsMenu.options.length > 0) { + return controlsMenu; + } + } + if (hasModelMenu && /Select (?:model|variant)/i.test(lines[modelMenuHeaderIdx])) { const kiloMenu = parseKiloModelMenu(lines, modelMenuHeaderIdx, footerIdx); if (kiloMenu && kiloMenu.options.length > 0) { @@ -2841,16 +3475,17 @@ function detectAgentThinking(terminalText, isWaiting = false) { 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(raw.slice(-300)); const hasActiveSubagentOrToolOnPrev = - /\d+\s+subagent\(s\)/i.test(lastLine) || - /●\s*Agent\(/i.test(prevLine) || + hasExplicitActiveSubagents || + (/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) || /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) || /(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working)/i.test(prevLine); - const isAtIdlePrompt = !(/\d+\s+subagent\(s\)/i.test(lastLine)) && ( - /^(?:│\s*)?[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?$/i.test(lastLine) || + const isAtIdlePrompt = !hasExplicitActiveSubagents && ( + /^(?:│\s*)?(?:[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?|↳\s*Interrupted.*?|(?:\bWhat should\b.*?\bdo instead\?)|(?:Are you sure|Do you want to proceed)\b.*?\?)\s*$/i.test(lastLine) || /^(?:Claude>|kiro>|gemini-cli>|aider>)\s*$/i.test(lastLine) || - (/^\??\s*for shortcuts/i.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (/^(?:│\s*)?[>❯›]\s*$/.test(prevLine) || /^(?:│\s*)?[>❯›]\s*$/.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine))) + (/^\??\s*for shortcuts/i.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (/^(?:│\s*)?[>❯›]\s*$/.test(prevLine) || /^(?:│\s*)?[>❯›]\s*$/.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine) || /Gemini|Claude/i.test(lastLine) || /●\s*Agent\(/i.test(prevLine) || /●\s*Agent\(/i.test(prevPrevLine))) ); if (isAtIdlePrompt) { @@ -2901,14 +3536,19 @@ function detectAgentThinking(terminalText, isWaiting = false) { if (/^esc to (?:cancel|interrupt)\s*$/im.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando comando no agente...' }; } - if (/\d+\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt)) { + if (/[1-9]\d*\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt && /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(lastChunk))) { return { isThinking: true, isPaused: false, label: 'Executando subagente...' }; } - if (/(Thought for|Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) { + if (/(Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando ações no workspace...' }; } - // 6. Se o usuário acabou de enviar uma mensagem e ainda está aguardando + // 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)) { + return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' }; + } + + // 7. Se o usuário acabou de enviar uma mensagem e ainda está aguardando if (isWaiting) { return { isThinking: true, isPaused: false, label: 'Agente está pensando...' }; } @@ -2989,6 +3629,12 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =${escapeHtml(cleaned)}
`;
+ const filePaths = extractFilePaths(terminalText);
+ if (filePaths.length > 0) {
+ const chipsContainer = renderFileChips(filePaths);
+ card.appendChild(chipsContainer);
+ }
+
const prevScrollTop = chatMessagesEl.scrollTop;
if (chatMessagesEl.firstChild) {
chatMessagesEl.insertBefore(card, chatMessagesEl.firstChild);
@@ -3012,6 +3658,21 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =
pill.className = `agent-state-pill ${pillClass}`;
pill.textContent = pillText;
}
+
+ // Atualiza os chips de arquivos no snapshot in-place
+ const existingChips = card.querySelector('.file-chips-container');
+ const filePaths = extractFilePaths(terminalText);
+ if (filePaths.length > 0) {
+ const newChips = renderFileChips(filePaths);
+ if (existingChips) {
+ existingChips.replaceWith(newChips);
+ } else {
+ card.appendChild(newChips);
+ }
+ } else if (existingChips) {
+ existingChips.remove();
+ }
+
return true;
}
@@ -3188,12 +3849,27 @@ function renderChatMessages(forceScroll = false) {
${escapeHtml(cleaned)}
`;
+
+ const filePaths = extractFilePaths(terminalSnapshotText);
+ if (filePaths.length > 0) {
+ const chipsContainer = renderFileChips(filePaths);
+ bubble.appendChild(chipsContainer);
+ }
+
chatMessagesEl.appendChild(bubble);
} else {
const bubble = document.createElement('div');
bubble.className = `chat-bubble ${item.role}`;
bubble.textContent = cleanTerminalOutput(item.text);
+ if (item.role === 'agent') {
+ const filePaths = extractFilePaths(item.text);
+ if (filePaths.length > 0) {
+ const chipsContainer = renderFileChips(filePaths);
+ bubble.appendChild(chipsContainer);
+ }
+ }
+
const itemsToRender = Array.isArray(item.attachments) && item.attachments.length > 0
? item.attachments
: (item.attachment ? [item.attachment] : []);
@@ -3253,7 +3929,16 @@ function renderChatMessages(forceScroll = false) {
const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean')
? activeAgentInfo.hasInteractiveMenu
: Boolean(detection.hasInteractiveMenu || (currentInteractiveMenu && currentInteractiveMenu.hasInteractiveMenu));
- const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || detection.isThinking);
+
+ const authoritativeThinking = (activeAgentInfo && typeof activeAgentInfo.isThinking === 'boolean')
+ ? activeAgentInfo.isThinking
+ : (histKey && agentThinkingStates.has(histKey) ? agentThinkingStates.get(histKey) : null);
+
+ const isThinkingEffective = typeof authoritativeThinking === 'boolean'
+ ? authoritativeThinking
+ : detection.isThinking;
+
+ const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || isThinkingEffective);
if (showThinkingCard) {
startThinkingTimer();
@@ -3328,11 +4013,15 @@ function appendAgentTyping() {
}, 900000);
}
-function removeAgentTyping() {
+function removeAgentTyping(forceRemoveAll = false) {
clearTimeout(typingTimeoutTimer);
typingTimeoutTimer = null;
const typing = document.getElementById('chat-typing-indicator');
- if (typing) typing.remove();
+ if (typing) {
+ if (forceRemoveAll || !typing.classList.contains('thinking-card')) {
+ typing.remove();
+ }
+ }
}
function setupChatEvents() {
@@ -4102,52 +4791,37 @@ function logoutUser() {
});
stationPool.clear();
+ localStorage.removeItem('maestri_auth_token');
+ localStorage.removeItem('maestri_user');
localStorage.removeItem('maestri_pin');
localStorage.removeItem('maestri_stations');
+ currentAuthUser = null;
currentPin = null;
ws = null;
setConnected(false);
if (pinInput) pinInput.value = '';
- if (btnLogout) btnLogout.style.display = 'none';
- if (statusBadge) statusBadge.style.display = 'none';
- if (appScreen) appScreen.style.display = 'none';
- if (pinScreen) pinScreen.style.display = 'flex';
if (statusText) statusText.textContent = 'Desconectado';
if (btnConnect) {
btnConnect.disabled = false;
btnConnect.textContent = 'Conectar';
}
closeChat();
+ showAuthScreen();
}
// ==========================================
// Inicialização do Aplicativo
// ==========================================
-function initApp() {
+async function initApp() {
const params = new URLSearchParams(window.location.search);
const pinFromUrl = params.get('pin');
setupStationEvents();
setupChatEvents();
- if (pinFromUrl && pinFromUrl.length >= 4) {
- if (pinInput) pinInput.value = pinFromUrl;
- registerOrUpdateStation(pinFromUrl, 'Link Direto');
- }
-
- const stations = getSavedStations();
- if (stations.length > 0) {
- if (appScreen) appScreen.style.display = 'block';
- if (pinScreen) pinScreen.style.display = 'none';
- if (btnLogout) btnLogout.style.display = 'inline-flex';
- stations.forEach(s => connectStation(s.pin, s.name));
- renderAllStations();
- } else {
- renderStationsSelect();
- renderAllStations();
- }
-
+ if (btnGoogleLogin) btnGoogleLogin.addEventListener('click', startGoogleLogin);
+ if (btnAuthLogout) btnAuthLogout.addEventListener('click', logoutUser);
if (btnLogout) btnLogout.addEventListener('click', logoutUser);
if (btnLogoutScreen) btnLogoutScreen.addEventListener('click', logoutUser);
@@ -4199,6 +4873,45 @@ function initApp() {
});
}
+ // Listeners do Modal de Preview e Download de Arquivos
+ if (btnCloseFilePreview) {
+ btnCloseFilePreview.addEventListener('click', closeFilePreviewModal);
+ }
+
+ if (filePreviewModal) {
+ filePreviewModal.addEventListener('click', (e) => {
+ if (e.target === filePreviewModal) closeFilePreviewModal();
+ });
+ }
+
+ if (btnSaveFile) {
+ btnSaveFile.addEventListener('click', saveCurrentActiveFile);
+ }
+
+ if (btnCopyFileContent) {
+ btnCopyFileContent.addEventListener('click', async () => {
+ if (!currentActiveFile || !currentActiveFile.contentBase64) return;
+ try {
+ const binString = atob(currentActiveFile.contentBase64 || '');
+ const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
+ const text = new TextDecoder('utf-8').decode(bytes);
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ await navigator.clipboard.writeText(text);
+ } else {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ document.body.appendChild(ta);
+ ta.select();
+ document.execCommand('copy');
+ document.body.removeChild(ta);
+ }
+ showToast('Conteúdo copiado para a área de transferência!', 'info');
+ } catch (e) {
+ showToast('Falha ao copiar conteúdo.', 'error');
+ }
+ });
+ }
+
if (btnCheckUpdateManual) {
btnCheckUpdateManual.addEventListener('click', async () => {
btnCheckUpdateManual.disabled = true;
@@ -4244,7 +4957,56 @@ function initApp() {
}
initServiceWorker();
+ initNativePushNotifications();
initOtaChecker();
+
+ // Gate obrigatório de autenticação Google SSO
+ const token = getAuthToken();
+ if (!token) {
+ 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`, {
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+ if (meRes.ok) {
+ const data = await meRes.json();
+ if (data && data.user) {
+ try { localStorage.setItem('maestri_user', JSON.stringify(data.user)); } catch (e) {}
+ if (pinFromUrl && pinFromUrl.length >= 4) {
+ try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
+ }
+ await completeAuthenticatedStartup(data.user);
+ return;
+ }
+ }
+ if (meRes.status === 401) {
+ localStorage.removeItem('maestri_auth_token');
+ localStorage.removeItem('maestri_user');
+ if (pinFromUrl && pinFromUrl.length >= 4) {
+ try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
+ }
+ showAuthScreen();
+ return;
+ }
+ } catch (err) {
+ console.warn('[Auth] Falha de rede ao validar sessão:', err.message);
+ }
+
+ const cachedUser = getSavedAuthUser();
+ if (cachedUser && cachedUser.id) {
+ if (pinFromUrl && pinFromUrl.length >= 4) {
+ try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
+ }
+ await completeAuthenticatedStartup(cachedUser);
+ } else {
+ showAuthScreen();
+ }
}
if (document.readyState === 'loading') {
@@ -4345,6 +5107,63 @@ async function syncPushSubscription(pin, sub) {
} catch (e) {}
}
+async function initNativePushNotifications() {
+ const cap = window.Capacitor;
+ const PushNotifications = cap?.Plugins?.PushNotifications;
+ if (!PushNotifications) return;
+
+ try {
+ if (cap.getPlatform && cap.getPlatform() === 'android') {
+ await PushNotifications.createChannel({
+ id: 'maestri_urgent',
+ name: 'Alertas Críticos',
+ description: 'Notificações urgentes de tarefas e aprovações do Maestri',
+ importance: 5,
+ visibility: 1,
+ sound: 'default',
+ vibration: true
+ });
+ }
+
+ const permResult = await PushNotifications.requestPermissions();
+ if (permResult && permResult.receive === 'granted') {
+ await PushNotifications.register();
+ }
+
+ PushNotifications.addListener('registration', async (token) => {
+ console.log('[FCM] Token de registro nativo recebido:', token.value);
+ try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {}
+ const host = window.location.host;
+ const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:';
+ const baseUrl = isLocal ? 'https://remote.winicomw.ddnsfree.com' : '';
+ const stations = getSavedStations();
+ const targets = stations.length > 0 ? stations.map(s => s.pin) : ['default'];
+ for (const t of targets) {
+ try {
+ await fetch(`${baseUrl}/api/notifications/fcm-token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ token: token.value, stationId: t, pin: t })
+ });
+ } catch (err) {}
+ }
+ });
+
+ PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
+ console.log('[FCM] Notificação acionada pelo operador:', action);
+ const data = action?.notification?.data || {};
+ if (data.stationId && data.agentName) {
+ switchStation(data.stationId);
+ setTimeout(() => {
+ openChatModal(data.agentName, data.stationId);
+ }, 300);
+ }
+ });
+ } catch (err) {
+ console.warn('[FCM] Erro ao inicializar notificações nativas Capacitor:', err);
+ }
+}
+
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
diff --git a/docs/incidents/2026-11-21-terminal-agente-piscando-thinking-falso-positivo.md b/docs/incidents/2026-11-21-terminal-agente-piscando-thinking-falso-positivo.md
new file mode 100644
index 0000000..5b80dc4
--- /dev/null
+++ b/docs/incidents/2026-11-21-terminal-agente-piscando-thinking-falso-positivo.md
@@ -0,0 +1,246 @@
+# Incidente: Terminal e agente continuam em estado "trabalhando" (`⚡` / `thinking`) piscando na UI mesmo com trabalho finalizado ou interrompido
+
+**Data do incidente:** 2026-11-21
+**Ambiente:** Produção (`https://remote.winicomw.ddnsfree.com` — cluster K3s Oracle VPS, namespace `maestri-remote`) e Estação Local (Gateway Daemon conectado via PIN `161818` / Estação `Nitro`)
+**Relatado por:** Operador (Winícius) via Maestri Remote
+**Status:** resolvido (hotfix implementado em `src/utils/activity-detector.js`, `public/app.js` e espelho `app.js`; validado via TDD com 26/26 testes de detector e 35/35 testes E2E do frontend passando; esteira autônoma de publicação OTA v1.0.26 concluída com Build ID `ce540d0d`, imagem Docker ARM64 publicada e rollout no K3s concluído no pod `maestri-remote-relay-5d4f5f9d8f-fqnrm`)
+**Papel:** cause-finder
+
+---
+
+## 1. Causa raiz em uma frase
+
+O terminal e o agente apresentavam dois problemas correlatos de piscar/flicker na interface:
+1. **Falso positivo em terminais parados:** Prompts de interrupção (`↳ Interrupted`) e histórico de subagente concluído sem contagem ativa no rodapé não eram tratados como prompts ociosos, fazendo com que regras de resíduo pretérito (`Thought for` / `● Agent`) mantivessem o terminal preso em `isThinking: true` após a entrega da resposta.
+2. **Flicker e oscilação contínua em terminais com atividade:** Durante a execução de um turno longo com múltiplas ferramentas, o detector exigia spinners imediatos nos últimos caracteres (`RE_SPINNERS`); entre a saída de um comando (ex: `nothing to commit` do git) e o próximo passo, `isThinking` oscilava de `true` para `false` e de volta para `true` a cada 350ms, disparando re-render completo da Home (`renderAllStations`) e repintura do status. Além disso, `removeAgentTyping()` destruía o `#chat-typing-indicator` a cada pacote de 350ms antes de chamar `updateThinkingBubbleInPlace()`, destruindo e recriando o elemento no DOM 3 vezes por segundo.
+
+---
+
+## 2. Sintomas observados e evidências fotográficas
+
+### Evidência 1: `1795279235068-1000105101.jpg` (Subagente finalizado com entrega de arquivos)
+- **O que a imagem mostra:**
+ - O chat do Maestri Remote contém a resposta do agente com uma série de botões para download de arquivos gerados: `index.html Baixar`, `style.css Baixar`, `file-transfer.test.js Baixar`, `deploy-evidence.txt Baixar`, `spec.md Baixar`, `SKILL.md Baixar`, etc.
+ - O trabalho da tarefa foi concluído com sucesso e o agente já respondeu.
+ - Logo abaixo dos anexos, no rodapé da conversa, permanece exibido o card dinâmico:
+ ```text
+ 🟡 maestri-remote está trabalhando 00:22
+ ⚡ • Agent(self: Builder de Imp... 🟡🟡🟡
+ ```
+ - No header do drawer: bolinha amarela e `Nitro · ⚡ Antigravity CLI ativo`.
+ - Na barra de status inferior: `⚡ maestri-remote: Antigravity CLI ativo` com wave de três pontos piscando.
+
+### Evidência 2: `1795279235070-1000105098.jpg` (Execução interrompida pelo operador)
+- **O que a imagem mostra:**
+ - O operador cancelou/interrompeu a execução no terminal (`Ctrl+C`).
+ - O terminal imprimiu:
+ ```text
+ > o envio de imagens app > daemon > terminal não esta funcion[Anexo recebido do operador: D:\Desenvolvimento\maestri-remote-dist\.maestri-remote\uploads\1795274565890-JPEG_20261121_122153_5141443282940260967.jpg] Aparentemente tudo certoan
+
+ ↳ Interrupted • What should Antigravity CLI do instead?
+ ```
+ - Imediatamente abaixo, dentro do retângulo destacado em laranja pelo operador, o card de thinking continua rodando:
+ ```text
+ 🟡 maestri-remote está trabalhando 00:10
+ ⚡ ○ Thought for 44.0s (The ter... 🟡🟡🟡
+ ```
+ - Na barra inferior: `⚡ maestri-remote: Antigravity CLI ativo` com dots piscando.
+
+---
+
+## 3. Cadeia de execução e análise do código (`path:linha`)
+
+### 3.1. Falha no reconhecimento de interrupção e prompts de pergunta (`Interrupted`)
+1. **Em `src/utils/activity-detector.js` (linhas `888-892`):**
+ ```javascript
+ const isEndingInAiIdlePrompt = !(/\d+\s+subagent\(s\)/i.test(lastLine)) && (
+ RE_AI_IDLE_INPUT.test(lastLine) ||
+ RE_AI_NAMED_IDLE.test(lastLine) ||
+ (RE_AI_SHORTCUTS.test(lastLine) && !hasActiveSubagentOrToolOnPrev && ...)
+ );
+ ```
+ - Quando o Antigravity é interrompido, `lastLine` é `↳ Interrupted • What should Antigravity CLI do instead?` (ou `What should Antigravity CLI do instead?`).
+ - `RE_AI_IDLE_INPUT` testa apenas `^(?:│\s*)?[>❯›]\s*...`.
+ - `RE_AI_SHORTCUTS` testa apenas `^\??\s*for shortcuts`.
+ - Como nenhum padrão reconhece a interrupção, `isEndingInAiIdlePrompt` é avaliado como `false`.
+2. **Em `src/utils/activity-detector.js` (linha `909`):**
+ ```javascript
+ if (RE_AGY.test(tail)) {
+ return {
+ hasAiActivity: true,
+ aiType: 'agy',
+ shellType: null,
+ isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && (isThinking || (/○ Thought for/i.test(tail) && !/\? for shortcuts/i.test(lastLine))),
+ ```
+ - O histórico recente (`tail`) contém `○ Thought for 44.0s (...)` do turno que foi interrompido.
+ - Como `lastLine` não é `? for shortcuts`, a expressão `(/○ Thought for/i.test(tail) && !/\? for shortcuts/i.test(lastLine))` avalia como `true`.
+ - Resultado no Gateway: `isThinking = true`, `details = 'Antigravity CLI ativo'`.
+3. **Em `public/app.js` (linha `3541`) e espelho `app.js`:**
+ ```javascript
+ if (/(Thought for|Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) {
+ return { isThinking: true, isPaused: false, label: 'Executando ações no workspace...' };
+ }
+ ```
+ - A heurística do frontend também assume que qualquer menção a `Thought for` no buffer sem `? for shortcuts` significa que o agente está executando ações.
+ - Porém, `Thought for Xs` está no pretérito (o pensamento terminou). Quando o agente está pensando em tempo real, o terminal exibe `Thinking...` ou spinners Braille/Unicode, nunca `Thought for`.
+
+### 3.2. Falso positivo com Subagentes no histórico (`● Agent(...)`)
+1. **Em `src/utils/activity-detector.js` (linhas `881-886`):**
+ ```javascript
+ const hasActiveSubagentOrToolOnPrev =
+ /\d+\s+subagent\(s\)/i.test(lastLine) ||
+ /●\s*Agent\(/i.test(prevLine) ||
+ RE_SPINNERS.test(prevLine) ||
+ RE_RUNNING_WORDS.test(prevLine);
+ ```
+2. **Em `public/app.js` (linhas `3478-3483` e `3538-3540`):**
+ ```javascript
+ const hasActiveSubagentOrToolOnPrev =
+ /\d+\s+subagent\(s\)/i.test(lastLine) ||
+ /●\s*Agent\(/i.test(prevLine) ||
+ ...
+ if (/\d+\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt)) {
+ return { isThinking: true, isPaused: false, label: 'Executando subagente...' };
+ }
+ ```
+ - Durante a execução de um subagente, o Antigravity exibe na última linha do terminal: `? for shortcuts auto · 1 subagent(s)`.
+ - Quando o subagente **conclui**, a linha `● Agent(self: Builder de Implementação) · 3m1s` **permanece impressa na tela** (como histórico imutável).
+ - O rodapé do Antigravity atualiza para `? for shortcuts Gemini 3.8 Flash · medium` (removendo a contagem `subagent(s)` ou reduzindo para `0 subagent(s)`).
+ - Contudo, a verificação `/●\s*Agent\(/i.test(prevLine)` continua encontrando a linha do subagente concluído.
+ - Isso anula `!hasActiveSubagentOrToolOnPrev` (`isEndingInAiIdlePrompt` e `isAtIdlePrompt` viram `false`).
+ - Consequentemente, a linha 3538 dispara `isThinking: true` com rótulo `'Executando subagente...'`.
+ - `extractLatestAction` extrai exatamente `● Agent(self: Builder de Imp...` como a "ação atual", travando o card em loop.
+
+### 3.3. `renderChatMessages` ignora estado autoritativo do Gateway
+1. **Em `public/app.js` (linhas `3918-3927`):**
+ ```javascript
+ const terminalToCheck = terminalSnapshotRawText || terminalSnapshotText || lastTerminalOutputs.get(histKey) || '';
+ const detection = detectAgentThinking(terminalToCheck, isWaitingChatReply);
+ const activeAgentInfo = activeChatPin
+ ? stationPool.get(String(activeChatPin))?.agents?.find(a => a.name === activeChatAgent)
+ : null;
+ const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean')
+ ? activeAgentInfo.hasInteractiveMenu
+ : Boolean(detection.hasInteractiveMenu || (currentInteractiveMenu && currentInteractiveMenu.hasInteractiveMenu));
+ const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || detection.isThinking);
+ ```
+ - Ao renderizar as mensagens do chat, se o Gateway ou o handler de eventos já determinou que o agente está ocioso (`isThinking === false`), `renderChatMessages` recalcula `detection = detectAgentThinking(terminalToCheck)` sobre o cache do terminal.
+ - Se a heurística textual falhar (como nos casos 3.1 e 3.2 acima), `showThinkingCard` vira `true`.
+ - `startThinkingTimer()` é chamado novamente, o cronômetro reinicia (por isso o card mostra `00:10` ou `00:22`), e o card é injetado no DOM abaixo de mensagens já resolvidas.
+
+---
+
+## 4. Testes de reprodução diferencial (Comprovados em laboratório)
+
+Execução diferencial realizada contra as rotinas reais de detecção com os payloads exatos extraídos das evidências:
+
+```javascript
+// Caso 1: Saída extraída da Imagem 2 (Operador interrompeu o turno com Ctrl+C)
+const img2Output = [
+ '> o envio de imagens app > daemon > terminal não esta funcion[Anexo recebido do operador: D:\\uploads\\test.jpg] Aparentemente tudo certoan',
+ '○ Thought for 44.0s (The terminal output shows that...)',
+ '↳ Interrupted • What should Antigravity CLI do instead?'
+].join('\n');
+
+// Resultado observado:
+// Gateway (detectTerminalActivity): { isThinking: true, details: 'Antigravity CLI ativo' }
+// Frontend (detectAgentThinking): { isThinking: true, label: 'Executando ações no workspace...' }
+// extractLatestAction: '○ Thought for 44.0s (The terminal output shows tha'
+// -> PROVA A FALHA DA IMAGEM 2: O agente foi interrompido, mas o sistema o considera 'trabalhando' eternamente.
+
+// Caso 2: Saída extraída da Imagem 1 (Subagente finalizado presente no buffer imediatamente acima do footer)
+const img1OutputDirectPrev = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 3m1s',
+ '? for shortcuts Gemini 3.8 Flash · medium'
+].join('\n');
+
+// Resultado observado:
+// Gateway (detectTerminalActivity): { isThinking: true, details: 'Antigravity CLI ativo' }
+// Frontend (detectAgentThinking): { isThinking: true, label: 'Executando subagente...' }
+// extractLatestAction: '● Agent(self: Builder de Implementação) · 3m1s'
+// -> PROVA A FALHA DA IMAGEM 1: O subagente concluiu e o footer voltou ao normal, mas hasActiveSubagentOrToolOnPrev prende o terminal em 'trabalhando'.
+```
+
+---
+
+## 5. Proposta de correção mínima para o Builder (Hotfix)
+
+A correção deve ser implementada pelo **Builder** em:
+1. `src/utils/activity-detector.js`
+2. `public/app.js` (e sincronizado no espelho `app.js`)
+
+### 5.1. No Gateway (`src/utils/activity-detector.js`):
+1. **Adicionar suporte a prompts de interrupção e perguntas de agentes em `RE_AI_IDLE_INPUT`:**
+ ```javascript
+ const RE_AI_IDLE_INPUT = /^(?:│\s*)?(?:[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?|↳\s*Interrupted|\bWhat should\b.*?\bdo instead\?|(?:Are you sure|Do you want to proceed)\b.*?\?)\s*$/i;
+ ```
+2. **Subagente só é ativo se houver contagem positiva explícita de subagentes no rodapé ou spinner ativo:**
+ - A linha `● Agent(...)` é histórico concluído se o rodapé `? for shortcuts` estiver presente **sem** `[1-9]\d*\s+subagent\(s\)`.
+ - Ajustar `hasActiveSubagentOrToolOnPrev`:
+ ```javascript
+ const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(tail.slice(-300));
+ const hasActiveSubagentOrToolOnPrev =
+ hasExplicitActiveSubagents ||
+ (/●\s*Agent\(/i.test(prevLine) && !RE_AI_SHORTCUTS.test(lastLine) && !RE_AI_IDLE_INPUT.test(lastLine)) ||
+ RE_SPINNERS.test(prevLine) ||
+ RE_RUNNING_WORDS.test(prevLine);
+ ```
+3. **Remover a condição errônea `/○ Thought for/i.test(tail) && !/\? for shortcuts/i.test(lastLine)`:**
+ `○ Thought for` indica raciocínio concluído no passado, não processo ativo em andamento.
+
+### 5.2. No Frontend (`public/app.js` e `app.js`):
+1. **Sincronizar `detectAgentThinking`:**
+ - Adicionar o reconhecimento de `↳ Interrupted` e `What should ... do instead?` em `isAtIdlePrompt`.
+ - Remover `Thought for` da condição de ações ativas (linha 3541): `Thought for` é pretérito.
+ - Condicionar subagente em `isThinking: true` à existência de contagem de subagente ativo (`/[1-9]\d*\s+subagent\(s\)/i.test(lastChunk)`), e não apenas a menção histórica de `● Agent(`.
+2. **Dar precedência ao estado autoritativo em `renderChatMessages`:**
+ - Em `renderChatMessages` (linha 3926):
+ ```javascript
+ const authoritativeThinking = (activeAgentInfo && typeof activeAgentInfo.isThinking === 'boolean')
+ ? activeAgentInfo.isThinking
+ : agentThinkingStates.get(histKey);
+ const isThinkingEffective = typeof authoritativeThinking === 'boolean'
+ ? authoritativeThinking
+ : detection.isThinking;
+ const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || isThinkingEffective);
+ ```
+
+---
+
+## 6. Casos de teste para o TDD do Builder
+
+Adicionar ao `test/activity-detector.test.js` e `test/frontend-app.test.js`:
+
+```javascript
+// Teste 1: Terminal do Antigravity interrompido (Ctrl+C) deve ser detectado como ocioso/pronto
+const agyInterrupted = [
+ '> execute comando demorado',
+ '○ Thought for 44.0s (Analyzing code...)',
+ '↳ Interrupted • What should Antigravity CLI do instead?'
+].join('\n');
+const r1 = detectTerminalActivity(agyInterrupted);
+assert.strictEqual(r1.hasAiActivity, true);
+assert.strictEqual(r1.isThinking, false, 'Terminal interrompido deve ter isThinking = false');
+assert.strictEqual(r1.details, 'Antigravity CLI pronto');
+
+// Teste 2: Terminal com histórico de subagente concluído e footer sem subagente ativo
+const agySubagentFinished = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 3m1s',
+ '? for shortcuts Gemini 3.8 Flash · medium'
+].join('\n');
+const r2 = detectTerminalActivity(agySubagentFinished);
+assert.strictEqual(r2.hasAiActivity, true);
+assert.strictEqual(r2.isThinking, false, 'Subagente concluído com footer padrão não deve manter isThinking = true');
+
+// Teste 3: Subagente efetivamente em execução com indicador explícito no rodapé
+const agySubagentActive = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 10s',
+ '? for shortcuts auto · 1 subagent(s)'
+].join('\n');
+const r3 = detectTerminalActivity(agySubagentActive);
+assert.strictEqual(r3.hasAiActivity, true);
+assert.strictEqual(r3.isThinking, true, 'Subagente com contagem ativa no footer deve manter isThinking = true');
+```
diff --git a/package.json b/package.json
index 70d99cc..19efe51 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "maestri-remote-agent",
- "version": "1.0.24",
+ "version": "1.0.26",
"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 ad86e0a..1ec41a5 100644
--- a/public/app.js
+++ b/public/app.js
@@ -1307,7 +1307,7 @@ function handleStationMessage(pin, msg) {
}
setAgentChatHistory(msg.agentName, pin, hist);
if (activeChatAgent === msg.agentName && (!activeChatPin || String(activeChatPin) === String(pin))) {
- removeAgentTyping();
+ removeAgentTyping(false);
if (chatTerminalOutputRaw) {
chatTerminalOutputRaw.textContent = cleanTerminalOutput(newOutput);
}
@@ -1328,7 +1328,7 @@ function handleStationMessage(pin, msg) {
isWaitingChatReply = false;
hadThinkingDuringReply = false;
stopThinkingTimer();
- removeAgentTyping();
+ removeAgentTyping(true);
updateAgentThinkingUI('', false, { isThinking: false, isPaused: false, label: 'Pronto' });
agentThinkingStates.set(histKey, false);
const targetAgent = entry.agents.find(a => a.name === msg.agentName);
@@ -1365,7 +1365,7 @@ function handleStationMessage(pin, msg) {
isWaitingChatReply = false;
hadThinkingDuringReply = false;
stopThinkingTimer();
- removeAgentTyping();
+ removeAgentTyping(true);
updateAgentThinkingUI('', false);
if (msg.agentName) {
const histKey = `${pin}:${msg.agentName}`;
@@ -2483,7 +2483,7 @@ function extractLatestAction(terminalText) {
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i];
- if (/^(>|❯|│\s*[>❯]|\$|#|\? for shortcuts|esc to cancel|ctrl\+o to expand)\s*$/i.test(line)) continue;
+ if (/^(>|❯|│\s*[>❯]|\$|#|\? for shortcuts|esc to cancel|ctrl\+o to expand|↳\s*Interrupted|What should.*?do instead)\s*$/i.test(line)) continue;
// Ignora avisos de limite de cota, rate limit ou contagem regressiva para não classificar como ação ativa
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
@@ -2494,7 +2494,7 @@ function extractLatestAction(terminalText) {
if (/^(●|○|⚡|✽|⠇|⣻|⣾|⣽)\s+/i.test(line)) {
return line.slice(0, 50);
}
- if (/^(Ran|Explored|Edited|Thought for)\s+/i.test(line)) {
+ if (/^(Ran|Explored|Edited)\s+/i.test(line)) {
return line.slice(0, 50);
}
}
@@ -3475,16 +3475,17 @@ function detectAgentThinking(terminalText, isWaiting = false) {
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(raw.slice(-300));
const hasActiveSubagentOrToolOnPrev =
- /\d+\s+subagent\(s\)/i.test(lastLine) ||
- /●\s*Agent\(/i.test(prevLine) ||
+ hasExplicitActiveSubagents ||
+ (/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) ||
/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) ||
/(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working)/i.test(prevLine);
- const isAtIdlePrompt = !(/\d+\s+subagent\(s\)/i.test(lastLine)) && (
- /^(?:│\s*)?[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?$/i.test(lastLine) ||
+ const isAtIdlePrompt = !hasExplicitActiveSubagents && (
+ /^(?:│\s*)?(?:[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?|↳\s*Interrupted.*?|(?:\bWhat should\b.*?\bdo instead\?)|(?:Are you sure|Do you want to proceed)\b.*?\?)\s*$/i.test(lastLine) ||
/^(?:Claude>|kiro>|gemini-cli>|aider>)\s*$/i.test(lastLine) ||
- (/^\??\s*for shortcuts/i.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (/^(?:│\s*)?[>❯›]\s*$/.test(prevLine) || /^(?:│\s*)?[>❯›]\s*$/.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine)))
+ (/^\??\s*for shortcuts/i.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (/^(?:│\s*)?[>❯›]\s*$/.test(prevLine) || /^(?:│\s*)?[>❯›]\s*$/.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine) || /Gemini|Claude/i.test(lastLine) || /●\s*Agent\(/i.test(prevLine) || /●\s*Agent\(/i.test(prevPrevLine)))
);
if (isAtIdlePrompt) {
@@ -3535,14 +3536,19 @@ function detectAgentThinking(terminalText, isWaiting = false) {
if (/^esc to (?:cancel|interrupt)\s*$/im.test(lastChunk)) {
return { isThinking: true, isPaused: false, label: 'Executando comando no agente...' };
}
- if (/\d+\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt)) {
+ if (/[1-9]\d*\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt && /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(lastChunk))) {
return { isThinking: true, isPaused: false, label: 'Executando subagente...' };
}
- if (/(Thought for|Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) {
+ if (/(Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) {
return { isThinking: true, isPaused: false, label: 'Executando ações no workspace...' };
}
- // 6. Se o usuário acabou de enviar uma mensagem e ainda está aguardando
+ // 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)) {
+ return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' };
+ }
+
+ // 7. Se o usuário acabou de enviar uma mensagem e ainda está aguardando
if (isWaiting) {
return { isThinking: true, isPaused: false, label: 'Agente está pensando...' };
}
@@ -3923,7 +3929,16 @@ function renderChatMessages(forceScroll = false) {
const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean')
? activeAgentInfo.hasInteractiveMenu
: Boolean(detection.hasInteractiveMenu || (currentInteractiveMenu && currentInteractiveMenu.hasInteractiveMenu));
- const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || detection.isThinking);
+
+ const authoritativeThinking = (activeAgentInfo && typeof activeAgentInfo.isThinking === 'boolean')
+ ? activeAgentInfo.isThinking
+ : (histKey && agentThinkingStates.has(histKey) ? agentThinkingStates.get(histKey) : null);
+
+ const isThinkingEffective = typeof authoritativeThinking === 'boolean'
+ ? authoritativeThinking
+ : detection.isThinking;
+
+ const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || isThinkingEffective);
if (showThinkingCard) {
startThinkingTimer();
@@ -3998,11 +4013,15 @@ function appendAgentTyping() {
}, 900000);
}
-function removeAgentTyping() {
+function removeAgentTyping(forceRemoveAll = false) {
clearTimeout(typingTimeoutTimer);
typingTimeoutTimer = null;
const typing = document.getElementById('chat-typing-indicator');
- if (typing) typing.remove();
+ if (typing) {
+ if (forceRemoveAll || !typing.classList.contains('thinking-card')) {
+ typing.remove();
+ }
+ }
}
function setupChatEvents() {
diff --git a/public/bundles/bundle-1.0.26.zip b/public/bundles/bundle-1.0.26.zip
new file mode 100644
index 0000000..0129cce
Binary files /dev/null and b/public/bundles/bundle-1.0.26.zip differ
diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip
index 79de412..0129cce 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 bfde512..f1df318 100644
--- a/public/bundles/manifest.json
+++ b/public/bundles/manifest.json
@@ -1,9 +1,9 @@
{
- "version": "1.0.24",
- "buildId": "5a3f32bc",
- "releasedAt": "2026-11-21T16:23:44.908Z",
- "bundleUrl": "/bundles/bundle-1.0.24.zip",
+ "version": "1.0.26",
+ "buildId": "ce540d0d",
+ "releasedAt": "2026-11-21T17:41:31.996Z",
+ "bundleUrl": "/bundles/bundle-1.0.26.zip",
"latestUrl": "/bundles/bundle-latest.zip",
- "checksum": "6710730c8f71a8db1eef7fd4673a6633a2b590a4186ee7d500b4afb4b24bc00f",
- "sizeBytes": 67263
+ "checksum": "93e2a2a6bdaca95d3c2b80a19e35ce02c89a8b2e3c7eb31a9d44d64e2bd81c29",
+ "sizeBytes": 67600
}
\ No newline at end of file
diff --git a/public/maestri-agent.zip b/public/maestri-agent.zip
index c06285f..1ae06ea 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 6959824..f1a6acb 100644
--- a/src/utils/activity-detector.js
+++ b/src/utils/activity-detector.js
@@ -26,10 +26,10 @@ const RE_AIDER = /Aider v\d|Tokens:.*?Model:/i;
// Glifos e spinners de execução / IA pensando
const RE_SPINNERS = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/;
const RE_CLAUDE_GLYPHS = /[✽✻✶✹✸]/;
-const RE_RUNNING_WORDS = /(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working|\d+\s+subagent\(s\))(?:(?=\s|$|\(|\[|\.|,|;|:)|\b)/i;
+const RE_RUNNING_WORDS = /(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working|[1-9]\d*\s+subagent\(s\))(?:(?=\s|$|\(|\[|\.|,|;|:)|\b)/i;
// Padrões de prompt ocioso de entrada de IA nas últimas linhas do terminal
-const RE_AI_IDLE_INPUT = /^(?:│\s*)?[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?$/i;
+const RE_AI_IDLE_INPUT = /^(?:│\s*)?(?:[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?|↳\s*Interrupted.*?|(?:\bWhat should\b.*?\bdo instead\?)|(?:Are you sure|Do you want to proceed)\b.*?\?)\s*$/i;
const RE_AI_SHORTCUTS = /^\??\s*for shortcuts/i;
const RE_AI_NAMED_IDLE = /^(?:Claude>|kiro>|gemini-cli>|aider>)\s*$/i;
@@ -878,17 +878,27 @@ export function detectTerminalActivity(rawOutput) {
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 =
- /\d+\s+subagent\(s\)/i.test(lastLine) ||
- /●\s*Agent\(/i.test(prevLine) ||
+ hasExplicitActiveSubagents ||
+ (/●\s*Agent\(/i.test(prevLine) && !RE_AI_SHORTCUTS.test(lastLine) && !RE_AI_IDLE_INPUT.test(lastLine)) ||
RE_SPINNERS.test(prevLine) ||
RE_RUNNING_WORDS.test(prevLine);
// Identifica se o terminal está no prompt ocioso de entrada de um agente de IA
- const isEndingInAiIdlePrompt = !(/\d+\s+subagent\(s\)/i.test(lastLine)) && (
+ const isEndingInAiIdlePrompt = !hasExplicitActiveSubagents && (
RE_AI_IDLE_INPUT.test(lastLine) ||
RE_AI_NAMED_IDLE.test(lastLine) ||
- (RE_AI_SHORTCUTS.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (RE_AI_IDLE_INPUT.test(prevLine) || RE_AI_IDLE_INPUT.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine)))
+ (RE_AI_SHORTCUTS.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (
+ RE_AI_IDLE_INPUT.test(prevLine) ||
+ RE_AI_IDLE_INPUT.test(prevPrevLine) ||
+ /Gemini/i.test(prevLine) ||
+ /Claude/i.test(prevLine) ||
+ /Gemini|Claude/i.test(lastLine) ||
+ /●\s*Agent\(/i.test(prevLine) ||
+ /●\s*Agent\(/i.test(prevPrevLine)
+ ))
);
const isUsageLimit = RE_USAGE_LIMIT.test(tail);
@@ -899,14 +909,15 @@ export function detectTerminalActivity(rawOutput) {
}
// Se o agente está no prompt ocioso de entrada ou pausado por limite de uso/cota, NÃO está pensando
- const isThinking = !isUsageLimit && !isEndingInAiIdlePrompt && (RE_SPINNERS.test(tail) || RE_RUNNING_WORDS.test(tail) || hasActiveSubagentOrToolOnPrev || (RE_CLAUDE_GLYPHS.test(tail) && !/done|completed/i.test(lastLine)));
+ const hasExplicitIndicator = 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)) {
return {
hasAiActivity: true,
aiType: 'agy',
shellType: null,
- isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && (isThinking || (/○ Thought for/i.test(tail) && !/\? for shortcuts/i.test(lastLine))),
+ isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && isThinking,
isPaused: isUsageLimit,
pauseReason: isUsageLimit ? 'usage_limit' : null,
pauseResetTime,
diff --git a/test/activity-detector.test.js b/test/activity-detector.test.js
index 4cb9fb2..816615b 100644
--- a/test/activity-detector.test.js
+++ b/test/activity-detector.test.js
@@ -500,7 +500,7 @@ $ git status
'● Agent(self: Reviewer) · 1m0s',
'? for shortcuts auto · Orchestrator (Argon)'
].join('\n');
- assert.strictEqual(detectTerminalActivity(agySubagentNoFooterCount).isThinking, true);
+ assert.strictEqual(detectTerminalActivity(agySubagentNoFooterCount).isThinking, false, 'Subagente concluído sem contagem no footer deve ser isThinking = false');
const agySubagentFooterOnly = [
'● Running background step',
@@ -774,4 +774,54 @@ $ git status
assert.strictEqual(act.isThinking, false);
assert.strictEqual(act.hasInteractiveMenu, true);
});
+
+ await t.test('25. Regressão — Hotfix falso positivo de thinking (terminal interrompido e subagente concluído)', () => {
+ // 25.1 Terminal do Antigravity interrompido (Ctrl+C) deve retornar hasAiActivity: true, isThinking: false, details: 'Antigravity CLI pronto'
+ const agyInterrupted = [
+ '> execute comando demorado',
+ '○ Thought for 44.0s (Analyzing code...)',
+ '↳ Interrupted • What should Antigravity CLI do instead?'
+ ].join('\n');
+ const r1 = detectTerminalActivity(agyInterrupted);
+ assert.strictEqual(r1.hasAiActivity, true, 'Deve identificar Antigravity CLI');
+ assert.strictEqual(r1.isThinking, false, 'Terminal interrompido deve ter isThinking = false');
+ assert.strictEqual(r1.details, 'Antigravity CLI pronto');
+
+ // 25.2 Terminal com histórico de subagente concluído e footer padrão (sem subagentes ativos)
+ const agySubagentFinished = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 3m1s',
+ '? for shortcuts Gemini 3.8 Flash · medium'
+ ].join('\n');
+ const r2 = detectTerminalActivity(agySubagentFinished);
+ assert.strictEqual(r2.hasAiActivity, true, 'Deve identificar Antigravity CLI');
+ assert.strictEqual(r2.isThinking, false, 'Subagente concluído com footer padrão não deve manter isThinking = true');
+ assert.strictEqual(r2.details, 'Antigravity CLI pronto');
+
+ // 25.3 Terminal com subagente ativo (contagem explícita no rodapé)
+ const agySubagentActive = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 10s',
+ '? for shortcuts auto · 1 subagent(s)'
+ ].join('\n');
+ const r3 = detectTerminalActivity(agySubagentActive);
+ assert.strictEqual(r3.hasAiActivity, true, 'Deve identificar Antigravity CLI');
+ assert.strictEqual(r3.isThinking, true, 'Subagente com contagem ativa no footer deve manter isThinking = true');
+ assert.strictEqual(r3.details, 'Antigravity CLI ativo');
+
+ // 25.4 Terminal executando comandos intermediários sem prompt final de repouso (MidRun) deve manter isThinking: true estável
+ const agyMidRunToolOutput = [
+ 'Antigravity CLI 1.5.4',
+ '> npm test',
+ '● Ran (npm test) (ctrl+o to expand)',
+ 'TAP version 13',
+ 'ok 1 - subtest passed',
+ 'ok 2 - another test passed',
+ 'duration_ms: 45.2'
+ ].join('\n');
+ const r4 = detectTerminalActivity(agyMidRunToolOutput);
+ assert.strictEqual(r4.hasAiActivity, true, 'Deve identificar Antigravity CLI');
+ 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');
+ });
});
diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js
index f241b64..24cdbcf 100644
--- a/test/frontend-app.test.js
+++ b/test/frontend-app.test.js
@@ -2968,4 +2968,82 @@ Também verificamos running command e compiling no buffer.
assert.deepStrictEqual(getSelectPins(), ['111111', '444444', '333333', '222222']);
assert.strictEqual(document.getElementById('stations-count-badge').textContent, '2/4');
});
+
+ test('35. Regressão Hotfix — Precedência autoritativa de isThinking e detecção no frontend sem falso positivo', async () => {
+ // 35.1 Validação direta de detectAgentThinking no frontend
+ const agyInterrupted = [
+ '> execute comando demorado',
+ '○ Thought for 44.0s (Analyzing code...)',
+ '↳ Interrupted • What should Antigravity CLI do instead?'
+ ].join('\n');
+ const f1 = window.detectAgentThinking(agyInterrupted, false);
+ assert.strictEqual(f1.isThinking, false, 'detectAgentThinking com Interrupted deve retornar isThinking = false');
+
+ const agySubagentFinished = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 3m1s',
+ '? for shortcuts Gemini 3.8 Flash · medium'
+ ].join('\n');
+ const f2 = window.detectAgentThinking(agySubagentFinished, false);
+ assert.strictEqual(f2.isThinking, false, 'detectAgentThinking com subagente concluído e footer padrão deve retornar isThinking = false');
+
+ const agySubagentActive = [
+ '> implemente a task',
+ '● Agent(self: Builder de Implementação) · 10s',
+ '? for shortcuts auto · 1 subagent(s)'
+ ].join('\n');
+ const f3 = window.detectAgentThinking(agySubagentActive, false);
+ assert.strictEqual(f3.isThinking, true, 'detectAgentThinking com 1 subagent(s) ativo deve retornar isThinking = true');
+
+ // 35.2 Validação de renderChatMessages com precedência autoritativa
+ // Conecta estação e abre chat
+ document.getElementById('pin-input').value = '161818';
+ document.getElementById('btn-connect').click();
+ await new Promise(r => setTimeout(r, 20));
+
+ mockWsInstance.onmessage({
+ data: JSON.stringify({
+ type: 'INIT_STATE',
+ machineName: 'Estacao Nitro',
+ agents: [{ name: 'Builder', isSelf: false, isThinking: false }]
+ })
+ });
+
+ const agentPill = document.querySelector('.agent-pill');
+ assert.ok(agentPill, 'Pill do agente Builder deve existir');
+ agentPill.click();
+ await new Promise(r => setTimeout(r, 20));
+
+ // Simula mensagem final entregue pelo agente
+ mockWsInstance.onmessage({
+ data: JSON.stringify({
+ type: 'AGENT_CHAT_REPLY',
+ agentName: 'Builder',
+ text: 'Tarefa implementada com sucesso.',
+ terminalSnapshot: agySubagentFinished,
+ timestamp: Date.now()
+ })
+ });
+ await new Promise(r => setTimeout(r, 20));
+
+ // Valida que o card dinâmico de thinking (.thinking-card) NÃO está presente no DOM
+ const thinkingCard = document.querySelector('.chat-bubble.thinking-card');
+ assert.strictEqual(thinkingCard, null, 'Card de thinking não deve existir quando resposta já chegou e agente está autoritativamente ocioso');
+
+ // 35.3 removeAgentTyping(false) não destrói .thinking-card (evita flicker a cada 350ms do polling)
+ const chatMessagesEl = document.getElementById('chat-messages');
+ const dummyThinking = document.createElement('div');
+ dummyThinking.id = 'chat-typing-indicator';
+ dummyThinking.className = 'chat-bubble thinking-card';
+ dummyThinking.innerHTML = 'Trabalhando...';
+ chatMessagesEl.appendChild(dummyThinking);
+
+ // Chamada normal durante streaming de terminal (removeAgentTyping(false))
+ window.removeAgentTyping(false);
+ assert.ok(document.getElementById('chat-typing-indicator'), 'removeAgentTyping(false) deve preservar o card de thinking para permitir update in-place sem flicker');
+
+ // Chamada forçada ao concluir/fechar (removeAgentTyping(true))
+ window.removeAgentTyping(true);
+ assert.strictEqual(document.getElementById('chat-typing-indicator'), null, 'removeAgentTyping(true) deve remover completamente o card ao encerrar');
+ });
});