fix(terminal): elimina falso positivo e flicker de status em terminais ativos e ociosos
This commit is contained in:
parent
10c11dfc2b
commit
9b175f91d8
@ -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');
|
||||||
|
```
|
||||||
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "maestri-remote-agent",
|
"name": "maestri-remote-agent",
|
||||||
"version": "1.0.24",
|
"version": "1.0.26",
|
||||||
"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": {
|
||||||
|
|||||||
@ -1307,7 +1307,7 @@ function handleStationMessage(pin, msg) {
|
|||||||
}
|
}
|
||||||
setAgentChatHistory(msg.agentName, pin, hist);
|
setAgentChatHistory(msg.agentName, pin, hist);
|
||||||
if (activeChatAgent === msg.agentName && (!activeChatPin || String(activeChatPin) === String(pin))) {
|
if (activeChatAgent === msg.agentName && (!activeChatPin || String(activeChatPin) === String(pin))) {
|
||||||
removeAgentTyping();
|
removeAgentTyping(false);
|
||||||
if (chatTerminalOutputRaw) {
|
if (chatTerminalOutputRaw) {
|
||||||
chatTerminalOutputRaw.textContent = cleanTerminalOutput(newOutput);
|
chatTerminalOutputRaw.textContent = cleanTerminalOutput(newOutput);
|
||||||
}
|
}
|
||||||
@ -1328,7 +1328,7 @@ function handleStationMessage(pin, msg) {
|
|||||||
isWaitingChatReply = false;
|
isWaitingChatReply = false;
|
||||||
hadThinkingDuringReply = false;
|
hadThinkingDuringReply = false;
|
||||||
stopThinkingTimer();
|
stopThinkingTimer();
|
||||||
removeAgentTyping();
|
removeAgentTyping(true);
|
||||||
updateAgentThinkingUI('', false, { isThinking: false, isPaused: false, label: 'Pronto' });
|
updateAgentThinkingUI('', false, { isThinking: false, isPaused: false, label: 'Pronto' });
|
||||||
agentThinkingStates.set(histKey, false);
|
agentThinkingStates.set(histKey, false);
|
||||||
const targetAgent = entry.agents.find(a => a.name === msg.agentName);
|
const targetAgent = entry.agents.find(a => a.name === msg.agentName);
|
||||||
@ -1365,7 +1365,7 @@ function handleStationMessage(pin, msg) {
|
|||||||
isWaitingChatReply = false;
|
isWaitingChatReply = false;
|
||||||
hadThinkingDuringReply = false;
|
hadThinkingDuringReply = false;
|
||||||
stopThinkingTimer();
|
stopThinkingTimer();
|
||||||
removeAgentTyping();
|
removeAgentTyping(true);
|
||||||
updateAgentThinkingUI('', false);
|
updateAgentThinkingUI('', false);
|
||||||
if (msg.agentName) {
|
if (msg.agentName) {
|
||||||
const histKey = `${pin}:${msg.agentName}`;
|
const histKey = `${pin}:${msg.agentName}`;
|
||||||
@ -2483,7 +2483,7 @@ function extractLatestAction(terminalText) {
|
|||||||
|
|
||||||
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];
|
||||||
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
|
// 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;
|
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
|
||||||
@ -2494,7 +2494,7 @@ function extractLatestAction(terminalText) {
|
|||||||
if (/^(●|○|⚡|✽|⠇|⣻|⣾|⣽)\s+/i.test(line)) {
|
if (/^(●|○|⚡|✽|⠇|⣻|⣾|⣽)\s+/i.test(line)) {
|
||||||
return line.slice(0, 50);
|
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);
|
return line.slice(0, 50);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -3475,16 +3475,17 @@ function detectAgentThinking(terminalText, isWaiting = false) {
|
|||||||
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 hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(raw.slice(-300));
|
||||||
const hasActiveSubagentOrToolOnPrev =
|
const hasActiveSubagentOrToolOnPrev =
|
||||||
/\d+\s+subagent\(s\)/i.test(lastLine) ||
|
hasExplicitActiveSubagents ||
|
||||||
/●\s*Agent\(/i.test(prevLine) ||
|
(/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) ||
|
||||||
/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) ||
|
/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) ||
|
||||||
/(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working)/i.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)) && (
|
const isAtIdlePrompt = !hasExplicitActiveSubagents && (
|
||||||
/^(?:│\s*)?[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?$/i.test(lastLine) ||
|
/^(?:│\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) ||
|
/^(?: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) {
|
if (isAtIdlePrompt) {
|
||||||
@ -3535,14 +3536,19 @@ function detectAgentThinking(terminalText, isWaiting = false) {
|
|||||||
if (/^esc to (?:cancel|interrupt)\s*$/im.test(lastChunk)) {
|
if (/^esc to (?:cancel|interrupt)\s*$/im.test(lastChunk)) {
|
||||||
return { isThinking: true, isPaused: false, label: 'Executando comando no agente...' };
|
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...' };
|
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...' };
|
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) {
|
if (isWaiting) {
|
||||||
return { isThinking: true, isPaused: false, label: 'Agente está pensando...' };
|
return { isThinking: true, isPaused: false, label: 'Agente está pensando...' };
|
||||||
}
|
}
|
||||||
@ -3923,7 +3929,16 @@ function renderChatMessages(forceScroll = false) {
|
|||||||
const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean')
|
const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean')
|
||||||
? activeAgentInfo.hasInteractiveMenu
|
? activeAgentInfo.hasInteractiveMenu
|
||||||
: Boolean(detection.hasInteractiveMenu || (currentInteractiveMenu && currentInteractiveMenu.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) {
|
if (showThinkingCard) {
|
||||||
startThinkingTimer();
|
startThinkingTimer();
|
||||||
@ -3998,11 +4013,15 @@ function appendAgentTyping() {
|
|||||||
}, 900000);
|
}, 900000);
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeAgentTyping() {
|
function removeAgentTyping(forceRemoveAll = false) {
|
||||||
clearTimeout(typingTimeoutTimer);
|
clearTimeout(typingTimeoutTimer);
|
||||||
typingTimeoutTimer = null;
|
typingTimeoutTimer = null;
|
||||||
const typing = document.getElementById('chat-typing-indicator');
|
const typing = document.getElementById('chat-typing-indicator');
|
||||||
if (typing) typing.remove();
|
if (typing) {
|
||||||
|
if (forceRemoveAll || !typing.classList.contains('thinking-card')) {
|
||||||
|
typing.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupChatEvents() {
|
function setupChatEvents() {
|
||||||
|
|||||||
BIN
public/bundles/bundle-1.0.26.zip
Normal file
BIN
public/bundles/bundle-1.0.26.zip
Normal file
Binary file not shown.
Binary file not shown.
@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"version": "1.0.24",
|
"version": "1.0.26",
|
||||||
"buildId": "5a3f32bc",
|
"buildId": "ce540d0d",
|
||||||
"releasedAt": "2026-11-21T16:23:44.908Z",
|
"releasedAt": "2026-11-21T17:41:31.996Z",
|
||||||
"bundleUrl": "/bundles/bundle-1.0.24.zip",
|
"bundleUrl": "/bundles/bundle-1.0.26.zip",
|
||||||
"latestUrl": "/bundles/bundle-latest.zip",
|
"latestUrl": "/bundles/bundle-latest.zip",
|
||||||
"checksum": "6710730c8f71a8db1eef7fd4673a6633a2b590a4186ee7d500b4afb4b24bc00f",
|
"checksum": "93e2a2a6bdaca95d3c2b80a19e35ce02c89a8b2e3c7eb31a9d44d64e2bd81c29",
|
||||||
"sizeBytes": 67263
|
"sizeBytes": 67600
|
||||||
}
|
}
|
||||||
Binary file not shown.
@ -26,10 +26,10 @@ const RE_AIDER = /Aider v\d|Tokens:.*?Model:/i;
|
|||||||
// Glifos e spinners de execução / IA pensando
|
// Glifos e spinners de execução / IA pensando
|
||||||
const RE_SPINNERS = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/;
|
const RE_SPINNERS = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/;
|
||||||
const RE_CLAUDE_GLYPHS = /[✽✻✶✹✸]/;
|
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
|
// 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_SHORTCUTS = /^\??\s*for shortcuts/i;
|
||||||
const RE_AI_NAMED_IDLE = /^(?:Claude>|kiro>|gemini-cli>|aider>)\s*$/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 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 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 =
|
||||||
/\d+\s+subagent\(s\)/i.test(lastLine) ||
|
hasExplicitActiveSubagents ||
|
||||||
/●\s*Agent\(/i.test(prevLine) ||
|
(/●\s*Agent\(/i.test(prevLine) && !RE_AI_SHORTCUTS.test(lastLine) && !RE_AI_IDLE_INPUT.test(lastLine)) ||
|
||||||
RE_SPINNERS.test(prevLine) ||
|
RE_SPINNERS.test(prevLine) ||
|
||||||
RE_RUNNING_WORDS.test(prevLine);
|
RE_RUNNING_WORDS.test(prevLine);
|
||||||
|
|
||||||
// Identifica se o terminal está no prompt ocioso de entrada de um agente de IA
|
// 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_IDLE_INPUT.test(lastLine) ||
|
||||||
RE_AI_NAMED_IDLE.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);
|
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
|
// 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)) {
|
if (RE_AGY.test(tail)) {
|
||||||
return {
|
return {
|
||||||
hasAiActivity: true,
|
hasAiActivity: true,
|
||||||
aiType: 'agy',
|
aiType: 'agy',
|
||||||
shellType: null,
|
shellType: null,
|
||||||
isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && (isThinking || (/○ Thought for/i.test(tail) && !/\? for shortcuts/i.test(lastLine))),
|
isThinking: !isUsageLimit && !isEndingInAiIdlePrompt && isThinking,
|
||||||
isPaused: isUsageLimit,
|
isPaused: isUsageLimit,
|
||||||
pauseReason: isUsageLimit ? 'usage_limit' : null,
|
pauseReason: isUsageLimit ? 'usage_limit' : null,
|
||||||
pauseResetTime,
|
pauseResetTime,
|
||||||
|
|||||||
@ -500,7 +500,7 @@ $ git status
|
|||||||
'● Agent(self: Reviewer) · 1m0s',
|
'● Agent(self: Reviewer) · 1m0s',
|
||||||
'? for shortcuts auto · Orchestrator (Argon)'
|
'? for shortcuts auto · Orchestrator (Argon)'
|
||||||
].join('\n');
|
].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 = [
|
const agySubagentFooterOnly = [
|
||||||
'● Running background step',
|
'● Running background step',
|
||||||
@ -774,4 +774,54 @@ $ git status
|
|||||||
assert.strictEqual(act.isThinking, false);
|
assert.strictEqual(act.isThinking, false);
|
||||||
assert.strictEqual(act.hasInteractiveMenu, true);
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -2968,4 +2968,82 @@ Também verificamos running command e compiling no buffer.
|
|||||||
assert.deepStrictEqual(getSelectPins(), ['111111', '444444', '333333', '222222']);
|
assert.deepStrictEqual(getSelectPins(), ['111111', '444444', '333333', '222222']);
|
||||||
assert.strictEqual(document.getElementById('stations-count-badge').textContent, '2/4');
|
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 = '<span>Trabalhando...</span>';
|
||||||
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user