fix(gateway): botão desligar encerra a IA com Ctrl+C sem relançar a ferramenta

This commit is contained in:
Winícius 2026-11-22 20:28:03 -03:00
parent 19465ff33c
commit 4eb3b924d5
3 changed files with 80 additions and 282 deletions

View File

@ -258,7 +258,7 @@ Ao tocar no chip de qualquer agente ativo no topo da tela:
- **Mensagens Bidirecionais & Múltiplos Anexos:** O operador pode enviar perguntas ou instruções em linguagem natural que são despachadas via WebSocket `{ type: 'CHAT_SEND' }` até o daemon local da estação e repassadas ao agente via `maestri ask "<Agente>" "<Mensagem>"`. Suporta anexar simultaneamente múltiplas fotos da galeria (`multiple`), múltiplos documentos/logs e fotos consecutivas da câmera com acúmulo no staging flutuante (chips compactos com descarte individual `×`), compressão automática em Canvas e persistência segura em lote no disco do host.
- **Feedback Visual & Indicadores em Tempo Real:** Exibe balão e banner dinâmicos com cronômetro em segundos e ação detectada em tempo real enquanto o agente executa tarefas demoradas.
- **Painel TUI Interativo (`#chat-tui-panel` & `⌨️`):** Detecta menus interativos TUI verticais (`axis: 'vertical'`) e horizontais (`axis: 'horizontal'`, como `Permission required` do Kilo CLI) em andamento e abre automaticamente um painel acima da barra de envio com chips clicáveis de opções (com marcação `❯` na opção selecionada e navegação automática por delta de setas `↑`/`↓` ou `←`/`→` + Enter via `TERMINAL_RAW_INPUT`) além de keypad dedicado (`↑ Cima`, `↓ Baixo`, `← Esq`, `→ Dir`, `↵ Enter`, `Esc`, `Tab ⇥`, `␣ Espaço`). Quando há ações clicáveis detectadas (`options.length > 0`) e o painel não foi aberto manualmente, o keypad `.chat-tui-keypad` fica oculto (`display: none`) e o hint padrão passa a ser `Toque na ação desejada`, pois o operador não tem acesso visual ao cursor do terminal e os próprios botões já navegam por delta de setas; o keypad reaparece sem ações detectadas ou ao alternar o botão `⌨️` (`#btn-tui-toggle`). O frontend aplica `sanitizeInteractiveMenu` defensivamente sobre todo `interactiveMenu` recebido (`AGENT_TERMINAL_OUTPUT`, `AGENTS_UPDATE`, `openChatWithAgent`, `renderTuiPanel`), descartando bordas de caixa (`┃`/`│`) como opção e limpando título/hint, e reanalisando o texto bruto corrente quando um daemon legado envia a borda como opção `0`.
- **Reload / Reinício de Terminal pelo Cabeçalho (`#btn-restart-terminal`):** O cabeçalho superior do Chat disponibiliza o botão `#btn-restart-terminal` (alvo mínimo `44×44px`) ao lado de `#btn-refresh-chat` para recarregar ou reiniciar o terminal em foco via evento `RESTART_AGENT_TERMINAL`. O Gateway executa estratégia em 2 níveis via `MaestriAdapter.restartAgentTerminal`: (1) tentativa primária por `maestri recruit "<Agente>" --preset "<Preset>" --replace "<Agente>"` (ou `--command "<cmd>" --replace "<Agente>"`) e (2) fallback determinístico via `maestri ask "<Agente>" --raw` (sequência `\x03`, `/exit\n`, `\x04` e relançamento do assistente identificado por `resolveTerminalLaunchSpec`, ou `\n` em shell puro), retornando `AGENT_TERMINAL_RESTARTED`, `AGENT_TERMINAL_OUTPUT` atualizado e `AGENTS_UPDATE`. Inclui guarda em duas camadas contra auto-interrupção do daemon (`isSelf === true`, método `blocked_self` sem envio de `\x03`), bloqueio de reentrância (`.restarting`) e limpeza automática de banners e menus TUI pendentes. (Change: `docs/changes/maestri-remote-terminal-reload-restart/spec.md`)
- **Desligar / Reiniciar Terminal pelo Cabeçalho (`#btn-restart-terminal`):** O botão (alvo mínimo `44×44px`) ao lado de `#btn-refresh-chat` envia `RESTART_AGENT_TERMINAL`. O Gateway executa `MaestriAdapter.restartAgentTerminal`, que age como o operador teclando Ctrl+C: envia `\x03`; se a ferramenta de IA (agy, Claude Code, Gemini, Codex etc.) continuar ativa, envia a sequência de saída da ferramenta (`/exit\n`) e, persistindo, `\x04` (Ctrl+D). O terminal fica no prompt do shell: **a ferramenta de IA não é relançada** e `maestri recruit --replace` não é usado. Se a IA não encerrar, retorna erro (`method: interrupt_ai`). O terminal do próprio daemon (`isSelf`) continua bloqueado.
- **Isolamento de Scroll e Atualização In-Place:** O polling periódico do terminal (a cada 4s) atualiza cirurgicamente apenas os elementos de snapshot e badges sem destruir o DOM nem deslocar o scroll de leitura do operador.
---

View File

@ -378,9 +378,9 @@ export class MaestriAdapter {
}
/**
* Reinicia ou recarrega um terminal gerenciado pelo Maestri em 2 níveis:
* 1) maestri recruit --replace (em Maestro Mode)
* 2) Fallback via --raw (\x03, saída limpa e relançamento do comando ou \n no shell)
* Botão de desligar: encerra a ferramenta de IA do terminal (agy, Claude Code etc.) enviando
* Ctrl+C, a sequência de saída da ferramenta e Ctrl+D se preciso. Deixa o terminal no shell,
* sem relançar a ferramenta.
*/
async restartAgentTerminal(agentName, options = {}) {
const trimmedAgent = typeof agentName === 'string' ? agentName.trim() : '';
@ -402,38 +402,17 @@ export class MaestriAdapter {
const activityBefore = detectTerminalActivity(rawBefore);
const spec = resolveTerminalLaunchSpec(rawBefore, activityBefore);
let recruitArgs = null;
if (spec.preset) {
recruitArgs = ['recruit', trimmedAgent, '--preset', spec.preset, '--replace', trimmedAgent];
} else if (spec.command) {
recruitArgs = ['recruit', trimmedAgent, '--command', spec.command, '--replace', trimmedAgent];
}
const replaceRes = recruitArgs
? await this.runMaestri(recruitArgs)
: { ok: false, output: '', error: 'Sem preset ou comando mapeado' };
if (replaceRes.ok) {
await this.wait(this.restartDelayMs);
const updatedOutput = await this.checkAgent(trimmedAgent);
return {
ok: true,
method: 'recruit_replace',
output: updatedOutput || replaceRes.output || '',
error: null
};
}
const failRaw = (res, fallbackOut, fallbackErr) => ({
ok: false,
method: 'raw_restart',
method: 'interrupt_ai',
output: res?.output || fallbackOut || '',
error: res?.error || fallbackErr
});
// Encerra a ferramenta de IA como um Ctrl+C do operador e deixa o terminal no shell (sem relançar).
const interruptRes = await this.sendRawInput(trimmedAgent, '\\x03');
if (!interruptRes.ok) {
return failRaw(interruptRes, rawBefore, replaceRes.error || 'Falha ao enviar comando ao terminal');
return failRaw(interruptRes, rawBefore, 'Falha ao enviar comando ao terminal');
}
await this.wait(this.restartDelayMs);
@ -460,32 +439,19 @@ export class MaestriAdapter {
}
}
if (spec.command) {
if (midActivity.hasAiActivity) {
return {
ok: false,
method: 'raw_restart',
output: midOutput || '',
error: `Não foi possível encerrar a sessão ativa do assistente (${spec.command}) antes do relançamento.`
};
}
const launchRes = await this.sendRawInput(trimmedAgent, `${spec.command}\\n`);
if (!launchRes.ok) {
return failRaw(launchRes, midOutput, `Falha ao relançar ${spec.command} no terminal`);
}
await this.wait(this.restartDelayMs);
} else {
const promptRes = await this.sendRawInput(trimmedAgent, '\\n');
if (!promptRes.ok) {
return failRaw(promptRes, midOutput, 'Falha ao reativar prompt do terminal');
}
if (spec.command && midActivity.hasAiActivity) {
return {
ok: false,
method: 'interrupt_ai',
output: midOutput || '',
error: `Não foi possível encerrar a sessão ativa do assistente (${spec.command}).`
};
}
const finalOutput = await this.checkAgent(trimmedAgent);
return {
ok: true,
method: 'raw_restart',
output: finalOutput || midOutput || '',
method: 'interrupt_ai',
output: midOutput || '',
error: null
};
}

View File

@ -799,268 +799,100 @@ test('MaestriAdapter.restartAgentTerminal deve bloquear reinício do próprio da
const workerOk = await adapter.restartAgentTerminal('Worker');
assert.equal(workerOk.ok, true);
assert.equal(workerOk.method, 'recruit_replace');
assert.equal(workerOk.method, 'interrupt_ai');
const forcedAllowSelfFalse = await adapter.restartAgentTerminal('maestri-remote-self', { isSelf: false });
assert.equal(forcedAllowSelfFalse.ok, true);
assert.equal(forcedAllowSelfFalse.method, 'recruit_replace');
assert.equal(forcedAllowSelfFalse.method, 'interrupt_ai');
});
test('MaestriAdapter.restartAgentTerminal deve tentar recruit --replace com preset ou comando quando em Maestro Mode', async () => {
const cliCalls = [];
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
let checkCount = 0;
adapter.runMaestri = async (args) => {
cliCalls.push(args);
if (args[0] === 'check') {
checkCount++;
if (checkCount === 1) {
return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle\n❯ ' };
}
return { ok: true, output: 'Claude Code reiniciado\n❯ ' };
}
if (args[0] === 'recruit') {
return { ok: true, output: 'Recreated Claude' };
}
return { ok: false, output: '' };
};
const resPreset = await adapter.restartAgentTerminal('Claude');
assert.equal(resPreset.ok, true);
assert.equal(resPreset.method, 'recruit_replace');
assert.equal(resPreset.error, null);
assert.ok(resPreset.output.includes('Claude Code reiniciado'));
assert.deepEqual(cliCalls[1], ['recruit', 'Claude', '--preset', 'Claude Code', '--replace', 'Claude']);
// Caso sem preset mapeado (gemini): usa --command
cliCalls.length = 0;
checkCount = 0;
adapter.runMaestri = async (args) => {
cliCalls.push(args);
if (args[0] === 'check') {
checkCount++;
return checkCount === 1
? { ok: true, output: 'Gemini CLI\nType your message or @path/to/file' }
: { ok: true, output: 'Gemini CLI pronto' };
}
if (args[0] === 'recruit') {
return { ok: true, output: 'Recreated Gemini' };
}
return { ok: false, output: '' };
};
const resCmd = await adapter.restartAgentTerminal('Gemini');
assert.equal(resCmd.ok, true);
assert.equal(resCmd.method, 'recruit_replace');
assert.deepEqual(cliCalls[1], ['recruit', 'Gemini', '--command', 'gemini', '--replace', 'Gemini']);
});
test('MaestriAdapter.restartAgentTerminal deve usar fallback --raw (\\x03 -> /exit -> \\x04 -> relançar) ou \\n em shell e tratar falha', async () => {
test('MaestriAdapter.restartAgentTerminal deve encerrar a IA com Ctrl+C e deixar o terminal no shell, sem recruit nem relançar', async () => {
const rawInputs = [];
const calls = [];
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
let checkSeq = 0;
// 1. Fluxo completo IA: recruit falha -> \x03 -> ainda IA -> /exit\n -> ainda IA -> \x04 -> shell -> claude\n
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') {
return { ok: false, output: '', error: 'Maestro Mode is required for recruit' };
}
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
if (checkSeq === 2) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' }; // após \x03 ainda ativo
if (checkSeq === 3) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' }; // após /exit\n ainda ativo
if (checkSeq === 4) return { ok: true, output: 'PS C:\\Users\\dev> ' }; // após \x04 voltou ao shell
return { ok: true, output: 'Claude Code reiniciado via raw\n❯ ' }; // após claude\n
}
return { ok: false, output: '' };
const setup = (checks) => {
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
calls.push(args);
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
const out = checks[Math.min(checkSeq, checks.length - 1)];
checkSeq++;
return { ok: true, output: out };
}
return { ok: false, output: '' };
};
};
const AI = 'Claude Code v2.1\nshift+tab to cycle';
const SH = 'PS C:\\Users\\dev> ';
const aiFallbackRes = await adapter.restartAgentTerminal('Claude');
assert.equal(aiFallbackRes.ok, true);
assert.equal(aiFallbackRes.method, 'raw_restart');
assert.equal(aiFallbackRes.error, null);
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04', 'claude\\n']);
assert.ok(aiFallbackRes.output.includes('Claude Code reiniciado via raw'));
// 1. Ctrl+C basta
setup([AI, SH]);
const r1 = await adapter.restartAgentTerminal('Claude');
assert.equal(r1.ok, true);
assert.equal(r1.method, 'interrupt_ai');
assert.deepEqual(rawInputs, ['\\x03']);
assert.equal(calls.some((c) => c[0] === 'recruit'), false, 'Nunca deve acionar recruit');
// 2. Shell puro: recruit falha -> \x03 -> \n
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') {
return { ok: false, output: '', error: 'Not in maestro mode' };
}
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq <= 2) return { ok: true, output: 'PS D:\\proj> ' };
return { ok: true, output: 'PS D:\\proj> prompt limpo' };
}
return { ok: false, output: '' };
};
// 2. Ctrl+C -> /exit
setup([AI, AI, SH]);
const r2 = await adapter.restartAgentTerminal('Claude');
assert.equal(r2.ok, true);
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n']);
const shellFallbackRes = await adapter.restartAgentTerminal('TermShell');
assert.equal(shellFallbackRes.ok, true);
assert.equal(shellFallbackRes.method, 'raw_restart');
assert.deepEqual(rawInputs, ['\\x03', '\\n']);
assert.ok(shellFallbackRes.output.includes('prompt limpo'));
// 3. Ctrl+C -> /exit -> Ctrl+D
setup([AI, AI, AI, SH]);
const r3 = await adapter.restartAgentTerminal('Claude');
assert.equal(r3.ok, true);
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
// 3. Falha ao enviar \x03 inicial deve abortar e retornar ok: false preservando rawBefore quando output vier vazio
rawInputs.length = 0;
// 4. Shell puro: só Ctrl+C, nenhum \n nem relançamento
setup([SH]);
const r4 = await adapter.restartAgentTerminal('TermShell');
assert.equal(r4.ok, true);
assert.deepEqual(rawInputs, ['\\x03']);
// 5. IA que não fecha: ok false
setup([AI]);
const r5 = await adapter.restartAgentTerminal('Claude');
assert.equal(r5.ok, false);
assert.equal(r5.method, 'interrupt_ai');
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
assert.match(r5.error, /Não foi possível encerrar/);
// 6. Falha ao enviar Ctrl+C inicial preserva a saída anterior
adapter.runMaestri = async (args) => {
if (args[0] === 'check') return { ok: true, output: 'PS D:\\proj> travado' };
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
return { ok: false, output: '', error: 'IPC timeout' };
}
if (args[0] === 'ask' && args[2] === '--raw') return { ok: false, output: '', error: 'IPC timeout' };
return { ok: false, output: '' };
};
const r6 = await adapter.restartAgentTerminal('TermTravado');
assert.equal(r6.ok, false);
assert.equal(r6.output, 'PS D:\\proj> travado');
assert.match(r6.error, /IPC timeout/);
const failRes = await adapter.restartAgentTerminal('TermTravado');
assert.equal(failRes.ok, false);
assert.equal(failRes.method, 'raw_restart');
assert.equal(failRes.output, 'PS D:\\proj> travado');
assert.match(failRes.error, /IPC timeout/);
// 4. Quando generic_ai não tem preset/command, pula recruit e usa fallback --raw sem erro
const calledRecruit = [];
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') {
calledRecruit.push(args);
return { ok: true, output: 'should not happen' };
}
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq === 1) return { ok: true, output: '⠋ thinking...' }; // generic_ai
return { ok: true, output: '⠋ thinking still...' };
}
return { ok: false, output: '' };
};
const genericRawRes = await adapter.restartAgentTerminal('GenericAgent');
assert.equal(calledRecruit.length, 0, 'Sem preset/command não deve acionar recruit');
assert.deepEqual(rawInputs, ['\\x03', '\\n'], 'Sem command não deve chamar /exit mesmo se ainda ativo');
assert.equal(genericRawRes.ok, true);
// 5. Quando \x03 sozinho já volta ao shell, não envia /exit\n nem \x04; apenas relança claude\n
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
if (checkSeq === 2) return { ok: true, output: 'PS D:\\proj> ' };
return { ok: true, output: 'Claude Code ok' };
}
return { ok: false, output: '' };
};
await adapter.restartAgentTerminal('Claude');
assert.deepEqual(rawInputs, ['\\x03', 'claude\\n']);
// 6. Quando /exit\n volta ao shell, não envia \x04; apenas relança claude\n
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq <= 2) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
if (checkSeq === 3) return { ok: true, output: 'PS D:\\proj> ' };
return { ok: true, output: 'Claude Code ok' };
}
return { ok: false, output: '' };
};
await adapter.restartAgentTerminal('Claude');
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', 'claude\\n']);
// 7. Quando spec.command existe e ainda continua em IA após \x04, não envia \n solto e retorna ok: false
rawInputs.length = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
return { ok: true, output: '' };
}
if (args[0] === 'check') {
return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
}
return { ok: false, output: '' };
};
const stuckRes = await adapter.restartAgentTerminal('Claude');
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
assert.equal(stuckRes.ok, false);
assert.equal(stuckRes.method, 'raw_restart');
assert.match(stuckRes.error, /Não foi possível encerrar/);
// 8. Falha intermediária em exitSequence, EOF (\x04), relançamento ou \n de shell deve retornar ok: false sem silenciosamente passar
for (const [failingSeq, agentLabel, expectedCount, checkOut] of [
['/exit\\n', 'Claude', 2, 'Claude Code v2.1\nshift+tab to cycle'],
['\\x04', 'Claude', 3, 'Claude Code v2.1\nshift+tab to cycle'],
['\\n', 'TermShell', 2, 'PS D:\\proj> ']
]) {
// 7. Falha na sequência de saída ou no EOF retorna ok false
for (const [failingSeq, expectedCount] of [['/exit\\n', 2], ['\\x04', 3]]) {
const seqLog = [];
let checks = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
seqLog.push(args[3]);
if (args[3] === failingSeq) return { ok: false, output: '', error: `falha_${failingSeq}` };
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checks++;
return { ok: true, output: checkOut };
}
if (args[0] === 'check') return { ok: true, output: AI };
return { ok: false, output: '' };
};
const midFailRes = await adapter.restartAgentTerminal(agentLabel);
assert.equal(midFailRes.ok, false, `Falha em ${failingSeq} deve retornar ok: false`);
const rf = await adapter.restartAgentTerminal('Claude');
assert.equal(rf.ok, false);
assert.equal(seqLog.length, expectedCount);
assert.match(midFailRes.error, new RegExp(`falha_${failingSeq.replace('\\', '\\\\')}`));
}
rawInputs.length = 0;
checkSeq = 0;
adapter.runMaestri = async (args) => {
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
if (args[0] === 'ask' && args[2] === '--raw') {
rawInputs.push(args[3]);
if (args[3] === 'claude\\n') return { ok: false, output: '', error: 'relaunch_timeout' };
return { ok: true, output: '' };
}
if (args[0] === 'check') {
checkSeq++;
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
return { ok: true, output: 'PS D:\\proj> ' };
}
return { ok: false, output: '' };
};
const relaunchFail = await adapter.restartAgentTerminal('Claude');
assert.equal(relaunchFail.ok, false);
assert.match(relaunchFail.error, /relaunch_timeout/);
// 9. Atraso positivo real no wait() quando restartDelayMs > 0
const timedAdapter = new MaestriAdapter({ restartDelayMs: 15 });
const t0 = Date.now();