fix(terminal): eliminar falso-positivo de thinking e captura indevida de prompts de shell
This commit is contained in:
parent
7c77e476f2
commit
19465ff33c
257
app.js
257
app.js
@ -2,6 +2,7 @@
|
|||||||
// Map<pin, { pin: string, name: string, machineName: string, ws: WebSocket|null, status: 'connecting'|'online'|'offline', agents: Array, pendingPrompts: Map }>
|
// Map<pin, { pin: string, name: string, machineName: string, ws: WebSocket|null, status: 'connecting'|'online'|'offline', agents: Array, pendingPrompts: Map }>
|
||||||
const stationPool = new Map();
|
const stationPool = new Map();
|
||||||
const reconnectTimers = new Map();
|
const reconnectTimers = new Map();
|
||||||
|
const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
|
||||||
|
|
||||||
// Variáveis de compatibilidade legada
|
// Variáveis de compatibilidade legada
|
||||||
let ws = null;
|
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() {
|
function getSavedAuthUser() {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem('maestri_user');
|
const raw = localStorage.getItem('maestri_user');
|
||||||
@ -583,14 +690,12 @@ function updateUserBadge(user) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncStationToServer(method, pathSuffix, body) {
|
async function syncStationToServer(method, pathSuffix, body) {
|
||||||
const token = getAuthToken();
|
if (!getAuthToken() && !getRefreshToken()) return null;
|
||||||
if (!token) return null;
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${getApiBaseUrl()}${pathSuffix}`, {
|
const res = await fetchWithAuth(`${getApiBaseUrl()}${pathSuffix}`, {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json'
|
||||||
'Authorization': `Bearer ${token}`
|
|
||||||
},
|
},
|
||||||
body: body ? JSON.stringify(body) : undefined
|
body: body ? JSON.stringify(body) : undefined
|
||||||
});
|
});
|
||||||
@ -608,12 +713,9 @@ async function syncStationToServer(method, pathSuffix, body) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncStationsFromServer() {
|
async function syncStationsFromServer() {
|
||||||
const token = getAuthToken();
|
if (!getAuthToken() && !getRefreshToken()) return getSavedStations();
|
||||||
if (!token) return getSavedStations();
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${getApiBaseUrl()}/api/stations`, {
|
const res = await fetchWithAuth(`${getApiBaseUrl()}/api/stations`);
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
logoutUser();
|
logoutUser();
|
||||||
return [];
|
return [];
|
||||||
@ -811,21 +913,18 @@ async function startGoogleLogin() {
|
|||||||
};
|
};
|
||||||
activeAuthPollCleanup = cleanup;
|
activeAuthPollCleanup = cleanup;
|
||||||
|
|
||||||
const finalizeSuccess = async (token, user) => {
|
const finalizeSuccess = async (token, user, refreshToken) => {
|
||||||
if (finished) return;
|
if (finished) return;
|
||||||
finished = true;
|
finished = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
try {
|
setAuthSession(token, refreshToken, user);
|
||||||
localStorage.setItem('maestri_auth_token', token);
|
|
||||||
localStorage.setItem('maestri_user', JSON.stringify(user || {}));
|
|
||||||
} catch (e) {}
|
|
||||||
await completeAuthenticatedStartup(user);
|
await completeAuthenticatedStartup(user);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onWindowMessage = (event) => {
|
const onWindowMessage = (event) => {
|
||||||
const data = event?.data;
|
const data = event?.data;
|
||||||
if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) {
|
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;
|
if (!pollRes.ok) return;
|
||||||
const data = await pollRes.json();
|
const data = await pollRes.json();
|
||||||
if (data.status === 'completed' && data.token) {
|
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') {
|
} else if (data.status === 'expired') {
|
||||||
finished = true;
|
finished = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
@ -2737,10 +2836,10 @@ function formatElapsed(startTime) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function extractLatestAction(terminalText) {
|
function extractLatestAction(terminalText) {
|
||||||
if (!terminalText || typeof terminalText !== 'string') return 'Processando solicitação...';
|
if (!terminalText || typeof terminalText !== 'string') return '';
|
||||||
const clean = cleanTerminalOutput(terminalText).trim();
|
const clean = cleanTerminalOutput(terminalText).trim();
|
||||||
const lines = clean.split('\n').map(l => l.trim()).filter(Boolean);
|
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--) {
|
for (let i = lines.length - 1; i >= 0; i--) {
|
||||||
const line = lines[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;
|
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
|
// Ignora menções de código ou CSS para evitar falsos positivos
|
||||||
if (/\.thinking|\#f59e0b|isThinking/i.test(line)) continue;
|
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)) {
|
if (/(?:running command|generating|percolating|analyzing|working|building|compiling|thinking\.\.\.)/i.test(line)) {
|
||||||
return line.slice(0, 50);
|
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];
|
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;
|
return lastLine.length > 50 ? lastLine.slice(0, 47) + '...' : lastLine;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2786,7 +2897,6 @@ function stopThinkingTimer() {
|
|||||||
thinkingStartTime = null;
|
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_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_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_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...' : '' };
|
return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const raw = terminalText.trim();
|
const clean = terminalText.replace(RE_ANSI, '').trim();
|
||||||
const lastChunk = raw.slice(-800);
|
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
|
// 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);
|
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
|
// 1. PRECEDÊNCIA MÁXIMA: Prompts de Shell do Sistema e Prompts Ociosos de IA
|
||||||
const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
const lines = clean.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
||||||
const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';
|
const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';
|
||||||
const prevLine = lines.length > 1 ? lines[lines.length - 2] : '';
|
const prevLine = lines.length > 1 ? lines[lines.length - 2] : '';
|
||||||
const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : '';
|
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 =
|
const hasActiveSubagentOrToolOnPrev =
|
||||||
hasExplicitActiveSubagents ||
|
hasExplicitActiveSubagents ||
|
||||||
(/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) ||
|
(/●\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
|
// 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...' };
|
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: true, isPaused: false, label: 'Agente está pensando...' };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { isThinking: false, isPaused: false, label: '' };
|
return { isThinking: false, isPaused: false, label: 'Pronto' };
|
||||||
}
|
}
|
||||||
window.detectAgentThinking = detectAgentThinking;
|
window.detectAgentThinking = detectAgentThinking;
|
||||||
|
window.extractLatestAction = extractLatestAction;
|
||||||
|
|
||||||
function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) {
|
function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) {
|
||||||
const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean')
|
const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean')
|
||||||
@ -5261,11 +5393,9 @@ function logoutUser() {
|
|||||||
});
|
});
|
||||||
stationPool.clear();
|
stationPool.clear();
|
||||||
|
|
||||||
localStorage.removeItem('maestri_auth_token');
|
clearAuthSession();
|
||||||
localStorage.removeItem('maestri_user');
|
|
||||||
localStorage.removeItem('maestri_pin');
|
localStorage.removeItem('maestri_pin');
|
||||||
localStorage.removeItem('maestri_stations');
|
localStorage.removeItem('maestri_stations');
|
||||||
currentAuthUser = null;
|
|
||||||
currentPin = null;
|
currentPin = null;
|
||||||
ws = null;
|
ws = null;
|
||||||
|
|
||||||
@ -5434,9 +5564,11 @@ async function initApp() {
|
|||||||
}
|
}
|
||||||
initOtaChecker();
|
initOtaChecker();
|
||||||
|
|
||||||
// Gate obrigatório de autenticação Google SSO
|
// Gate obrigatório de autenticação Google SSO com renovação silenciosa via refresh token
|
||||||
const token = getAuthToken();
|
let token = getAuthToken();
|
||||||
if (!token) {
|
const refreshToken = getRefreshToken();
|
||||||
|
|
||||||
|
if (!token && !refreshToken) {
|
||||||
if (pinFromUrl && pinFromUrl.length >= 4) {
|
if (pinFromUrl && pinFromUrl.length >= 4) {
|
||||||
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
||||||
}
|
}
|
||||||
@ -5444,10 +5576,36 @@ async function initApp() {
|
|||||||
return;
|
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 {
|
try {
|
||||||
const meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
|
let meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
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) {
|
if (meRes.ok) {
|
||||||
const data = await meRes.json();
|
const data = await meRes.json();
|
||||||
if (data && data.user) {
|
if (data && data.user) {
|
||||||
@ -5460,8 +5618,7 @@ async function initApp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (meRes.status === 401) {
|
if (meRes.status === 401) {
|
||||||
localStorage.removeItem('maestri_auth_token');
|
clearAuthSession();
|
||||||
localStorage.removeItem('maestri_user');
|
|
||||||
if (pinFromUrl && pinFromUrl.length >= 4) {
|
if (pinFromUrl && pinFromUrl.length >= 4) {
|
||||||
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
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') {
|
if (document.readyState === 'loading') {
|
||||||
window.addEventListener('DOMContentLoaded', initApp);
|
window.addEventListener('DOMContentLoaded', initApp);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "maestri-remote-agent",
|
"name": "maestri-remote-agent",
|
||||||
"version": "1.0.31",
|
"version": "1.0.32",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Gateway Local do Maestri Remote para estações de trabalho",
|
"description": "Gateway Local do Maestri Remote para estações de trabalho",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
// Map<pin, { pin: string, name: string, machineName: string, ws: WebSocket|null, status: 'connecting'|'online'|'offline', agents: Array, pendingPrompts: Map }>
|
// Map<pin, { pin: string, name: string, machineName: string, ws: WebSocket|null, status: 'connecting'|'online'|'offline', agents: Array, pendingPrompts: Map }>
|
||||||
const stationPool = new Map();
|
const stationPool = new Map();
|
||||||
const reconnectTimers = new Map();
|
const reconnectTimers = new Map();
|
||||||
|
const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
|
||||||
|
|
||||||
// Variáveis de compatibilidade legada
|
// Variáveis de compatibilidade legada
|
||||||
let ws = null;
|
let ws = null;
|
||||||
@ -2835,10 +2836,10 @@ function formatElapsed(startTime) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function extractLatestAction(terminalText) {
|
function extractLatestAction(terminalText) {
|
||||||
if (!terminalText || typeof terminalText !== 'string') return 'Processando solicitação...';
|
if (!terminalText || typeof terminalText !== 'string') return '';
|
||||||
const clean = cleanTerminalOutput(terminalText).trim();
|
const clean = cleanTerminalOutput(terminalText).trim();
|
||||||
const lines = clean.split('\n').map(l => l.trim()).filter(Boolean);
|
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--) {
|
for (let i = lines.length - 1; i >= 0; i--) {
|
||||||
const line = lines[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;
|
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
|
// Ignora menções de código ou CSS para evitar falsos positivos
|
||||||
if (/\.thinking|\#f59e0b|isThinking/i.test(line)) continue;
|
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)) {
|
if (/(?:running command|generating|percolating|analyzing|working|building|compiling|thinking\.\.\.)/i.test(line)) {
|
||||||
return line.slice(0, 50);
|
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];
|
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;
|
return lastLine.length > 50 ? lastLine.slice(0, 47) + '...' : lastLine;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2884,7 +2897,6 @@ function stopThinkingTimer() {
|
|||||||
thinkingStartTime = null;
|
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_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_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_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...' : '' };
|
return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const raw = terminalText.trim();
|
const clean = terminalText.replace(RE_ANSI, '').trim();
|
||||||
const lastChunk = raw.slice(-800);
|
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
|
// 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);
|
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
|
// 1. PRECEDÊNCIA MÁXIMA: Prompts de Shell do Sistema e Prompts Ociosos de IA
|
||||||
const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
const lines = clean.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
||||||
const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';
|
const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';
|
||||||
const prevLine = lines.length > 1 ? lines[lines.length - 2] : '';
|
const prevLine = lines.length > 1 ? lines[lines.length - 2] : '';
|
||||||
const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : '';
|
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 =
|
const hasActiveSubagentOrToolOnPrev =
|
||||||
hasExplicitActiveSubagents ||
|
hasExplicitActiveSubagents ||
|
||||||
(/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) ||
|
(/●\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
|
// 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...' };
|
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: true, isPaused: false, label: 'Agente está pensando...' };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { isThinking: false, isPaused: false, label: '' };
|
return { isThinking: false, isPaused: false, label: 'Pronto' };
|
||||||
}
|
}
|
||||||
window.detectAgentThinking = detectAgentThinking;
|
window.detectAgentThinking = detectAgentThinking;
|
||||||
|
window.extractLatestAction = extractLatestAction;
|
||||||
|
|
||||||
function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) {
|
function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) {
|
||||||
const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean')
|
const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean')
|
||||||
|
|||||||
BIN
public/bundles/bundle-1.0.32.zip
Normal file
BIN
public/bundles/bundle-1.0.32.zip
Normal file
Binary file not shown.
Binary file not shown.
@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"version": "1.0.31",
|
"version": "1.0.32",
|
||||||
"buildId": "58d9c94c",
|
"buildId": "b00e32c7",
|
||||||
"releasedAt": "2026-11-22T15:34:43.243Z",
|
"releasedAt": "2026-11-22T15:59:03.064Z",
|
||||||
"bundleUrl": "/bundles/bundle-1.0.31.zip",
|
"bundleUrl": "/bundles/bundle-1.0.32.zip",
|
||||||
"latestUrl": "/bundles/bundle-latest.zip",
|
"latestUrl": "/bundles/bundle-latest.zip",
|
||||||
"checksum": "32f6f2b500796a5da1019d302e454e008bc058094a56c1ac3e4c8dafbe612eed",
|
"checksum": "2dc1bc3ec93d41b021d417937322e08e14b12efd20bbb700fb7fb84a0973f01a",
|
||||||
"sizeBytes": 75171
|
"sizeBytes": 75807
|
||||||
}
|
}
|
||||||
Binary file not shown.
@ -7,10 +7,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Padrões de prompt de shell puro do sistema operacional (final da saída)
|
// 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_PS_GENERIC = /(?:^|\n)\s*PS\s*>\s*$/m;
|
||||||
const RE_CMD_PROMPT = /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\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
|
// Padrões de cabeçalho inicial de shell puro
|
||||||
const RE_PS_HEADER = /Windows PowerShell|PowerShell 7|Copyright \(C\) Microsoft Corporation/i;
|
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
|
// Remove códigos ANSI de cor e estilo para análise limpa e determinística do buffer
|
||||||
const tail = trimmed.slice(-3000);
|
const clean = rawOutput.replace(RE_ANSI, '');
|
||||||
const lines = trimmed.split('\n').map(l => l.trim()).filter(Boolean);
|
const cleanTrimmed = clean.trim();
|
||||||
const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';
|
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;
|
const isEndingInShellPrompt = isLastLinePS || isLastLineCmd || isLastLineBash;
|
||||||
|
|
||||||
// Se a última linha for um prompt de shell puro (ex: "PS C:\Users> " ou "C:\> " ou "user@host:~$ "),
|
// 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
|
// 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 hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(tail.slice(-300));
|
||||||
|
|
||||||
const hasActiveSubagentOrToolOnPrev =
|
const hasActiveSubagentOrToolOnPrev =
|
||||||
@ -908,8 +944,13 @@ export function detectTerminalActivity(rawOutput) {
|
|||||||
if (timeMatch) pauseResetTime = timeMatch[1];
|
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
|
// Indicadores explícitos de execução ativa de IA
|
||||||
const hasExplicitIndicator = RE_SPINNERS.test(tail) || RE_RUNNING_WORDS.test(tail) || hasActiveSubagentOrToolOnPrev || (RE_CLAUDE_GLYPHS.test(tail) && !/done|completed/i.test(lastLine));
|
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;
|
const isThinking = !isUsageLimit && !isEndingInAiIdlePrompt;
|
||||||
|
|
||||||
if (RE_AGY.test(tail)) {
|
if (RE_AGY.test(tail)) {
|
||||||
@ -917,7 +958,7 @@ export function detectTerminalActivity(rawOutput) {
|
|||||||
hasAiActivity: true,
|
hasAiActivity: true,
|
||||||
aiType: 'agy',
|
aiType: 'agy',
|
||||||
shellType: null,
|
shellType: null,
|
||||||
isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && isThinking,
|
isThinking: !isUsageLimit && !isEndingInAiIdlePrompt,
|
||||||
isPaused: isUsageLimit,
|
isPaused: isUsageLimit,
|
||||||
pauseReason: isUsageLimit ? 'usage_limit' : null,
|
pauseReason: isUsageLimit ? 'usage_limit' : null,
|
||||||
pauseResetTime,
|
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 {
|
return {
|
||||||
hasAiActivity: true,
|
hasAiActivity: true,
|
||||||
aiType: 'generic_ai',
|
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
|
// 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)) {
|
if (RE_PS_HEADER.test(tail) || RE_PS_PROMPT.test(tail) || lastLine.endsWith('>') || isLastLinePS) {
|
||||||
return {
|
return {
|
||||||
hasAiActivity: false,
|
hasAiActivity: false,
|
||||||
aiType: null,
|
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 {
|
return {
|
||||||
hasAiActivity: false,
|
hasAiActivity: false,
|
||||||
aiType: null,
|
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 {
|
return {
|
||||||
hasAiActivity: false,
|
hasAiActivity: false,
|
||||||
aiType: null,
|
aiType: null,
|
||||||
|
|||||||
@ -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.isThinking, true, 'Comando em execução sem prompt final de repouso deve manter isThinking = true estável');
|
||||||
assert.strictEqual(r4.details, 'Antigravity CLI ativo');
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -3451,4 +3451,39 @@ Também verificamos running command e compiling no buffer.
|
|||||||
freshDom.window.close();
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user