krnell 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/painel.py CHANGED
@@ -16,6 +16,7 @@ import base64
16
16
  import contextlib
17
17
  import copy
18
18
  import ctypes
19
+ from datetime import datetime
19
20
  import signal
20
21
  from html.parser import HTMLParser
21
22
  from http.client import HTTPException
@@ -509,6 +510,47 @@ def _cor_fracao(frac) -> str:
509
510
  return ERRO
510
511
 
511
512
 
513
+ def _fmt_duracao_unica(segundos) -> str:
514
+ """Formata tempo restante em unidade única: 7d, 23h, 59m, 59s."""
515
+ try:
516
+ sec = int(round(float(segundos)))
517
+ except (TypeError, ValueError):
518
+ return ''
519
+ if sec <= 0:
520
+ return '0s'
521
+ if sec >= 86400:
522
+ return f'{sec // 86400}d'
523
+ if sec >= 3600:
524
+ return f'{sec // 3600}h'
525
+ if sec >= 60:
526
+ return f'{sec // 60}m'
527
+ return f'{sec}s'
528
+
529
+
530
+ def _reset_restante_bucket(b: dict | None) -> str:
531
+ if not isinstance(b, dict):
532
+ return ''
533
+ reset_iso = b.get('resetTime')
534
+ if isinstance(reset_iso, str) and reset_iso.strip():
535
+ try:
536
+ iso = reset_iso.strip()
537
+ if iso.endswith('Z'):
538
+ iso = iso[:-1] + '+00:00'
539
+ alvo = datetime.fromisoformat(iso).timestamp()
540
+ return _fmt_duracao_unica(max(0, alvo - time.time()))
541
+ except ValueError:
542
+ pass
543
+ sec = b.get('resetInSeconds')
544
+ if isinstance(sec, (int, float)):
545
+ return _fmt_duracao_unica(max(0, sec))
546
+ human = str(b.get('resetHuman') or '').strip()
547
+ if human:
548
+ # Extrai a primeira unidade (ex.: "6d 23h" -> "6d")
549
+ m = re.search(r'(\d+\s*[dhms])', human)
550
+ return m.group(1).replace(' ', '') if m else human.replace(' ', '')
551
+ return ''
552
+
553
+
512
554
  def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> tuple[str, str]:
513
555
  if not isinstance(b, dict):
514
556
  return '', FRACO
@@ -517,8 +559,8 @@ def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> t
517
559
  return '', FRACO
518
560
  valor = b.get('remainingPercent')
519
561
  pct = float(valor) if isinstance(valor, (int, float)) else float(frac) * 100
520
- reset = str(b.get('resetHuman') or '').replace(' ', '') if com_reset else ''
521
- txt = f'{prefixo} {pct:.1f}%' + (f' ({reset})' if reset and pct < 100 else '')
562
+ reset = _reset_restante_bucket(b) if com_reset else ''
563
+ txt = f'{prefixo} {pct:.1f}%' + (f' ({reset})' if reset else '')
522
564
  return txt, _cor_fracao(frac)
523
565
 
524
566
 
@@ -526,7 +568,19 @@ def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> t
526
568
  _SPIN_BRAILLE = ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏')
527
569
  _PULSO_ONLINE = ('●', '●', '●', '◉', '◉', '●')
528
570
  _ONDA_LIVE = ('▁▂▃▄', '▂▃▄▅', '▃▄▅▆', '▄▅▆▇', '▅▆▇▆', '▆▇▆▅', '▇▆▅▄', '▆▅▄▃', '▅▄▃▂', '▄▃▂▁')
529
- _GLIFO_MARCA = ('◈', '◈', '◇', '◈', '◈', '◈', '◈', '◈')
571
+ _GLIFO_MARCA = ('◈',)
572
+ # Wordmark pixel-block estilo OpenCode (duas cores: "krn" + "ell", 30 cols)
573
+ _LOGO_KRNELL = (
574
+ ('█ ▄▀ █▀▀▄ █▀▀▄ ', '█▀▀█ █ █ '),
575
+ ('█▄▀ █▄▄▀ █ █ ', '█▀▀ █ █ '),
576
+ ('█ ▀▄ █ █ █ █ ', '▀▀▀▀ ▀▀▀▀ ▀▀▀▀'),
577
+ )
578
+ _DICAS_HOME = (
579
+ '/ commands · /connect · /model',
580
+ 'Try "/model" to switch between NVIDIA & Antigravity',
581
+ 'Try "/quota" to inspect live 5h & 7d quotas',
582
+ 'Try "/connect" to add API keys or Google OAuth',
583
+ )
530
584
 
531
585
 
532
586
  def versao_local() -> str:
@@ -845,10 +899,42 @@ class Coletor(threading.Thread):
845
899
  # Formatacao
846
900
  # ---------------------------------------------------------------------------
847
901
 
902
+ _TZ_LOCAL_CACHE = None
903
+
904
+
905
+ def _tz_local():
906
+ """Detecta fuso real do dispositivo (inclusive Android/proot quando /etc/localtime está em UTC)."""
907
+ global _TZ_LOCAL_CACHE
908
+ if _TZ_LOCAL_CACHE is not None:
909
+ return _TZ_LOCAL_CACHE
910
+ from zoneinfo import ZoneInfo
911
+ candidatos = [os.environ.get('TZ', '').strip()]
912
+ if not candidatos[0]:
913
+ try:
914
+ prop = subprocess.run(['getprop', 'persist.sys.timezone'], capture_output=True, text=True, timeout=1.0)
915
+ if prop.returncode == 0 and prop.stdout.strip():
916
+ candidatos.append(prop.stdout.strip())
917
+ except OSError:
918
+ pass
919
+ for nome in candidatos:
920
+ if not nome:
921
+ continue
922
+ try:
923
+ _TZ_LOCAL_CACHE = ZoneInfo(nome)
924
+ return _TZ_LOCAL_CACHE
925
+ except Exception:
926
+ continue
927
+ _TZ_LOCAL_CACHE = False
928
+ return _TZ_LOCAL_CACHE
929
+
930
+
848
931
  def fmt_hora(ts) -> str:
849
932
  try:
933
+ tz = _tz_local()
934
+ if tz:
935
+ return datetime.fromtimestamp(float(ts), tz=tz).strftime('%H:%M:%S')
850
936
  return time.strftime('%H:%M:%S', time.localtime(float(ts)))
851
- except (TypeError, ValueError):
937
+ except (TypeError, ValueError, OSError):
852
938
  return '--:--:--'
853
939
 
854
940
 
@@ -1133,6 +1219,7 @@ class Painel:
1133
1219
  self.proc = None
1134
1220
  self.tarefa_ativa = False
1135
1221
  self.saindo = False
1222
+ self._sair_em_background = False # Ctrl+C fecha TUI mantendo bridge vivo; /exit para tudo
1136
1223
  self.revisao_vista = -1
1137
1224
  self.scroll = 0
1138
1225
  self.ultima_acao = None
@@ -1169,12 +1256,20 @@ class Painel:
1169
1256
  self._ag_auth_state = ''
1170
1257
  self._anim_tick = 0
1171
1258
  self._anim_ultimo = 0.0
1259
+ self._intro_frame = 0 # animação de abertura do logo/tela (0..3)
1260
+ self._fechar_overlay_frame = 0 # animação rápida de fechamento (0=inativo)
1261
+ self._fechar_overlay_linhas: list[str] = []
1262
+ self._digito_pulso = 0.0 # timestamp do último caractere digitado (brilho no prompt ▸)
1263
+ self._dica_idx = 0
1264
+ self._dica_chars = 0
1265
+ self._dica_ultimo = 0.0
1172
1266
  self._dialogo_frame = 0 # animacao de abertura do dialogo
1173
1267
  self._dialogo_id = None
1174
1268
  self._reexec_solicitado = False # /restart na TUI reexecuta painel.py do zero
1175
1269
  self._reexec_comando = None # update reabre pelo entrypoint npm recém-instalado
1176
1270
  self._restart_overlay = None # estado da animacao de reinicio estilo OpenCode
1177
1271
  self.atualizacoes = atualizador.MonitorAtualizacao(versao_local())
1272
+ self._update_revisao_vista = -1
1178
1273
  self._update_zona = None # (y, x inicial, x final) do pill opcional no header
1179
1274
  self._update_hover = False
1180
1275
  self.modo = 'repl'
@@ -1275,7 +1370,7 @@ class Painel:
1275
1370
  cab.add_column(ratio=1, no_wrap=True)
1276
1371
  cab.add_column(justify='right', no_wrap=True)
1277
1372
  titulo = Text()
1278
- glifo = _GLIFO_MARCA[tick % len(_GLIFO_MARCA)] if online else '◇'
1373
+ glifo = '◈' if online else '◇'
1279
1374
  titulo.append(f'{glifo} ', style=f'bold {ACENTO}')
1280
1375
  titulo.append('krnell', style=f'bold {TEXTO}')
1281
1376
  if largura >= 34:
@@ -1303,17 +1398,42 @@ class Painel:
1303
1398
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
1304
1399
  cab.add_row(titulo, estado)
1305
1400
 
1401
+ # Wordmark pixel-block "krnell" centralizado estilo OpenCode (com espaço vertical)
1402
+ logo_blocos: list = []
1403
+ if largura >= 36 and altura >= 16:
1404
+ intro = getattr(self, '_intro_frame', 99)
1405
+ mostrar_linhas = 3 if intro >= 3 else max(1, intro + 1)
1406
+ pad_logo = ' ' * max(0, (largura - 30) // 2)
1407
+ for idx_l, (esq_l, dir_l) in enumerate(_LOGO_KRNELL[:mostrar_linhas]):
1408
+ tl = Text(no_wrap=True)
1409
+ tl.append(pad_logo)
1410
+ tl.append(esq_l, style=f'bold {FRACO if intro == 0 else TEXTO}')
1411
+ tl.append(dir_l, style=f'bold {ACENTO}')
1412
+ logo_blocos.append(tl)
1413
+ if disponivel:
1414
+ pill = f" ↑ update v{disponivel['version']} available · tap or /update "
1415
+ pill_vis = tui_core.truncate_vis(pill, max(16, largura - 2))
1416
+ pad_p = ' ' * max(0, (largura - cell_len(pill_vis)) // 2)
1417
+ tp = Text(no_wrap=True)
1418
+ tp.append(pad_p)
1419
+ tp.append(pill_vis, style=f'bold {ACENTO3 if self._update_hover else ACENTO} on {FUNDO}')
1420
+ logo_blocos.append(tp)
1421
+ logo_blocos.append(Text(''))
1422
+
1306
1423
  usar_overlay = self.modo == 'tui'
1307
1424
  menu_render = self._render_menu()
1308
1425
  modais_render = [] if usar_overlay else self._render_modais(largura)
1309
1426
  extra = sum(len(self._linhas(x, largura)) for x in (menu_render, modais_render) if x)
1310
- espaco_corpo = max(5, altura - 7 - extra)
1311
- info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if largura < 96 else []
1312
- if espaco_corpo < len(info_compacta) + 5:
1427
+ # Só usa layout de 2 colunas quando houver largura real confortável para ambas
1428
+ # (evita quebrar "7d 20.9%" em 2 linhas no meio do zoom do celular).
1429
+ duas_colunas = largura >= 108
1430
+ espaco_corpo = max(4, altura - 7 - len(logo_blocos) - extra)
1431
+ info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if not duas_colunas else []
1432
+ if espaco_corpo < len(info_compacta) + 4:
1313
1433
  info_compacta = info_compacta[:1]
1314
1434
  linhas_req = max(2, min(espaco_corpo - len(info_compacta), 48))
1315
- estreito = largura < 74
1316
- ultra_estreito = largura < 46
1435
+ estreito = largura < 78
1436
+ ultra_estreito = largura < 48
1317
1437
 
1318
1438
  reqs = snap.get('requests') or []
1319
1439
  visiveis = max(1, linhas_req - 1)
@@ -1359,8 +1479,9 @@ class Painel:
1359
1479
  obs = Text(str(evento.get('error') or ('stream' if evento.get('stream') else '')),
1360
1480
  style=ERRO if evento.get('error') else FRACO)
1361
1481
  hora = fmt_hora(evento.get('ts'))
1482
+ rotulo_ev = str(evento.get('model') or evento.get('account') or '—')
1362
1483
  linha_req(hora[:5] if estreito else hora, cel_codigo,
1363
- str(evento.get('account') or evento.get('model') or '—'),
1484
+ rotulo_ev,
1364
1485
  fmt_duracao(evento.get('ms')), fmt_tokens(evento.get('tokens')), obs)
1365
1486
  for item in em_voo:
1366
1487
  sp = _SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]
@@ -1369,8 +1490,9 @@ class Painel:
1369
1490
  style=ACENTO2 if item.get('tok_s') else AVISO)
1370
1491
  saida = (('~' if not item.get('exato') else '') + fmt_tokens_grande(item['tokens_out'])
1371
1492
  if item.get('tokens_out') else '—')
1493
+ rotulo_live = str(item.get('modelo') or item.get('model') or item.get('conta') or item.get('rota') or '—')
1372
1494
  linha_req(Text('now', style=ACENTO2), Text(f'{sp} live', style=ACENTO2),
1373
- str(item.get('conta') or item.get('rota') or '—'),
1495
+ rotulo_live,
1374
1496
  fmt_duracao((item.get('segundos') or 0) * 1000), saida, obs_live)
1375
1497
  vazio_row = ('', '', '', '', '', '')[:len(tabela.columns)]
1376
1498
  for _ in range(max(0, visiveis - len(fatia) - len(em_voo))):
@@ -1388,10 +1510,17 @@ class Painel:
1388
1510
  atividade.add_row(tabela)
1389
1511
 
1390
1512
  renderaveis = [cab, Text('')]
1391
- if largura >= 96:
1513
+ renderaveis.extend(logo_blocos)
1514
+ if disponivel and logo_blocos:
1515
+ # Guarda zona clicável do banner central de update também
1516
+ y_banner = 2 + len(_LOGO_KRNELL)
1517
+ self._update_banner_zona = (y_banner, 0, max(0, largura - 1))
1518
+ else:
1519
+ self._update_banner_zona = None
1520
+ if duas_colunas:
1392
1521
  grade = Table.grid(expand=True, padding=(0, 2, 0, 0))
1393
1522
  grade.add_column(ratio=3)
1394
- grade.add_column(ratio=1)
1523
+ grade.add_column(min_width=30, ratio=1)
1395
1524
  grade.add_row(atividade, self._lado_minimo(snap, online, status))
1396
1525
  renderaveis.append(grade)
1397
1526
  else:
@@ -1416,22 +1545,30 @@ class Painel:
1416
1545
 
1417
1546
  def _lado_minimo(self, snap: dict, online: bool, status: dict) -> Text:
1418
1547
  """Apenas dados vivos; diagnóstico e pool detalhado ficam em /status."""
1419
- lado = Text()
1548
+ lado = Text(no_wrap=True, overflow='ellipsis')
1420
1549
  ag_status = snap.get('ag_status') if isinstance(snap.get('ag_status'), dict) else {}
1421
1550
  resumo = _resumo_cota_antigravity(ag_status)
1422
1551
  if resumo:
1423
1552
  lado.append('Antigravity\n', style=FRACO)
1424
1553
  for item in resumo[:2]:
1425
- lado.append(f"{item['nome']:<8}", style=TEXTO)
1426
- t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1554
+ lado.append(f"{item['nome']:<7}", style=TEXTO)
1555
+ # Ordem limpa: 7d primeiro e 5h depois (sem parênteses cortando);
1556
+ # o tempo de reset vem logo abaixo numa linha dedicada.
1427
1557
  ts, cs = _fmt_bucket_curto(item.get('bsem'), '7d', com_reset=False)
1428
- if t5:
1429
- lado.append(t5, style=c5)
1430
- if t5 and ts:
1431
- lado.append(' ', style=BORDA)
1558
+ t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1432
1559
  if ts:
1433
1560
  lado.append(ts, style=cs)
1561
+ if ts and t5:
1562
+ lado.append(' ', style=BORDA)
1563
+ if t5:
1564
+ lado.append(t5, style=c5)
1434
1565
  lado.append('\n')
1566
+ primeiro_item = resumo[0]
1567
+ r5 = _reset_restante_bucket(primeiro_item.get('b5h'))
1568
+ r7 = _reset_restante_bucket(primeiro_item.get('bsem'))
1569
+ partes_r = [p for p in (f'diário {r5}' if r5 else '', f'semanal {r7}' if r7 else '') if p]
1570
+ if partes_r:
1571
+ lado.append('reseta ' + ' · '.join(partes_r) + '\n', style=FRACO)
1435
1572
  tokens_mes = snap.get('tokens_mes') or {}
1436
1573
  total_mes = int(tokens_mes.get('total') or 0)
1437
1574
  if total_mes:
@@ -1467,12 +1604,18 @@ class Painel:
1467
1604
  resumo = _resumo_cota_antigravity(ag_status)
1468
1605
  for idx, item in enumerate(resumo[:2]):
1469
1606
  if idx:
1470
- segunda.append(' · ' if self.largura < 50 else ' · ', style=BORDA)
1471
- segunda.append(item['nome'][0], style=FRACO)
1472
- for bucket, prefixo in ((item.get('b5h'), '5h'), (item.get('bsem'), '7d')):
1607
+ segunda.append(' · ' if self.largura < 50 else ' │ ', style=BORDA)
1608
+ segunda.append(item['nome'][0], style=ACENTO)
1609
+ for bucket, prefixo in ((item.get('bsem'), '7d'), (item.get('b5h'), '5h')):
1473
1610
  texto, cor = _fmt_bucket_curto(bucket, prefixo, com_reset=False)
1474
1611
  if texto:
1475
1612
  segunda.append(' ' + texto, style=cor)
1613
+ if resumo:
1614
+ r5 = _reset_restante_bucket(resumo[0].get('b5h'))
1615
+ r7 = _reset_restante_bucket(resumo[0].get('bsem'))
1616
+ partes_r = [p for p in (f'diário {r5}' if r5 else '', f'semanal {r7}' if r7 else '') if p]
1617
+ if partes_r and self.largura >= 46:
1618
+ segunda.append(' · reseta ' + ' · '.join(partes_r), style=FRACO)
1476
1619
  if not segunda.plain:
1477
1620
  total = int((snap.get('tokens_mes') or {}).get('total') or 0)
1478
1621
  segunda.append(f'{fmt_tokens_grande(total)} tok this month' if total else
@@ -2381,12 +2524,14 @@ class Painel:
2381
2524
  self.menu_off = False
2382
2525
  self.menu_sel = 0
2383
2526
  return True
2384
- # Tocar na linha de cotas da home (linha 3 em telas estreitas ou coluna direita) abre /quota
2527
+ # Tocar na linha de cotas da home (logo abaixo do cabeçalho/logo) abre /quota
2385
2528
  if not self._menu_aberto():
2386
- if self.largura < 96 and y == 3:
2529
+ y_cota = 3 + (len(_LOGO_KRNELL) + 1 + (1 if self.atualizacoes.disponivel else 0)
2530
+ if (self.largura >= 36 and self.altura >= 16) else 0)
2531
+ if self.largura < 108 and y == y_cota:
2387
2532
  self.mostrar_tokens()
2388
2533
  return True
2389
- if self.largura >= 96 and y in (2, 3, 4) and x >= int(self.largura * 0.72):
2534
+ if self.largura >= 108 and y >= 2 and x >= int(self.largura * 0.72):
2390
2535
  self.mostrar_tokens()
2391
2536
  return True
2392
2537
  return False
@@ -2427,11 +2572,19 @@ class Painel:
2427
2572
  return True
2428
2573
 
2429
2574
  def ponto_no_botao_update(self, x: int, y: int) -> bool:
2430
- zona = self._update_zona
2431
- if not zona or self.modal or self.wizard or self._restart_overlay:
2575
+ if self.modal or self.wizard or self._restart_overlay:
2432
2576
  return False
2433
- linha, inicio, fim = zona
2434
- return y == linha and inicio <= x <= fim
2577
+ zona = self._update_zona
2578
+ if zona:
2579
+ linha, inicio, fim = zona
2580
+ if y == linha and inicio <= x <= fim:
2581
+ return True
2582
+ banner = getattr(self, '_update_banner_zona', None)
2583
+ if banner:
2584
+ linha_b, ini_b, fim_b = banner
2585
+ if y == linha_b and ini_b <= x <= fim_b:
2586
+ return True
2587
+ return False
2435
2588
 
2436
2589
  def clicar_botao_update(self, x: int, y: int) -> bool:
2437
2590
  if not self.ponto_no_botao_update(x, y):
@@ -2545,21 +2698,39 @@ class Painel:
2545
2698
  frame.append('')
2546
2699
  self.ultima_contagem = len(frame)
2547
2700
  base = len(frame)
2548
- buf = ['\x1b[?2026h\x1b[H']
2549
- if getattr(self, '_precisa_limpar_tela', False):
2550
- buf.append('\x1b[2J')
2551
- self._precisa_limpar_tela = False
2552
- for idx, linha in enumerate(frame, 1):
2553
- buf.append(f'\x1b[{idx};1H\x1b[2K' + linha + '\x1b[0m\x1b[K')
2701
+ linhas_novas = [linha + '\x1b[0m' for linha in frame]
2554
2702
  regua = '─' * max(6, largura - 2)
2555
- buf.append(f'\x1b[{base + 1};1H\x1b[2K' + ansi('borda') + '╭' + regua + '╮' + RESET)
2556
- buf.append(self._formatar_caixa(base + 2))
2557
- buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2703
+ linhas_novas.append(ansi('borda') + '╭' + regua + '╮' + RESET)
2704
+ linhas_novas.append(self._formatar_caixa(base + 2))
2705
+ linhas_novas.append(ansi('borda') + '╰' + regua + '╯' + RESET)
2558
2706
  self._status_y = base + 3
2559
- buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2560
- # Quando um menu ou modal ocupa a caixa, oculta o cursor nativo para não
2561
- # deixar um bloquinho branco piscando no meio da tela.
2562
- if self.modal or (self.wizard and self._wizard_lista()):
2707
+ linhas_novas.append(self._barra_status())
2708
+
2709
+ # Diff por linha: só reescreve o que realmente mudou (exceto em clear/resize),
2710
+ # eliminando o piscamento no Termux e em terminais Android.
2711
+ limpar = bool(getattr(self, '_precisa_limpar_tela', False))
2712
+ anteriores = None if limpar else getattr(self, '_frame_anterior', None)
2713
+ if anteriores is not None and len(anteriores) != len(linhas_novas):
2714
+ anteriores = None
2715
+ buf = ['\x1b[?2026h']
2716
+ if limpar:
2717
+ buf.append('\x1b[H\x1b[2J')
2718
+ self._precisa_limpar_tela = False
2719
+ for idx, texto in enumerate(linhas_novas, 1):
2720
+ if anteriores is not None and anteriores[idx - 1] == texto:
2721
+ continue
2722
+ if idx == base + 2 and texto.startswith('\x1b['):
2723
+ # _formatar_caixa já traz posicionamento \x1b[row;1H\x1b[2K
2724
+ buf.append(texto)
2725
+ else:
2726
+ buf.append(f'\x1b[{idx};1H\x1b[2K' + texto + '\x1b[K')
2727
+ if limpar:
2728
+ buf.append('\x1b[J')
2729
+ self._frame_anterior = list(linhas_novas)
2730
+ # Oculta o cursor nativo do terminal em listas/modais e quando a caixa está
2731
+ # vazia (evita o ponto/bloco branco piscando sozinho no Termux/celular).
2732
+ mostrar_cursor = bool(self.buf) or (self.wizard and not self._wizard_lista())
2733
+ if self.modal or not mostrar_cursor:
2563
2734
  buf.append('\x1b[?25l\x1b[?2026l')
2564
2735
  else:
2565
2736
  coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
@@ -2817,22 +2988,34 @@ class Painel:
2817
2988
  visivel = self._texto_entrada()
2818
2989
  largura = self.largura
2819
2990
  contagem = cell_len(visivel)
2991
+ # Pulso visual sutil no "▸" enquanto o usuário digita
2992
+ pulso_ativo = (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.16
2993
+ cor_prompt = 'acento3' if pulso_ativo else 'acento'
2820
2994
  partes = [
2821
2995
  f'\x1b[{linha};1H\x1b[2K',
2822
- ansi('borda'), '│', RESET, ' ', ansi('acento'), '▸ ', RESET,
2996
+ ansi('borda'), '│', RESET, ' ', ansi(cor_prompt), '▸ ', RESET,
2823
2997
  ]
2824
2998
  if visivel:
2825
2999
  partes.extend([ansi('texto'), visivel, RESET])
3000
+ # Cursor de digitação limpo (barra fina) quando há texto sendo digitado
3001
+ if pulso_ativo and contagem + 1 <= max(1, largura - 6):
3002
+ partes.extend([ansi('acento'), '▏', RESET])
3003
+ contagem += 1
2826
3004
  elif self._wizard_lista():
2827
3005
  dica = 'filtrar…'
2828
3006
  partes.extend([ansi('fraco'), dica, RESET])
2829
3007
  contagem = cell_len(dica)
2830
3008
  elif not self.wizard:
2831
- dica = '/ commands · Ctrl+L connect · Ctrl+P palette'
2832
- if cell_len(dica) > largura - 8:
2833
- dica = '/ commands · /connect'
2834
- if cell_len(dica) > largura - 8:
2835
- dica = '/help'
3009
+ dica_cheia = _DICAS_HOME[getattr(self, '_dica_idx', 0) % len(_DICAS_HOME)]
3010
+ if cell_len(dica_cheia) > largura - 8:
3011
+ dica_cheia = '/ commands · /connect'
3012
+ if cell_len(dica_cheia) > largura - 8:
3013
+ dica_cheia = '/help'
3014
+ n_chars = getattr(self, '_dica_chars', len(dica_cheia))
3015
+ if n_chars <= 0 or n_chars >= len(dica_cheia):
3016
+ dica = dica_cheia
3017
+ else:
3018
+ dica = dica_cheia[:n_chars] + '▏'
2836
3019
  dica = tui_core.truncate_vis(dica, max(1, largura - 7))
2837
3020
  partes.extend([ansi('fraco'), dica, RESET])
2838
3021
  contagem = cell_len(dica)
@@ -2862,8 +3045,8 @@ class Painel:
2862
3045
  # Cache do frame base: quando um diálogo está aberto e os dados não mudaram,
2863
3046
  # reaproveita o fundo esmaecido sem re-renderizar tabela/painéis Rich a cada seta/scroll.
2864
3047
  em_restart = bool(getattr(self, '_restart_overlay', None))
2865
- chave_base = (self.largura, self.altura, self.coletor.revisao, self.scroll,
2866
- TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
3048
+ chave_base = (self.largura, self.altura, self.coletor.revisao, self.atualizacoes.revisao,
3049
+ self.scroll, TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
2867
3050
  cache = getattr(self, '_cache_frame_base', None)
2868
3051
  if tem_overlay and cache and cache[0] == chave_base:
2869
3052
  frame = list(cache[1])
@@ -2884,15 +3067,19 @@ class Painel:
2884
3067
  self._overlay_width = 0
2885
3068
  self._overlay_height = 0
2886
3069
  self._overlay_clique = {}
2887
- # Quando um diálogo novo abre na TUI, anima brevemente a revelação (slide/expand)
2888
- # Em telas pequenas/estreitas (Termux/celular) ou após resize, pula o slide para
2889
- # nunca sobrepor dois quadros parciais.
3070
+ # Quando um diálogo novo abre na TUI, anima a abertura (2 frames rápidos,
3071
+ # inclusive no celular, pois cada linha agora usa \x1b[row;1H\x1b[2K limpo).
2890
3072
  modal_identidade = ('tokens-live' if (self.modal or {}).get('tipo') == 'tokens' else id(self.modal))
2891
3073
  dialogo_atual = (id(self.wizard), (self.wizard or {}).get('tipo'), (self.wizard or {}).get('passo'), modal_identidade, em_restart)
2892
3074
  if tem_overlay and dialogo_atual != getattr(self, '_dialogo_id', None):
2893
3075
  self._dialogo_id = dialogo_atual
2894
- self._dialogo_frame = 99 if (self.largura < 80 or self.altura < 24 or tui_core.is_termux()) else 0
3076
+ self._dialogo_frame = 0 if (self.altura >= 14 and not em_restart) else 99
3077
+ self._fechar_overlay_frame = 0
2895
3078
  elif not tem_overlay:
3079
+ if getattr(self, '_dialogo_id', None) is not None and getattr(self, '_ultimo_overlay_linhas', None):
3080
+ self._fechar_overlay_linhas = list(self._ultimo_overlay_linhas)
3081
+ self._fechar_overlay_frame = 1
3082
+ self._ultimo_overlay_linhas = []
2896
3083
  self._dialogo_id = None
2897
3084
  self._dialogo_frame = 99
2898
3085
  # Em telas baixas, garante que o frame do overlay nunca passe da area util
@@ -2903,11 +3090,12 @@ class Painel:
2903
3090
  if len(caixa_linhas) > limite and limite >= 4:
2904
3091
  caixa_linhas = caixa_linhas[:limite - 1] + [caixa_linhas[-1]]
2905
3092
  mapa_clique = {k: v for k, v in mapa_clique.items() if k < limite - 1}
2906
- # Animação de entrada suave (2 frames rápidos, sem travar teclado)
2907
- if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 6:
3093
+ self._ultimo_overlay_linhas = list(caixa_linhas)
3094
+ # Animação de abertura suave (2 frames rápidos, sem travar teclado)
3095
+ if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 5:
2908
3096
  passo_a = self._dialogo_frame
2909
3097
  self._dialogo_frame += 1
2910
- recorte = max(4, int(len(caixa_linhas) * (0.55 if passo_a == 0 else 0.82)))
3098
+ recorte = max(4, int(len(caixa_linhas) * (0.50 if passo_a == 0 else 0.80)))
2911
3099
  caixa_vis = caixa_linhas[:recorte - 1] + [caixa_linhas[-1]]
2912
3100
  else:
2913
3101
  caixa_vis = caixa_linhas
@@ -2938,12 +3126,27 @@ class Painel:
2938
3126
  self._registrar_menu(frame, cortado)
2939
3127
  self._registrar_wizard(frame, cortado)
2940
3128
  self._registrar_modal(frame, cortado)
3129
+ elif getattr(self, '_fechar_overlay_frame', 0) > 0 and getattr(self, '_fechar_overlay_linhas', None):
3130
+ # Transição rápida de fechamento (1 frame encolhendo a caixa antes de sumir)
3131
+ caixa_ant = self._fechar_overlay_linhas
3132
+ self._fechar_overlay_frame = 0
3133
+ self._fechar_overlay_linhas = []
3134
+ if len(caixa_ant) > 5 and limite >= 6:
3135
+ recorte = max(4, int(len(caixa_ant) * 0.48))
3136
+ caixa_vis = caixa_ant[:recorte - 1] + [caixa_ant[-1]]
3137
+ frame, _, _ = tui_core.desenhar_overlay_centrado(
3138
+ frame, caixa_vis, self.largura, limite, cor_fundo_ansi='', esmaecer_fundo=False
3139
+ )
3140
+ self._registrar_menu(frame, cortado)
3141
+ self._registrar_wizard(frame, cortado)
3142
+ self._registrar_modal(frame, cortado)
2941
3143
  else:
2942
3144
  self._registrar_menu(frame, cortado)
2943
3145
  self._registrar_wizard(frame, cortado)
2944
3146
  self._registrar_modal(frame, cortado)
2945
3147
  self.desenhar(frame)
2946
3148
  self.revisao_vista = self.coletor.revisao
3149
+ self._update_revisao_vista = self.atualizacoes.revisao
2947
3150
 
2948
3151
  # -- teclado e mouse ------------------------------------------------------
2949
3152
  def ler_tecla(self, timeout: float):
@@ -3067,11 +3270,20 @@ class Painel:
3067
3270
  return None
3068
3271
 
3069
3272
  def _precisa_animar(self) -> bool:
3070
- """Indica se ha algo vivo para animar (restart, abertura de dialogo, tarefa ou geracao em voo)."""
3273
+ """Indica se ha algo vivo para animar (abertura, fechamento, digitacao, restart, tarefa ou live)."""
3071
3274
  if getattr(self, '_restart_overlay', None):
3072
3275
  return True
3073
- if self.modo == 'tui' and (self.wizard or self.modal) and getattr(self, '_dialogo_frame', 99) < 2:
3276
+ if getattr(self, '_intro_frame', 99) < 3:
3074
3277
  return True
3278
+ if getattr(self, '_fechar_overlay_frame', 0) > 0:
3279
+ return True
3280
+ if (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.18:
3281
+ return True
3282
+ if self.modo == 'tui' and (self.wizard or self.modal):
3283
+ # Com diálogo aberto (ex.: Antigravity, Connect, Model), congela o
3284
+ # redesenho de fundo para não piscar a tela a cada 80ms enquanto há
3285
+ # requisições live rodando atrás.
3286
+ return getattr(self, '_dialogo_frame', 99) < 2 or self.tarefa_ativa
3075
3287
  if self.tarefa_ativa:
3076
3288
  return True
3077
3289
  snap = getattr(self, '_snap_visto', None) or {}
@@ -3080,6 +3292,48 @@ class Painel:
3080
3292
  return True
3081
3293
  return False
3082
3294
 
3295
+ # Imersão rápida na abertura da TUI (funciona em `krnell` e ao abrir pelo OpenCode)
3296
+ def _animar_abertura_tui(self, saida) -> None:
3297
+ if os.environ.get('KRNELL_NO_INTRO') == '1' or not sys.stdout.isatty():
3298
+ self._intro_frame = 3
3299
+ return
3300
+ larg, alt = shutil.get_terminal_size((110, 30))
3301
+ if larg < 36 or alt < 14:
3302
+ self._intro_frame = 3
3303
+ return
3304
+ centro_y = max(2, (alt - 5) // 2)
3305
+ pad_x = max(0, (larg - 30) // 2)
3306
+ ver = f'v{versao_local()}'
3307
+ pad_v = max(0, (larg - len(ver) - 9) // 2)
3308
+ saida.write('\x1b[?25l\x1b[2J\x1b[H')
3309
+ for passo in range(1, 4):
3310
+ buf = ['\x1b[?2026h']
3311
+ for i in range(passo):
3312
+ esq_l, dir_l = _LOGO_KRNELL[i]
3313
+ buf.append(
3314
+ f'\x1b[{centro_y + i};1H\x1b[2K'
3315
+ + ' ' * pad_x
3316
+ + ansi('texto') + esq_l + ansi('acento') + dir_l + RESET
3317
+ )
3318
+ sub = '◈ krnell ' + ver
3319
+ bar = ('━' * (passo * 6)) + ('─' * ((3 - passo) * 6))
3320
+ buf.append(
3321
+ f'\x1b[{centro_y + 4};1H\x1b[2K'
3322
+ + ' ' * pad_v
3323
+ + ansi('acento') + sub + RESET
3324
+ )
3325
+ pad_b = max(0, (larg - len(bar)) // 2)
3326
+ buf.append(
3327
+ f'\x1b[{centro_y + 5};1H\x1b[2K'
3328
+ + ' ' * pad_b
3329
+ + ansi('acento2') + bar + RESET
3330
+ + '\x1b[?2026l'
3331
+ )
3332
+ saida.write(''.join(buf))
3333
+ saida.flush()
3334
+ time.sleep(0.055)
3335
+ self._intro_frame = 3
3336
+
3083
3337
  def rodar_tui(self) -> None:
3084
3338
  if not self.ativar_vt():
3085
3339
  self.modo = 'repl'
@@ -3091,9 +3345,10 @@ class Painel:
3091
3345
  self.iniciar_bridge_na_abertura()
3092
3346
  self.iniciar_dashboard_na_abertura()
3093
3347
  saida = sys.stdout
3094
- saida.write('\x1b[?1049h\x1b[?25h')
3348
+ saida.write('\x1b[?1049h\x1b[?25l')
3095
3349
  saida.write('\x1b[?7l')
3096
3350
  saida.flush()
3351
+ self._animar_abertura_tui(saida)
3097
3352
  self._precisa_limpar_tela = True
3098
3353
  try:
3099
3354
  self.atualizar_tela()
@@ -3104,12 +3359,37 @@ class Painel:
3104
3359
  if tecla is None:
3105
3360
  nova_larg, nova_alt = shutil.get_terminal_size((self.largura, self.altura))
3106
3361
  mudou_tamanho = (nova_larg != self.largura or nova_alt != self.altura)
3107
- mudou_dados = self.coletor.revisao != self.revisao_vista
3362
+ mudou_dados = (
3363
+ self.coletor.revisao != self.revisao_vista
3364
+ or self.atualizacoes.revisao != self._update_revisao_vista
3365
+ )
3108
3366
  expirou_msg = bool(self.msg and time.time() > self.msg_ate)
3109
3367
  if expirou_msg:
3110
3368
  self.msg = None
3111
- intervalo_anim = 0.03 if getattr(self, '_dialogo_frame', 99) < 2 else (0.09 if animando else 0.9)
3369
+ intervalo_anim = (
3370
+ 0.035 if (
3371
+ getattr(self, '_dialogo_frame', 99) < 2
3372
+ or getattr(self, '_fechar_overlay_frame', 0) > 0
3373
+ or getattr(self, '_intro_frame', 99) < 3
3374
+ ) else (0.08 if animando else 0.9)
3375
+ )
3112
3376
  tick_anim = (agora - self._anim_ultimo) >= intervalo_anim
3377
+ # Animação de digitação sutil no placeholder da home quando ocioso
3378
+ anim_dica = False
3379
+ if not self.buf and not self.wizard and not self.modal and not self._restart_overlay:
3380
+ dica_alvo = _DICAS_HOME[self._dica_idx % len(_DICAS_HOME)]
3381
+ if self._dica_chars < len(dica_alvo):
3382
+ if (agora - self._dica_ultimo) >= 0.045:
3383
+ self._dica_chars += 2
3384
+ self._dica_ultimo = agora
3385
+ anim_dica = True
3386
+ elif (agora - self._dica_ultimo) >= 5.5:
3387
+ self._dica_idx = (self._dica_idx + 1) % len(_DICAS_HOME)
3388
+ self._dica_chars = 0
3389
+ self._dica_ultimo = agora
3390
+ anim_dica = True
3391
+ if tick_anim and getattr(self, '_intro_frame', 99) < 3:
3392
+ self._intro_frame += 1
3113
3393
  if tick_anim and (animando or (not self.wizard and not self.modal)):
3114
3394
  self._anim_tick = (self._anim_tick + 1) % 100000
3115
3395
  self._anim_ultimo = agora
@@ -3117,8 +3397,10 @@ class Painel:
3117
3397
  self._cache_frame_base = None
3118
3398
  self._dialogo_frame = 99
3119
3399
  self._precisa_limpar_tela = True
3120
- if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
3400
+ if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and animando):
3121
3401
  self.atualizar_tela()
3402
+ elif anim_dica:
3403
+ self.desenhar_linha_entrada()
3122
3404
  continue
3123
3405
  # Coalescing de scroll/setas: drena eventos repetidos pendentes no buffer
3124
3406
  # para manter a rolagem lisa sem travar o terminal.
@@ -3191,11 +3473,30 @@ class Painel:
3191
3473
  print(f'não consegui reexecutar a TUI ({exc}). Execute: krnell')
3192
3474
  return
3193
3475
  return
3476
+ if getattr(self, '_sair_em_background', False):
3477
+ self.proc = None
3478
+ self._soltar_job()
3479
+ estado = ('bridge segue rodando em background — use /exit na TUI para desligar'
3480
+ if self.bridge_online() else 'bridge parado')
3481
+ print(f'painel fechado — {estado}.')
3482
+ return
3194
3483
  tinha_bridge = self._encerrar_com_o_painel()
3484
+ # /exit desliga o bridge de verdade (mesmo que tenha sido iniciado antes em background)
3485
+ if not tinha_bridge and self.bridge_online():
3486
+ try:
3487
+ self._parar_bridge()
3488
+ tinha_bridge = True
3489
+ except Exception:
3490
+ pass
3491
+ try:
3492
+ cfg_fim = ler_config()
3493
+ prov_cfg = ((cfg_fim.get('provedores') or {}).get(cfg_fim.get('provider')) or {})
3494
+ porta_m = kimi.porta_de(prov_cfg.get('base_url') or cfg_fim.get('upstream_base_url') or '')
3495
+ kimi.parar_motor(ROOT, porta_m)
3496
+ except Exception:
3497
+ pass
3195
3498
  if tinha_bridge:
3196
- estado = 'o bridge encerrou junto com o painel (portas fechadas)'
3197
- elif self.bridge_online():
3198
- estado = 'o bridge segue no ar — foi iniciado fora deste painel'
3499
+ estado = 'bridge e motor local encerrados (portas fechadas)'
3199
3500
  else:
3200
3501
  estado = 'bridge parado'
3201
3502
  print(f'painel encerrado — {estado}.')
@@ -3283,6 +3584,7 @@ class Painel:
3283
3584
  pass # modal fecha somente com Enter/Esc
3284
3585
  else:
3285
3586
  self.buf += tecla[1]
3587
+ self._digito_pulso = time.monotonic()
3286
3588
  redesenhar = True
3287
3589
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_clique':
3288
3590
  if self.clicar_botao_update(tecla[1], tecla[2]):
@@ -3340,6 +3642,9 @@ class Painel:
3340
3642
  elif self.modal or self.wizard:
3341
3643
  self.modal = self.wizard = None
3342
3644
  else:
3645
+ # Ctrl+C fecha somente a TUI e deixa o bridge rodando em background
3646
+ # (Windows, Linux, Ubuntu e Termux). Use /exit para desligar de verdade.
3647
+ self._sair_em_background = True
3343
3648
  self.saindo = True
3344
3649
  redesenhar = True
3345
3650
  elif tecla == 'cima':
@@ -3553,6 +3858,7 @@ class Painel:
3553
3858
  self.msg_ate = time.time() + segundos
3554
3859
 
3555
3860
  def fechar(self, arg: str = ''):
3861
+ self._sair_em_background = False
3556
3862
  self.saindo = True
3557
3863
 
3558
3864
  def _linhas_ajuda_colunas(self, itens) -> list:
@@ -5824,21 +6130,28 @@ class Painel:
5824
6130
  raise ValueError('o bridge já está no ar')
5825
6131
  BRIDGE_LOG.parent.mkdir(exist_ok=True)
5826
6132
  log = open(BRIDGE_LOG, 'ab')
5827
- flags = 0x08000000 if os.name == 'nt' else 0 # CREATE_NO_WINDOW
6133
+ # Processo destacado (cross-platform: Windows DETACHED/NEW_PROCESS_GROUP,
6134
+ # Linux/Ubuntu/Termux start_new_session) para que Ctrl+C na TUI deixe o
6135
+ # bridge vivo em background e somente /exit ou /stop encerre o servidor.
6136
+ opcoes: dict = {}
6137
+ if os.name == 'nt':
6138
+ opcoes['creationflags'] = (
6139
+ getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
6140
+ | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0x00000200)
6141
+ | getattr(subprocess, 'DETACHED_PROCESS', 0x00000008)
6142
+ )
6143
+ else:
6144
+ opcoes['start_new_session'] = True
5828
6145
  self._soltar_job()
5829
6146
  try:
5830
6147
  self.proc = subprocess.Popen(
5831
6148
  [sys.executable, '-B', str(ROOT / 'bridge.py'), '--config', 'config.json'],
5832
- cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT, creationflags=flags)
6149
+ cwd=str(ROOT), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, **opcoes)
5833
6150
  finally:
5834
6151
  try:
5835
6152
  log.close()
5836
6153
  except OSError:
5837
6154
  pass
5838
- # o bridge vive junto com o painel: X no console, /sair ou queda o encerram
5839
- self._job_bridge = prender_processo_ao_painel(self.proc.pid)
5840
- if os.name == 'nt' and not self._job_bridge:
5841
- self._instalar_guarda_ctrl()
5842
6155
  for _ in range(60):
5843
6156
  time.sleep(0.2)
5844
6157
  if self._bridge_online_direto():