krnell 3.0.4 → 3.0.6

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
@@ -526,7 +526,19 @@ def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> t
526
526
  _SPIN_BRAILLE = ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏')
527
527
  _PULSO_ONLINE = ('●', '●', '●', '◉', '◉', '●')
528
528
  _ONDA_LIVE = ('▁▂▃▄', '▂▃▄▅', '▃▄▅▆', '▄▅▆▇', '▅▆▇▆', '▆▇▆▅', '▇▆▅▄', '▆▅▄▃', '▅▄▃▂', '▄▃▂▁')
529
- _GLIFO_MARCA = ('◈', '◈', '◇', '◈', '◈', '◈', '◈', '◈')
529
+ _GLIFO_MARCA = ('◈',)
530
+ # Wordmark pixel-block estilo OpenCode (duas cores: "krn" + "ell", 30 cols)
531
+ _LOGO_KRNELL = (
532
+ ('█ ▄▀ █▀▀▄ █▀▀▄ ', '█▀▀█ █ █ '),
533
+ ('█▄▀ █▄▄▀ █ █ ', '█▀▀ █ █ '),
534
+ ('█ ▀▄ █ █ █ █ ', '▀▀▀▀ ▀▀▀▀ ▀▀▀▀'),
535
+ )
536
+ _DICAS_HOME = (
537
+ '/ commands · /connect · /model',
538
+ 'Try "/model" to switch between NVIDIA & Antigravity',
539
+ 'Try "/quota" to inspect live 5h & 7d quotas',
540
+ 'Try "/connect" to add API keys or Google OAuth',
541
+ )
530
542
 
531
543
 
532
544
  def versao_local() -> str:
@@ -1133,6 +1145,7 @@ class Painel:
1133
1145
  self.proc = None
1134
1146
  self.tarefa_ativa = False
1135
1147
  self.saindo = False
1148
+ self._sair_em_background = False # Ctrl+C fecha TUI mantendo bridge vivo; /exit para tudo
1136
1149
  self.revisao_vista = -1
1137
1150
  self.scroll = 0
1138
1151
  self.ultima_acao = None
@@ -1145,6 +1158,8 @@ class Painel:
1145
1158
  self._wizard_item_linhas = {} # linha do wizard -> indice do item
1146
1159
  self._modal_ini = None # linha do frame do 1o item do modal (clique copia)
1147
1160
  self._reqs_visiveis = 10 # quantas requisicoes cabem na janela (roda do mouse)
1161
+ self._wizard_pilha: list[dict] = [] # pilha para Esc voltar 1 nível em vez de cancelar tudo
1162
+ self._esc_zona = None # colunas do botão `esc back` do rodapé (toque/clique)
1148
1163
  self._copiar_zona = None # colunas do botao copiar do rodape (clique)
1149
1164
  self._copiar_hover = False # mouse em cima do botao copiar
1150
1165
  self._status_y = None # linha (0-based) da barra de status
@@ -1160,16 +1175,27 @@ class Painel:
1160
1175
  self._term_posix = None # tui_core.TerminalPosix no Termux/Linux/macOS
1161
1176
  self._overlay_top = None
1162
1177
  self._overlay_left = None
1178
+ self._overlay_width = 0
1179
+ self._overlay_height = 0
1163
1180
  self._overlay_clique = {} # y_relativo -> indice do item no overlay centrado
1164
1181
  self._ag_auth_url = None
1182
+ self._ag_auth_state = ''
1165
1183
  self._anim_tick = 0
1166
1184
  self._anim_ultimo = 0.0
1185
+ self._intro_frame = 0 # animação de abertura do logo/tela (0..3)
1186
+ self._fechar_overlay_frame = 0 # animação rápida de fechamento (0=inativo)
1187
+ self._fechar_overlay_linhas: list[str] = []
1188
+ self._digito_pulso = 0.0 # timestamp do último caractere digitado (brilho no prompt ▸)
1189
+ self._dica_idx = 0
1190
+ self._dica_chars = 0
1191
+ self._dica_ultimo = 0.0
1167
1192
  self._dialogo_frame = 0 # animacao de abertura do dialogo
1168
1193
  self._dialogo_id = None
1169
1194
  self._reexec_solicitado = False # /restart na TUI reexecuta painel.py do zero
1170
1195
  self._reexec_comando = None # update reabre pelo entrypoint npm recém-instalado
1171
1196
  self._restart_overlay = None # estado da animacao de reinicio estilo OpenCode
1172
1197
  self.atualizacoes = atualizador.MonitorAtualizacao(versao_local())
1198
+ self._update_revisao_vista = -1
1173
1199
  self._update_zona = None # (y, x inicial, x final) do pill opcional no header
1174
1200
  self._update_hover = False
1175
1201
  self.modo = 'repl'
@@ -1270,7 +1296,7 @@ class Painel:
1270
1296
  cab.add_column(ratio=1, no_wrap=True)
1271
1297
  cab.add_column(justify='right', no_wrap=True)
1272
1298
  titulo = Text()
1273
- glifo = _GLIFO_MARCA[tick % len(_GLIFO_MARCA)] if online else '◇'
1299
+ glifo = '◈' if online else '◇'
1274
1300
  titulo.append(f'{glifo} ', style=f'bold {ACENTO}')
1275
1301
  titulo.append('krnell', style=f'bold {TEXTO}')
1276
1302
  if largura >= 34:
@@ -1287,28 +1313,53 @@ class Painel:
1287
1313
  estado.append(' ' if largura < 52 else ' ')
1288
1314
  if online:
1289
1315
  if (status.get('live') or {}).get('ativas'):
1290
- rot_on = f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} live' if largura < 42 else f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working'
1316
+ rot_on = f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} live' if largura < 54 else f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working'
1291
1317
  estado.append(rot_on, style=ACENTO2)
1292
1318
  else:
1293
- estado.append('● on' if largura < 38 else '● online', style=OK)
1319
+ estado.append('● on' if largura < 40 else '● online', style=OK)
1294
1320
  else:
1295
- estado.append('○ off' if largura < 38 else '○ offline', style=ERRO)
1321
+ estado.append('○ off' if largura < 40 else '○ offline', style=ERRO)
1296
1322
  if rotulo_update:
1297
1323
  inicio = max(0, largura - cell_len(estado.plain))
1298
1324
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
1299
1325
  cab.add_row(titulo, estado)
1300
1326
 
1327
+ # Wordmark pixel-block "krnell" centralizado estilo OpenCode (com espaço vertical)
1328
+ logo_blocos: list = []
1329
+ if largura >= 36 and altura >= 16:
1330
+ intro = getattr(self, '_intro_frame', 99)
1331
+ mostrar_linhas = 3 if intro >= 3 else max(1, intro + 1)
1332
+ pad_logo = ' ' * max(0, (largura - 30) // 2)
1333
+ for idx_l, (esq_l, dir_l) in enumerate(_LOGO_KRNELL[:mostrar_linhas]):
1334
+ tl = Text(no_wrap=True)
1335
+ tl.append(pad_logo)
1336
+ tl.append(esq_l, style=f'bold {FRACO if intro == 0 else TEXTO}')
1337
+ tl.append(dir_l, style=f'bold {ACENTO}')
1338
+ logo_blocos.append(tl)
1339
+ if disponivel:
1340
+ pill = f" ↑ update v{disponivel['version']} available · tap or /update "
1341
+ pill_vis = tui_core.truncate_vis(pill, max(16, largura - 2))
1342
+ pad_p = ' ' * max(0, (largura - cell_len(pill_vis)) // 2)
1343
+ tp = Text(no_wrap=True)
1344
+ tp.append(pad_p)
1345
+ tp.append(pill_vis, style=f'bold {ACENTO3 if self._update_hover else ACENTO} on {FUNDO}')
1346
+ logo_blocos.append(tp)
1347
+ logo_blocos.append(Text(''))
1348
+
1301
1349
  usar_overlay = self.modo == 'tui'
1302
1350
  menu_render = self._render_menu()
1303
1351
  modais_render = [] if usar_overlay else self._render_modais(largura)
1304
1352
  extra = sum(len(self._linhas(x, largura)) for x in (menu_render, modais_render) if x)
1305
- espaco_corpo = max(5, altura - 7 - extra)
1306
- info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if largura < 96 else []
1307
- if espaco_corpo < len(info_compacta) + 5:
1353
+ # Só usa layout de 2 colunas quando houver largura real confortável para ambas
1354
+ # (evita quebrar "7d 20.9%" em 2 linhas no meio do zoom do celular).
1355
+ duas_colunas = largura >= 108
1356
+ espaco_corpo = max(4, altura - 7 - len(logo_blocos) - extra)
1357
+ info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if not duas_colunas else []
1358
+ if espaco_corpo < len(info_compacta) + 4:
1308
1359
  info_compacta = info_compacta[:1]
1309
1360
  linhas_req = max(2, min(espaco_corpo - len(info_compacta), 48))
1310
- estreito = largura < 74
1311
- ultra_estreito = largura < 46
1361
+ estreito = largura < 78
1362
+ ultra_estreito = largura < 48
1312
1363
 
1313
1364
  reqs = snap.get('requests') or []
1314
1365
  visiveis = max(1, linhas_req - 1)
@@ -1330,9 +1381,9 @@ class Painel:
1330
1381
  show_header=False, pad_edge=False)
1331
1382
  if not ultra_estreito:
1332
1383
  tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1333
- tabela.add_column(width=5, no_wrap=True)
1384
+ tabela.add_column(width=6, no_wrap=True)
1334
1385
  tabela.add_column(ratio=1, no_wrap=True, overflow='ellipsis')
1335
- tabela.add_column(width=5 if ultra_estreito else 6, justify='right', no_wrap=True)
1386
+ tabela.add_column(width=6 if ultra_estreito else 7, justify='right', no_wrap=True)
1336
1387
  if not estreito:
1337
1388
  tabela.add_column(width=9, justify='right', no_wrap=True)
1338
1389
  tabela.add_column(width=14, no_wrap=True, overflow='ellipsis')
@@ -1354,8 +1405,9 @@ class Painel:
1354
1405
  obs = Text(str(evento.get('error') or ('stream' if evento.get('stream') else '')),
1355
1406
  style=ERRO if evento.get('error') else FRACO)
1356
1407
  hora = fmt_hora(evento.get('ts'))
1408
+ rotulo_ev = str(evento.get('model') or evento.get('account') or '—')
1357
1409
  linha_req(hora[:5] if estreito else hora, cel_codigo,
1358
- str(evento.get('account') or evento.get('model') or '—'),
1410
+ rotulo_ev,
1359
1411
  fmt_duracao(evento.get('ms')), fmt_tokens(evento.get('tokens')), obs)
1360
1412
  for item in em_voo:
1361
1413
  sp = _SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]
@@ -1364,8 +1416,9 @@ class Painel:
1364
1416
  style=ACENTO2 if item.get('tok_s') else AVISO)
1365
1417
  saida = (('~' if not item.get('exato') else '') + fmt_tokens_grande(item['tokens_out'])
1366
1418
  if item.get('tokens_out') else '—')
1419
+ rotulo_live = str(item.get('modelo') or item.get('model') or item.get('conta') or item.get('rota') or '—')
1367
1420
  linha_req(Text('now', style=ACENTO2), Text(f'{sp} live', style=ACENTO2),
1368
- str(item.get('conta') or item.get('rota') or '—'),
1421
+ rotulo_live,
1369
1422
  fmt_duracao((item.get('segundos') or 0) * 1000), saida, obs_live)
1370
1423
  vazio_row = ('', '', '', '', '', '')[:len(tabela.columns)]
1371
1424
  for _ in range(max(0, visiveis - len(fatia) - len(em_voo))):
@@ -1383,10 +1436,17 @@ class Painel:
1383
1436
  atividade.add_row(tabela)
1384
1437
 
1385
1438
  renderaveis = [cab, Text('')]
1386
- if largura >= 96:
1439
+ renderaveis.extend(logo_blocos)
1440
+ if disponivel and logo_blocos:
1441
+ # Guarda zona clicável do banner central de update também
1442
+ y_banner = 2 + len(_LOGO_KRNELL)
1443
+ self._update_banner_zona = (y_banner, 0, max(0, largura - 1))
1444
+ else:
1445
+ self._update_banner_zona = None
1446
+ if duas_colunas:
1387
1447
  grade = Table.grid(expand=True, padding=(0, 2, 0, 0))
1388
1448
  grade.add_column(ratio=3)
1389
- grade.add_column(ratio=1)
1449
+ grade.add_column(min_width=30, ratio=1)
1390
1450
  grade.add_row(atividade, self._lado_minimo(snap, online, status))
1391
1451
  renderaveis.append(grade)
1392
1452
  else:
@@ -1411,19 +1471,19 @@ class Painel:
1411
1471
 
1412
1472
  def _lado_minimo(self, snap: dict, online: bool, status: dict) -> Text:
1413
1473
  """Apenas dados vivos; diagnóstico e pool detalhado ficam em /status."""
1414
- lado = Text()
1474
+ lado = Text(no_wrap=True, overflow='ellipsis')
1415
1475
  ag_status = snap.get('ag_status') if isinstance(snap.get('ag_status'), dict) else {}
1416
1476
  resumo = _resumo_cota_antigravity(ag_status)
1417
1477
  if resumo:
1418
1478
  lado.append('Antigravity\n', style=FRACO)
1419
1479
  for item in resumo[:2]:
1420
- lado.append(f"{item['nome']:<8}", style=TEXTO)
1480
+ lado.append(f"{item['nome']:<7}", style=TEXTO)
1421
1481
  t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1422
1482
  ts, cs = _fmt_bucket_curto(item.get('bsem'), '7d', com_reset=False)
1423
1483
  if t5:
1424
1484
  lado.append(t5, style=c5)
1425
1485
  if t5 and ts:
1426
- lado.append(' ', style=BORDA)
1486
+ lado.append(' ', style=BORDA)
1427
1487
  if ts:
1428
1488
  lado.append(ts, style=cs)
1429
1489
  lado.append('\n')
@@ -1445,9 +1505,14 @@ class Painel:
1445
1505
 
1446
1506
  def _info_compacta(self, snap, online, status, cfg, provedor) -> list:
1447
1507
  """Duas linhas no máximo em telas estreitas; o resto mora em /status e /quota."""
1448
- modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(8, self.largura - len(provedor) - 14))
1508
+ # Nunca duplica `model_enviado` quando estiver no provedor `kimi` legado com modelo Antigravity
1509
+ if cfg.get('provider') == 'kimi' and modelo_ativo(cfg) in kimi.MODELOS_ANTIGRAVITY:
1510
+ provedor_exib = 'antigravity'
1511
+ else:
1512
+ provedor_exib = provedor
1513
+ modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(8, self.largura - len(provedor_exib) - 14))
1449
1514
  primeira = Text(no_wrap=True, overflow='ellipsis')
1450
- primeira.append(provedor, style=f'bold {ACENTO}')
1515
+ primeira.append(provedor_exib, style=f'bold {ACENTO}')
1451
1516
  primeira.append(f' {modelo}', style=TEXTO)
1452
1517
  var = variante_ativa(cfg, provedor)
1453
1518
  if cell_len(primeira.plain) + len(var) + 5 <= self.largura:
@@ -1495,7 +1560,9 @@ class Painel:
1495
1560
  if self.modal or self.wizard:
1496
1561
  direita = [(' esc back ', 'fraco', None, 'ess'), botao]
1497
1562
  else:
1498
- direita = [(' ctrl+p commands · ctrl+l connect ', 'fraco', None, 'extra'), botao]
1563
+ direita = [(' commands ', 'fraco', None, 'extra'),
1564
+ (' connect ', 'acento2', None, 'nor'),
1565
+ botao]
1499
1566
  return esquerda, direita
1500
1567
 
1501
1568
  def _barra_status(self) -> str:
@@ -1524,11 +1591,31 @@ class Painel:
1524
1591
  acumulado += w
1525
1592
  espaco = max(1, self.largura - acumulado - larg_dir)
1526
1593
  self._copiar_zona = None
1594
+ self._esc_zona = None
1595
+ self._status_acoes: list[tuple[int, int, str]] = [] # (x_ini, x_fim, acao)
1596
+ # Registra áreas tocáveis na esquerda da barra (provedor/modelo -> /model, esforço -> /effort)
1597
+ if not self.tarefa_ativa and not (self.msg and time.time() <= self.msg_ate):
1598
+ x_cur = 0
1599
+ for idx_seg, (txt_seg, _) in enumerate(cortados):
1600
+ w_seg = cell_len(txt_seg)
1601
+ if w_seg > 0:
1602
+ acao_esq = 'effort' if idx_seg == 2 else 'model'
1603
+ self._status_acoes.append((x_cur, x_cur + w_seg - 1, acao_esq))
1604
+ x_cur += w_seg
1527
1605
  if dr:
1528
- larg_btn = cell_len(dr[-1][0])
1529
- inicio = self.largura - larg_btn
1530
- if inicio >= 1:
1531
- self._copiar_zona = (inicio, self.largura - 1)
1606
+ pos_fim = self.largura
1607
+ for seg in reversed(dr):
1608
+ larg_seg = cell_len(seg[0])
1609
+ inicio = pos_fim - larg_seg
1610
+ if 'copy' in seg[0] and inicio >= 1:
1611
+ self._copiar_zona = (inicio, pos_fim - 1)
1612
+ elif 'esc' in seg[0] and inicio >= 1:
1613
+ self._esc_zona = (inicio, pos_fim - 1)
1614
+ elif 'commands' in seg[0] and inicio >= 1:
1615
+ self._status_acoes.append((inicio, pos_fim - 1, 'palette'))
1616
+ elif 'connect' in seg[0] and inicio >= 1:
1617
+ self._status_acoes.append((inicio, pos_fim - 1, 'connect'))
1618
+ pos_fim = inicio
1532
1619
  return pintar_segmentos(cortados) + ' ' * espaco + pintar_segmentos(dr)
1533
1620
 
1534
1621
  def _texto_status_rich(self, snap=None) -> Text:
@@ -1598,7 +1685,7 @@ class Painel:
1598
1685
 
1599
1686
  def _limite_menu(self) -> int:
1600
1687
  """Quantos itens do menu cabem sem apertar o resto do painel."""
1601
- return max(3, min(10, self.altura - 16))
1688
+ return max(3, min(10, self.altura - 10))
1602
1689
 
1603
1690
  def _sel_menu(self) -> int:
1604
1691
  """Indice do item destacado, ja preso a lista atual de candidatos."""
@@ -1654,7 +1741,7 @@ class Painel:
1654
1741
  fundo elevado e barra de destaque no item escolhido."""
1655
1742
  if not self._menu_aberto():
1656
1743
  return []
1657
- interno = max(8, self.largura - 4) # o vao entre os trilhos ┃
1744
+ interno = max(14, self.largura - 4) # o vao entre os trilhos ┃
1658
1745
 
1659
1746
  def com_trilhos(miolo: Text) -> Text:
1660
1747
  t = Text()
@@ -1665,25 +1752,30 @@ class Painel:
1665
1752
 
1666
1753
  candidatos = self._candidatos_menu()
1667
1754
  if not candidatos:
1668
- return [com_trilhos(Text(' ' + 'nenhum comando corresponde'.ljust(interno - 1),
1669
- style=f'{FRACO} on {FUNDO}'))]
1755
+ msg_vazio = tui_core.pad_vis(' nenhum comando corresponde', interno)
1756
+ return [com_trilhos(Text(msg_vazio, style=f'{FRACO} on {FUNDO}'))]
1670
1757
  inicio, visiveis = self._janela_menu()
1671
1758
  destaque = self._sel_menu() - inicio
1672
- coluna = min(max(len(comando) for comando, _ in MENU_COMANDOS) + 2, interno - 3)
1759
+ coluna = min(max(len(comando) for comando, _ in MENU_COMANDOS) + 2, max(8, interno - 4))
1673
1760
  linhas = []
1674
1761
  for posicao, (comando, descricao) in enumerate(visiveis):
1675
- descricao = descricao[:max(0, interno - 2 - coluna)]
1676
- nome = f'{comando:<{coluna}}'
1677
- miolo = f' {nome}{descricao}'
1762
+ max_desc = max(0, interno - 2 - coluna)
1763
+ desc_vis = tui_core.truncate_vis(descricao, max_desc) if max_desc >= 4 else ''
1764
+ nome = tui_core.pad_vis(comando, coluna)
1765
+ miolo = f' {nome}{desc_vis}'
1766
+ miolo_fixo = tui_core.pad_vis(miolo, interno)
1678
1767
  t = Text()
1679
1768
  if posicao == destaque:
1680
1769
  # o item que o Enter/Tab executa ou o clique escolhe
1681
- t.append(miolo.ljust(interno), style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1770
+ t.append(miolo_fixo, style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1682
1771
  else:
1683
1772
  t.append(' ', style=f'on {FUNDO}')
1684
1773
  t.append(nome, style=f'{TEXTO} on {FUNDO}')
1685
- t.append(descricao, style=f'{FRACO} on {FUNDO}')
1686
- t.append(' ' * (interno - len(miolo)), style=f'on {FUNDO}')
1774
+ if desc_vis:
1775
+ t.append(desc_vis, style=f'{FRACO} on {FUNDO}')
1776
+ falta = max(0, interno - 1 - cell_len(nome) - cell_len(desc_vis))
1777
+ if falta:
1778
+ t.append(' ' * falta, style=f'on {FUNDO}')
1687
1779
  linhas.append(com_trilhos(t))
1688
1780
  acima = inicio
1689
1781
  abaixo = len(candidatos) - (inicio + len(visiveis))
@@ -1693,10 +1785,8 @@ class Painel:
1693
1785
  pedacos.append(f'+{acima} acima')
1694
1786
  if abaixo:
1695
1787
  pedacos.append(f'+{abaixo} abaixo')
1696
- texto = f"… {' · '.join(pedacos)} — ↑↓ e roda rolam · digite para filtrar"
1697
- texto = texto[:interno - 2]
1698
- linhas.append(com_trilhos(Text(' ' + texto.ljust(interno - 1),
1699
- style=f'{FRACO} on {FUNDO}')))
1788
+ texto = tui_core.pad_vis(f" … {' · '.join(pedacos)}", interno)
1789
+ linhas.append(com_trilhos(Text(texto, style=f'{FRACO} on {FUNDO}')))
1700
1790
  return linhas
1701
1791
 
1702
1792
  def _registrar_menu(self, frame: list, cortado: bool = False) -> None:
@@ -1723,14 +1813,23 @@ class Painel:
1723
1813
  return None
1724
1814
 
1725
1815
  def clicar_menu(self, y: int) -> bool:
1726
- """Clique no menu: roda o comando daquela linha."""
1727
- indice = self.indice_menu_no_clique(y)
1728
- if indice is None:
1816
+ """Clique/toque no menu '/': roda o comando ou rola se tocou na linha de paginação."""
1817
+ candidatos = self._candidatos_menu()
1818
+ if not candidatos or self._menu_ini is None:
1729
1819
  return False
1730
- self.buf = self._candidatos_menu()[indice][0]
1731
- self.menu_sel = indice
1732
- self.ao_enter()
1733
- return True
1820
+ posicao = y - self._menu_ini
1821
+ inicio, visiveis = self._janela_menu()
1822
+ if 0 <= posicao < len(visiveis):
1823
+ indice = inicio + posicao
1824
+ self.buf = candidatos[indice][0]
1825
+ self.menu_sel = indice
1826
+ self.ao_enter()
1827
+ return True
1828
+ # Linha de paginação ("… +2 abaixo") logo abaixo dos itens visíveis: tocar nela rola!
1829
+ if posicao == len(visiveis) and len(candidatos) > len(visiveis):
1830
+ abaixo = len(candidatos) - (inicio + len(visiveis))
1831
+ return self.roda_mouse(1 if abaixo > 0 else -1)
1832
+ return False
1734
1833
 
1735
1834
  def roda_mouse(self, sentido: int) -> bool:
1736
1835
  """Roda: rola a janela do menu e a selecao se reajusta (como no OpenCode);
@@ -1745,24 +1844,43 @@ class Painel:
1745
1844
  if candidatos:
1746
1845
  limite = self._limite_menu()
1747
1846
  maximo = max(0, len(candidatos) - limite)
1748
- self.menu_topo = max(0, min(maximo, self.menu_topo + sentido * 3))
1749
- primeiro = self.menu_topo
1750
- ultimo = min(len(candidatos) - 1, primeiro + limite - 1)
1751
- self.menu_sel = max(primeiro, min(ultimo, self._sel_menu()))
1847
+ passo = 1 if tui_core.is_termux() else 3
1848
+ delta = sentido * passo
1849
+ if maximo > 0:
1850
+ novo_topo = max(0, min(maximo, self.menu_topo + delta))
1851
+ if novo_topo != self.menu_topo:
1852
+ self.menu_topo = novo_topo
1853
+ primeiro = self.menu_topo
1854
+ ultimo = min(len(candidatos) - 1, primeiro + limite - 1)
1855
+ self.menu_sel = max(primeiro, min(ultimo, self._sel_menu() + delta))
1856
+ else:
1857
+ self.menu_sel = max(0, min(len(candidatos) - 1, self._sel_menu() + delta))
1858
+ else:
1859
+ self.menu_sel = max(0, min(len(candidatos) - 1, self._sel_menu() + delta))
1752
1860
  return True
1753
1861
  if self.wizard and self._wizard_lista():
1754
1862
  itens = self._itens_wizard_filtrados()
1755
- limite = self._limite_wizard()
1756
- maximo = max(0, len(itens) - limite)
1757
- topo = max(0, min(maximo, self.wizard.get('topo', 0) + sentido * 3))
1758
- self.wizard['topo'] = topo
1759
- # o destaque acompanha a janela: nunca fica escondido nem "pula" sozinho
1760
- self.wizard['sel'] = max(topo, min(topo + limite - 1, self._sel_wizard()))
1863
+ if itens:
1864
+ limite = self._limite_wizard()
1865
+ maximo = max(0, len(itens) - limite)
1866
+ passo = 1 if tui_core.is_termux() else 3
1867
+ delta = sentido * passo
1868
+ topo_atual = self.wizard.get('topo', 0)
1869
+ if maximo > 0:
1870
+ novo_topo = max(0, min(maximo, topo_atual + delta))
1871
+ self.wizard['topo'] = novo_topo
1872
+ if novo_topo != topo_atual:
1873
+ self.wizard['sel'] = max(novo_topo, min(novo_topo + limite - 1, self._sel_wizard() + delta))
1874
+ else:
1875
+ self.wizard['sel'] = max(0, min(len(itens) - 1, self._sel_wizard() + delta))
1876
+ else:
1877
+ self.wizard['sel'] = max(0, min(len(itens) - 1, self._sel_wizard() + delta))
1761
1878
  return True
1762
1879
  snap = self.coletor.ler()
1763
1880
  reqs = snap.get('requests') or []
1764
1881
  visiveis = max(1, getattr(self, '_reqs_visiveis', 10))
1765
- self.scroll = max(0, min(self.scroll + sentido * 3, max(0, len(reqs) - visiveis)))
1882
+ passo = 1 if tui_core.is_termux() else 3
1883
+ self.scroll = max(0, min(self.scroll + sentido * passo, max(0, len(reqs) - visiveis)))
1766
1884
  return True
1767
1885
 
1768
1886
  def completar_menu(self) -> bool:
@@ -1823,18 +1941,18 @@ class Painel:
1823
1941
  n_un = self._tamanho_pool(cfg, 'unorouter')
1824
1942
  n_th = self._tamanho_pool(cfg, 'tokenharbor')
1825
1943
  itens = [
1826
- ('Antigravity', 'ag_hub', f'{len(ag_contas)}c' if ag_contas else 'OAuth'),
1827
- ('NVIDIA', 'nv_ativar', 'Free'),
1944
+ ('NVIDIA Playground', 'nv_ativar', 'Free · sem conta'),
1945
+ ('OpenCode', 'oc_ativar', 'Free · sem conta'),
1946
+ ('Antigravity', 'ag_hub', f'{len(ag_contas)}c · OAuth' if ag_contas else 'Google OAuth'),
1828
1947
  ('WorkBuddy', 'wb_hub', f'{n_wb}c' if n_wb else 'Login'),
1829
- ('OpenCode', 'oc_ativar', 'Free'),
1830
1948
  ('ChatGPT / Copilot / xAI', 'oauth_hub', 'OAuth'),
1831
- ('UnoRouter', 'key:unorouter', f'{n_un}k' if n_un else 'API'),
1832
- ('TokenHarbor', 'key:tokenharbor', f'{n_th}k' if n_th else 'API'),
1949
+ ('UnoRouter', 'key:unorouter', f'{n_un}k' if n_un else 'API key'),
1950
+ ('TokenHarbor', 'key:tokenharbor', f'{n_th}k' if n_th else 'API key'),
1833
1951
  ]
1834
1952
  for preset in provedores_catalogo.PROVEDORES_API_PRESETS:
1835
1953
  slug = preset['slug']
1836
1954
  n_c = self._tamanho_pool(cfg, slug)
1837
- det = f'{n_c}k' if n_c else ('Local' if slug == 'ollama' else '')
1955
+ det = f'{n_c}k' if n_c else ('Local' if slug == 'ollama' else 'API key')
1838
1956
  itens.append((preset['nome'], f'preset:{slug}', det))
1839
1957
  slugs_padrao = {'workbuddy', 'kimi', 'nvidia', 'antigravity'} | set(provedores_catalogo.PRESET_POR_SLUG)
1840
1958
  for nome_p in sorted((cfg.get('provedores') or {}).keys()):
@@ -1842,14 +1960,14 @@ class Painel:
1842
1960
  continue
1843
1961
  n_c = self._tamanho_pool(cfg, nome_p)
1844
1962
  itens.append((nome_p, f'prov:{nome_p}', f'{n_c}k' if n_c else ''))
1845
- itens.append(('Sync OpenCode', 'sync_opencode', ''))
1846
- itens.append(('+ Custom provider', 'custom_add', ''))
1963
+ itens.append(('Sync OpenCode', 'sync_opencode', 'models + plugin'))
1964
+ itens.append(('+ Custom provider', 'custom_add', 'base URL + key'))
1847
1965
  mapa_atual = {
1848
- 'antigravity': 'ag_hub',
1849
1966
  'nvidia': 'nv_ativar',
1850
1967
  'kimi': 'nv_ativar',
1851
- 'workbuddy': 'wb_hub',
1968
+ 'antigravity': 'ag_hub',
1852
1969
  'opencode': 'oc_ativar',
1970
+ 'workbuddy': 'wb_hub',
1853
1971
  'unorouter': 'key:unorouter',
1854
1972
  'tokenharbor': 'key:tokenharbor',
1855
1973
  }
@@ -1920,6 +2038,23 @@ class Painel:
1920
2038
  return itens, 0
1921
2039
  if tipo == 'model':
1922
2040
  dados = w.get('dados', {})
2041
+ entradas = dados.get('entradas') or []
2042
+ atual = modelo_ativo(cfg)
2043
+ prov_atual = str(cfg.get('provider') or '')
2044
+ if prov_atual == 'kimi':
2045
+ prov_atual = 'nvidia'
2046
+ if entradas:
2047
+ itens = []
2048
+ indice = None
2049
+ for i, ent in enumerate(entradas):
2050
+ chave = f"pm:{ent['provedor']}:{ent['id']}"
2051
+ itens.append((ent['rotulo'], chave, ent.get('detalhe') or ''))
2052
+ if indice is None and ent['id'] == atual and ent['provedor'] == prov_atual:
2053
+ indice = i
2054
+ if indice is None:
2055
+ indice = next((i for i, ent in enumerate(entradas) if ent['id'] == atual), 0)
2056
+ itens.append(('informar outro ID…', 'custom_id', '/model ID'))
2057
+ return itens, indice
1923
2058
  modelos = dados.get('modelos') or []
1924
2059
  info = dados.get('info') or {}
1925
2060
  total_contas = len(workbuddy.ler_contas(ROOT)) or 0
@@ -1943,7 +2078,6 @@ class Painel:
1943
2078
  partes.append(marca + (f' (~{horas:.0f}h)' if horas else ''))
1944
2079
  itens.append((modelo, str(i), ' · '.join(partes)))
1945
2080
  itens.append(('informar outro ID…', str(len(modelos) + 1), '/model ID'))
1946
- atual = modelo_ativo(cfg)
1947
2081
  indice = indice_modelo_ativo(modelos, atual)
1948
2082
  return itens, indice
1949
2083
  if tipo == 'esforco':
@@ -2064,7 +2198,9 @@ class Painel:
2064
2198
  Usa o mapa gravado no desenho (_wizard_item_linhas): assim cabecalho,
2065
2199
  descricao e rodape nao deslocam o clique nem o hover.
2066
2200
  """
2067
- if not (self.wizard and self._wizard_lista()) or self._wizard_ini is None:
2201
+ if not self.wizard or self._wizard_ini is None:
2202
+ return None
2203
+ if not (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback'):
2068
2204
  return None
2069
2205
  return getattr(self, '_wizard_item_linhas', {}).get(y - self._wizard_ini)
2070
2206
 
@@ -2090,11 +2226,31 @@ class Painel:
2090
2226
  return topo, itens[topo:topo + limite]
2091
2227
 
2092
2228
  def clicar_wizard(self, y: int) -> bool:
2093
- """Clique num item da lista do wizard: destaca e confirma (mouseUp)."""
2229
+ """Clique/toque num item ou botão do wizard."""
2094
2230
  indice = self.indice_wizard_no_clique(y)
2095
2231
  if indice is None:
2096
2232
  return False
2233
+ if self.wizard and self.wizard.get('tipo') == 'ag_callback':
2234
+ url = str((self.wizard.get('dados') or {}).get('url') or self._ag_auth_url or '')
2235
+ if not url:
2236
+ return False
2237
+ if indice == 0:
2238
+ if copiar_area_transferencia(url):
2239
+ self.avisar('link OAuth copiado — abra no navegador', 'ok', 6)
2240
+ else:
2241
+ self.avisar(f'copie manualmente: {url}', 'aviso', 10)
2242
+ return True
2243
+ if indice == 1:
2244
+ if tui_core.abrir_url_sistema(url):
2245
+ self.avisar('abrindo link OAuth no navegador…', 'ok', 6)
2246
+ else:
2247
+ copiar_area_transferencia(url)
2248
+ self.avisar('navegador não abriu — link copiado para colar no browser', 'aviso', 8)
2249
+ return True
2250
+ return False
2097
2251
  lista = self._itens_wizard_filtrados()
2252
+ if not (0 <= indice < len(lista)):
2253
+ return False
2098
2254
  self.wizard['sel'] = indice
2099
2255
  self.buf = ''
2100
2256
  self.passo_wizard(lista[indice][1])
@@ -2124,8 +2280,14 @@ class Painel:
2124
2280
  idx_sel = self._overlay_clique.get(y - self._modal_ini)
2125
2281
  if idx_sel is None:
2126
2282
  return None
2283
+ acoes = (self.modal or {}).get('acoes') or []
2127
2284
  copias = (self.modal or {}).get('copias') or []
2128
- validos = [i for i, c in enumerate(copias) if c]
2285
+ linhas = (self.modal or {}).get('linhas') or []
2286
+ validos = [
2287
+ i for i in range(len(linhas))
2288
+ if (i < len(acoes) and isinstance(acoes[i], dict))
2289
+ or (i < len(copias) and copias[i])
2290
+ ]
2129
2291
  return validos[idx_sel] if 0 <= idx_sel < len(validos) else None
2130
2292
  posicao = y - self._modal_ini
2131
2293
  linhas = (self.modal or {}).get('linhas') or []
@@ -2134,10 +2296,17 @@ class Painel:
2134
2296
  return None
2135
2297
 
2136
2298
  def clicar_modal(self, y: int) -> bool:
2137
- """Clique num endereço do modal: copia para a área de transferência e avisa."""
2299
+ """Clique/toque num botão ou link do modal: executa ação ou copia URL."""
2138
2300
  indice = self.indice_modal_no_clique(y)
2139
2301
  if indice is None:
2140
2302
  return False
2303
+ acoes = (self.modal or {}).get('acoes') or []
2304
+ if indice < len(acoes) and isinstance(acoes[indice], dict):
2305
+ ac = acoes[indice]
2306
+ fn = ac.get('fn')
2307
+ if callable(fn):
2308
+ fn()
2309
+ return True
2141
2310
  copias = (self.modal or {}).get('copias') or []
2142
2311
  alvo = copias[indice] if indice < len(copias) else None
2143
2312
  if not alvo:
@@ -2163,6 +2332,139 @@ class Painel:
2163
2332
  return f'http://{nome}.local{sufixo}/v1'
2164
2333
  return f'http://127.0.0.1{sufixo}/v1'
2165
2334
 
2335
+ def _pilha(self) -> list:
2336
+ pilha = getattr(self, '_wizard_pilha', None)
2337
+ if pilha is None:
2338
+ pilha = []
2339
+ self._wizard_pilha = pilha
2340
+ return pilha
2341
+
2342
+ def _empilhar_wizard(self, novo: dict) -> None:
2343
+ """Abre um sub-passo do wizard guardando o anterior para Esc voltar 1 nível."""
2344
+ if self.wizard is not None:
2345
+ self._pilha().append(copy.deepcopy(self.wizard))
2346
+ self.wizard = novo
2347
+ self.buf = ''
2348
+
2349
+ def _voltar_wizard(self) -> bool:
2350
+ """Volta um passo na pilha de dialogs; retorna True se voltou, False se fechou."""
2351
+ self.buf = ''
2352
+ pilha = self._pilha()
2353
+ if pilha:
2354
+ self.wizard = pilha.pop()
2355
+ return True
2356
+ if self.wizard:
2357
+ tipo = self.wizard.get('tipo')
2358
+ passo = self.wizard.get('passo')
2359
+ if tipo == 'add' and passo == 'segredo':
2360
+ self.wizard['passo'] = 'base'
2361
+ return True
2362
+ if tipo == 'add' and passo == 'base':
2363
+ self.wizard['passo'] = 'nome'
2364
+ return True
2365
+ if tipo in ('ag_hub', 'wb_hub', 'oauth_hub'):
2366
+ self.abrir_hub_connect()
2367
+ return True
2368
+ if tipo == 'ag_callback':
2369
+ self.abrir_hub_antigravity()
2370
+ return True
2371
+ self.wizard = None
2372
+ return False
2373
+
2374
+ def ponto_no_botao_esc(self, x: int, y: int) -> bool:
2375
+ """Toque/clique no botão `esc back` do rodapé ou no `esc` do topo do dialog."""
2376
+ if not (self.modal or self.wizard):
2377
+ return False
2378
+ zona = getattr(self, '_esc_zona', None)
2379
+ if zona and y == self._status_y and zona[0] <= x <= zona[1]:
2380
+ return True
2381
+ top = getattr(self, '_overlay_top', None)
2382
+ left = getattr(self, '_overlay_left', None)
2383
+ w_ov = getattr(self, '_overlay_width', 0)
2384
+ if top is not None and left is not None and w_ov >= 12:
2385
+ if y == top + 1 and (left + w_ov - 8) <= x <= (left + w_ov - 1):
2386
+ return True
2387
+ return False
2388
+
2389
+ def clicar_fora_overlay(self, x: int, y: int) -> bool:
2390
+ """Toque fora da caixa do dialog volta um nível / fecha (conforto no celular)."""
2391
+ if not (self.modal or self.wizard):
2392
+ return False
2393
+ top = getattr(self, '_overlay_top', None)
2394
+ left = getattr(self, '_overlay_left', None)
2395
+ h_ov = getattr(self, '_overlay_height', 0)
2396
+ w_ov = getattr(self, '_overlay_width', 0)
2397
+ if top is None or left is None or not h_ov or not w_ov:
2398
+ return False
2399
+ # Não interfere na linha de entrada nem na barra de status
2400
+ if y >= max(1, self.altura - 4):
2401
+ return False
2402
+ dentro = (top <= y < top + h_ov) and (left <= x < left + w_ov)
2403
+ if not dentro:
2404
+ if self.modal:
2405
+ self.modal = None
2406
+ else:
2407
+ self._voltar_wizard()
2408
+ return True
2409
+ return False
2410
+
2411
+ def clicar_barra_home(self, x: int, y: int) -> bool:
2412
+ """Navegação por toque na home (sem setas nem Enter):
2413
+ - tocar na linha de status (modelo -> /model, esforço -> /effort, connect -> /connect, commands -> paleta)
2414
+ - tocar na linha compacta de cota (Antigravity) -> abre /quota
2415
+ - tocar na caixa de entrada vazia -> abre o menu `/` de comandos
2416
+ """
2417
+ if self.modal or self.wizard:
2418
+ return False
2419
+ if y == self._status_y:
2420
+ for ini, fim, acao in getattr(self, '_status_acoes', []):
2421
+ if ini <= x <= fim:
2422
+ if acao == 'model':
2423
+ self.abrir_wizard_modelo()
2424
+ elif acao == 'effort':
2425
+ self.abrir_wizard_variante()
2426
+ elif acao == 'connect':
2427
+ self.abrir_hub_connect()
2428
+ elif acao == 'palette':
2429
+ self.abrir_paleta()
2430
+ return True
2431
+ return False
2432
+ # Tocar na caixa de entrada vazia abre/fecha o menu de comandos "/"
2433
+ linha_caixa = (self._status_y - 2) if self._status_y is not None else -1
2434
+ if y == linha_caixa and not self.buf:
2435
+ self.buf = '/'
2436
+ self.menu_off = False
2437
+ self.menu_sel = 0
2438
+ return True
2439
+ # Tocar na linha de cotas da home (logo abaixo do cabeçalho/logo) abre /quota
2440
+ if not self._menu_aberto():
2441
+ y_cota = 3 + (len(_LOGO_KRNELL) + 1 + (1 if self.atualizacoes.disponivel else 0)
2442
+ if (self.largura >= 36 and self.altura >= 16) else 0)
2443
+ if self.largura < 108 and y == y_cota:
2444
+ self.mostrar_tokens()
2445
+ return True
2446
+ if self.largura >= 108 and y >= 2 and x >= int(self.largura * 0.72):
2447
+ self.mostrar_tokens()
2448
+ return True
2449
+ return False
2450
+
2451
+ def clicar_scroll_overlay(self, x: int, y: int) -> bool:
2452
+ """Toque na linha de paginação do diálogo rola a lista pra baixo (ou pra cima na esquerda)."""
2453
+ if not (self.wizard and self._wizard_lista()):
2454
+ return False
2455
+ top = getattr(self, '_overlay_top', None)
2456
+ left = getattr(self, '_overlay_left', None)
2457
+ h_ov = getattr(self, '_overlay_height', 0)
2458
+ w_ov = getattr(self, '_overlay_width', 0)
2459
+ if top is None or left is None or h_ov < 6 or w_ov < 16:
2460
+ return False
2461
+ # Linha de paginação fica logo acima do rodapé (h_ov - 4) ou no rodapé (h_ov - 2)
2462
+ y_rel = y - top
2463
+ if y_rel in (h_ov - 4, h_ov - 3, h_ov - 2) and left <= x < left + w_ov:
2464
+ sentido = -1 if x < (left + w_ov // 2) else 1
2465
+ return self.roda_mouse(sentido)
2466
+ return False
2467
+
2166
2468
  def ponto_no_botao_copiar(self, x: int, y: int) -> bool:
2167
2469
  """O ponto (x, y) do terminal está sobre o botão copiar do rodapé?"""
2168
2470
  zona = self._copiar_zona
@@ -2182,11 +2484,19 @@ class Painel:
2182
2484
  return True
2183
2485
 
2184
2486
  def ponto_no_botao_update(self, x: int, y: int) -> bool:
2185
- zona = self._update_zona
2186
- if not zona or self.modal or self.wizard or self._restart_overlay:
2487
+ if self.modal or self.wizard or self._restart_overlay:
2187
2488
  return False
2188
- linha, inicio, fim = zona
2189
- return y == linha and inicio <= x <= fim
2489
+ zona = self._update_zona
2490
+ if zona:
2491
+ linha, inicio, fim = zona
2492
+ if y == linha and inicio <= x <= fim:
2493
+ return True
2494
+ banner = getattr(self, '_update_banner_zona', None)
2495
+ if banner:
2496
+ linha_b, ini_b, fim_b = banner
2497
+ if y == linha_b and ini_b <= x <= fim_b:
2498
+ return True
2499
+ return False
2190
2500
 
2191
2501
  def clicar_botao_update(self, x: int, y: int) -> bool:
2192
2502
  if not self.ponto_no_botao_update(x, y):
@@ -2312,8 +2622,14 @@ class Painel:
2312
2622
  buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2313
2623
  self._status_y = base + 3
2314
2624
  buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2315
- coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
2316
- buf.append(f'\x1b[{base + 2};{coluna}H\x1b[?2026l')
2625
+ # Oculta o cursor nativo do terminal em listas/modais e quando a caixa está
2626
+ # vazia (evita o ponto/bloco branco piscando sozinho no Termux/celular).
2627
+ mostrar_cursor = bool(self.buf) or (self.wizard and not self._wizard_lista())
2628
+ if self.modal or not mostrar_cursor:
2629
+ buf.append('\x1b[?25l\x1b[?2026l')
2630
+ else:
2631
+ coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
2632
+ buf.append(f'\x1b[?25h\x1b[{base + 2};{coluna}H\x1b[?2026l')
2317
2633
  saida.write(''.join(buf))
2318
2634
  saida.flush()
2319
2635
 
@@ -2366,23 +2682,37 @@ class Painel:
2366
2682
 
2367
2683
  if self.modal:
2368
2684
  titulo = str(self.modal.get('titulo') or 'Detalhes')
2369
- dica = str(self.modal.get('dica') or 'Enter ou Esc fecha')
2685
+ dica = str(self.modal.get('dica') or 'Esc voltar')
2370
2686
  linhas_mod = self.modal.get('linhas') or []
2371
2687
  copias = self.modal.get('copias') or []
2688
+ acoes = self.modal.get('acoes') or []
2372
2689
  itens = []
2373
2690
  for idx, l in enumerate(linhas_mod):
2374
- txt = l.plain if isinstance(l, Text) else str(l)
2375
- if idx < len(copias) and copias[idx]:
2376
- itens.append({'tipo': 'item', 'rotulo': txt, 'detalhe': 'clique p/ copiar',
2377
- 'badge': '↳', 'badge_cor': ACENTO2, 'chave': str(idx)})
2691
+ if idx < len(acoes) and isinstance(acoes[idx], dict):
2692
+ ac = acoes[idx]
2693
+ itens.append({
2694
+ 'tipo': 'item',
2695
+ 'rotulo': str(ac.get('rotulo') or (l.plain if isinstance(l, Text) else str(l))),
2696
+ 'detalhe': str(ac.get('detalhe') or ''),
2697
+ 'badge': str(ac.get('badge') or '▸'),
2698
+ 'badge_cor': ac.get('cor') or ACENTO2,
2699
+ 'ativo': bool(ac.get('ativo')),
2700
+ 'chave': str(idx),
2701
+ })
2702
+ elif idx < len(copias) and copias[idx]:
2703
+ txt = l.plain if isinstance(l, Text) else str(l)
2704
+ itens.append({'tipo': 'item', 'rotulo': txt, 'detalhe': 'toque p/ copiar',
2705
+ 'badge': '⎘', 'badge_cor': ACENTO2, 'chave': str(idx)})
2706
+ elif isinstance(l, Text):
2707
+ itens.append({'tipo': 'texto', 'rotulo': l.plain, 'rich': l, 'cor': TEXTO})
2378
2708
  else:
2379
- itens.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO})
2380
- limite_mod = max(2, min(len(itens), max(2, self.altura - 9)))
2709
+ itens.append({'tipo': 'texto', 'rotulo': str(l), 'cor': TEXTO})
2710
+ limite_mod = max(3, min(len(itens), max(3, self.altura - 8)))
2381
2711
  rich_lines, mapa_clique = tui_core.construir_dialogo_opencode(
2382
2712
  titulo=titulo,
2383
2713
  largura_caixa=w_box,
2384
2714
  itens=itens,
2385
- foco=-1,
2715
+ foco=0 if acoes else -1,
2386
2716
  topo=0,
2387
2717
  limite=limite_mod,
2388
2718
  rodape=dica,
@@ -2402,11 +2732,13 @@ class Painel:
2402
2732
  # Agrupa discretamente em 3 seções limpas (estilo OpenCode)
2403
2733
  itens_dlg = []
2404
2734
  def _secao_de(chave: str) -> str:
2405
- if chave in ('ag_hub', 'nv_ativar', 'wb_hub', 'oc_ativar', 'oauth_hub'):
2406
- return 'Accounts & Free'
2735
+ if chave in ('nv_ativar', 'oc_ativar'):
2736
+ return 'Built-in (Free · No Account)'
2737
+ if chave in ('ag_hub', 'wb_hub', 'oauth_hub'):
2738
+ return 'Accounts & OAuth'
2407
2739
  if chave in ('sync_opencode', 'custom_add'):
2408
2740
  return 'More'
2409
- return 'API Providers'
2741
+ return 'API Keys'
2410
2742
  sec_ant = None
2411
2743
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2412
2744
  for rotulo, chave, detalhe in filtrados:
@@ -2429,6 +2761,31 @@ class Painel:
2429
2761
  'ativo': eh_atual,
2430
2762
  'chave': chave,
2431
2763
  })
2764
+ elif self.wizard.get('tipo') == 'model' and (self.wizard.get('dados') or {}).get('entradas'):
2765
+ # Agrupa por provedor exatamente como o Select model do OpenCode
2766
+ entradas_map = {
2767
+ f"pm:{e['provedor']}:{e['id']}": e['secao']
2768
+ for e in (self.wizard.get('dados') or {}).get('entradas') or []
2769
+ }
2770
+ itens_dlg = []
2771
+ sec_ant = None
2772
+ chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2773
+ for rotulo, chave, detalhe in filtrados:
2774
+ sec = entradas_map.get(chave, 'Custom')
2775
+ if not self.buf.strip() and sec != sec_ant:
2776
+ itens_dlg.append({'tipo': 'secao', 'rotulo': sec})
2777
+ sec_ant = sec
2778
+ eh_atual = chave_atual is not None and chave == chave_atual
2779
+ badge = '●' if eh_atual else ('+' if chave == 'custom_id' else ' ')
2780
+ itens_dlg.append({
2781
+ 'tipo': 'item',
2782
+ 'rotulo': rotulo,
2783
+ 'detalhe': detalhe,
2784
+ 'badge': badge,
2785
+ 'badge_cor': OK if eh_atual else (ACENTO2 if chave == 'custom_id' else FRACO),
2786
+ 'ativo': eh_atual,
2787
+ 'chave': chave,
2788
+ })
2432
2789
  else:
2433
2790
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2434
2791
  itens_dlg = []
@@ -2473,8 +2830,29 @@ class Painel:
2473
2830
  mascarar = bool(w.get('passo') in ('chave', 'segredo'))
2474
2831
  itens_txt = []
2475
2832
  for l in linhas_w:
2476
- txt = l.plain if isinstance(l, Text) else str(l)
2477
- itens_txt.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO if txt else FRACO})
2833
+ if isinstance(l, Text):
2834
+ itens_txt.append({'tipo': 'texto', 'rotulo': l.plain, 'rich': l, 'cor': TEXTO if l.plain else FRACO})
2835
+ else:
2836
+ txt = str(l)
2837
+ itens_txt.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO if txt else FRACO})
2838
+ if w.get('tipo') == 'ag_callback' and (w.get('dados') or {}).get('url'):
2839
+ itens_txt.append({'tipo': 'texto', 'rotulo': '', 'cor': FRACO})
2840
+ itens_txt.append({
2841
+ 'tipo': 'item',
2842
+ 'rotulo': 'Copiar link OAuth',
2843
+ 'detalhe': 'toque / clique',
2844
+ 'badge': '⎘',
2845
+ 'badge_cor': ACENTO,
2846
+ 'chave': 'ag_copy_url',
2847
+ })
2848
+ itens_txt.append({
2849
+ 'tipo': 'item',
2850
+ 'rotulo': 'Abrir no navegador',
2851
+ 'detalhe': 'browser',
2852
+ 'badge': '↗',
2853
+ 'badge_cor': ACENTO2,
2854
+ 'chave': 'ag_open_url',
2855
+ })
2478
2856
  # Placeholder minimalista conforme o passo
2479
2857
  passo_w = w.get('passo')
2480
2858
  placeholder_w = {
@@ -2493,7 +2871,7 @@ class Painel:
2493
2871
  limite=max(8, len(itens_txt)),
2494
2872
  busca=self.buf,
2495
2873
  placeholder=placeholder_w,
2496
- rodape='Enter confirma · Esc cancela',
2874
+ rodape='Enter confirma · Esc voltar',
2497
2875
  cores=cores,
2498
2876
  mascarar_busca=mascarar,
2499
2877
  mostrar_busca=True,
@@ -2505,22 +2883,34 @@ class Painel:
2505
2883
  visivel = self._texto_entrada()
2506
2884
  largura = self.largura
2507
2885
  contagem = cell_len(visivel)
2886
+ # Pulso visual sutil no "▸" enquanto o usuário digita
2887
+ pulso_ativo = (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.16
2888
+ cor_prompt = 'acento3' if pulso_ativo else 'acento'
2508
2889
  partes = [
2509
2890
  f'\x1b[{linha};1H\x1b[2K',
2510
- ansi('borda'), '│', RESET, ' ', ansi('acento'), '▸ ', RESET,
2891
+ ansi('borda'), '│', RESET, ' ', ansi(cor_prompt), '▸ ', RESET,
2511
2892
  ]
2512
2893
  if visivel:
2513
2894
  partes.extend([ansi('texto'), visivel, RESET])
2895
+ # Cursor de digitação limpo (barra fina) quando há texto sendo digitado
2896
+ if pulso_ativo and contagem + 1 <= max(1, largura - 6):
2897
+ partes.extend([ansi('acento'), '▏', RESET])
2898
+ contagem += 1
2514
2899
  elif self._wizard_lista():
2515
2900
  dica = 'filtrar…'
2516
2901
  partes.extend([ansi('fraco'), dica, RESET])
2517
2902
  contagem = cell_len(dica)
2518
2903
  elif not self.wizard:
2519
- dica = '/ commands · Ctrl+L connect · Ctrl+P palette'
2520
- if cell_len(dica) > largura - 8:
2521
- dica = '/ commands · /connect'
2522
- if cell_len(dica) > largura - 8:
2523
- dica = '/help'
2904
+ dica_cheia = _DICAS_HOME[getattr(self, '_dica_idx', 0) % len(_DICAS_HOME)]
2905
+ if cell_len(dica_cheia) > largura - 8:
2906
+ dica_cheia = '/ commands · /connect'
2907
+ if cell_len(dica_cheia) > largura - 8:
2908
+ dica_cheia = '/help'
2909
+ n_chars = getattr(self, '_dica_chars', len(dica_cheia))
2910
+ if n_chars <= 0 or n_chars >= len(dica_cheia):
2911
+ dica = dica_cheia
2912
+ else:
2913
+ dica = dica_cheia[:n_chars] + '▏'
2524
2914
  dica = tui_core.truncate_vis(dica, max(1, largura - 7))
2525
2915
  partes.extend([ansi('fraco'), dica, RESET])
2526
2916
  contagem = cell_len(dica)
@@ -2550,8 +2940,8 @@ class Painel:
2550
2940
  # Cache do frame base: quando um diálogo está aberto e os dados não mudaram,
2551
2941
  # reaproveita o fundo esmaecido sem re-renderizar tabela/painéis Rich a cada seta/scroll.
2552
2942
  em_restart = bool(getattr(self, '_restart_overlay', None))
2553
- chave_base = (self.largura, self.altura, self.coletor.revisao, self.scroll,
2554
- TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
2943
+ chave_base = (self.largura, self.altura, self.coletor.revisao, self.atualizacoes.revisao,
2944
+ self.scroll, TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
2555
2945
  cache = getattr(self, '_cache_frame_base', None)
2556
2946
  if tem_overlay and cache and cache[0] == chave_base:
2557
2947
  frame = list(cache[1])
@@ -2569,16 +2959,22 @@ class Painel:
2569
2959
  self._cache_frame_base = (chave_base, list(frame), cortado)
2570
2960
  self._overlay_top = None
2571
2961
  self._overlay_left = None
2962
+ self._overlay_width = 0
2963
+ self._overlay_height = 0
2572
2964
  self._overlay_clique = {}
2573
- # Quando um diálogo novo abre na TUI, anima brevemente a revelação (slide/expand)
2574
- # Em telas pequenas/estreitas (Termux/celular) ou após resize, pula o slide para
2575
- # nunca sobrepor dois quadros parciais.
2965
+ # Quando um diálogo novo abre na TUI, anima a abertura (2 frames rápidos,
2966
+ # inclusive no celular, pois cada linha agora usa \x1b[row;1H\x1b[2K limpo).
2576
2967
  modal_identidade = ('tokens-live' if (self.modal or {}).get('tipo') == 'tokens' else id(self.modal))
2577
2968
  dialogo_atual = (id(self.wizard), (self.wizard or {}).get('tipo'), (self.wizard or {}).get('passo'), modal_identidade, em_restart)
2578
2969
  if tem_overlay and dialogo_atual != getattr(self, '_dialogo_id', None):
2579
2970
  self._dialogo_id = dialogo_atual
2580
- self._dialogo_frame = 99 if (self.largura < 80 or self.altura < 24 or tui_core.is_termux()) else 0
2971
+ self._dialogo_frame = 0 if (self.altura >= 14 and not em_restart) else 99
2972
+ self._fechar_overlay_frame = 0
2581
2973
  elif not tem_overlay:
2974
+ if getattr(self, '_dialogo_id', None) is not None and getattr(self, '_ultimo_overlay_linhas', None):
2975
+ self._fechar_overlay_linhas = list(self._ultimo_overlay_linhas)
2976
+ self._fechar_overlay_frame = 1
2977
+ self._ultimo_overlay_linhas = []
2582
2978
  self._dialogo_id = None
2583
2979
  self._dialogo_frame = 99
2584
2980
  # Em telas baixas, garante que o frame do overlay nunca passe da area util
@@ -2589,11 +2985,12 @@ class Painel:
2589
2985
  if len(caixa_linhas) > limite and limite >= 4:
2590
2986
  caixa_linhas = caixa_linhas[:limite - 1] + [caixa_linhas[-1]]
2591
2987
  mapa_clique = {k: v for k, v in mapa_clique.items() if k < limite - 1}
2592
- # Animação de entrada suave (2 frames rápidos, sem travar teclado)
2593
- if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 6:
2988
+ self._ultimo_overlay_linhas = list(caixa_linhas)
2989
+ # Animação de abertura suave (2 frames rápidos, sem travar teclado)
2990
+ if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 5:
2594
2991
  passo_a = self._dialogo_frame
2595
2992
  self._dialogo_frame += 1
2596
- recorte = max(4, int(len(caixa_linhas) * (0.55 if passo_a == 0 else 0.82)))
2993
+ recorte = max(4, int(len(caixa_linhas) * (0.50 if passo_a == 0 else 0.80)))
2597
2994
  caixa_vis = caixa_linhas[:recorte - 1] + [caixa_linhas[-1]]
2598
2995
  else:
2599
2996
  caixa_vis = caixa_linhas
@@ -2607,14 +3004,16 @@ class Painel:
2607
3004
  )
2608
3005
  self._overlay_top = top
2609
3006
  self._overlay_left = left
3007
+ self._overlay_width = _w_box
3008
+ self._overlay_height = len(caixa_vis)
2610
3009
  self._overlay_clique = mapa_clique
2611
3010
  self._menu_ini = None
2612
- if self.wizard and self._wizard_lista():
3011
+ if self.wizard and (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback'):
2613
3012
  self._wizard_ini = top
2614
3013
  self._wizard_item_linhas = mapa_clique
2615
3014
  else:
2616
3015
  self._wizard_ini = None
2617
- if self.modal and self.modal.get('copias'):
3016
+ if self.modal and (self.modal.get('copias') or self.modal.get('acoes')):
2618
3017
  self._modal_ini = top
2619
3018
  else:
2620
3019
  self._modal_ini = None
@@ -2622,12 +3021,27 @@ class Painel:
2622
3021
  self._registrar_menu(frame, cortado)
2623
3022
  self._registrar_wizard(frame, cortado)
2624
3023
  self._registrar_modal(frame, cortado)
3024
+ elif getattr(self, '_fechar_overlay_frame', 0) > 0 and getattr(self, '_fechar_overlay_linhas', None):
3025
+ # Transição rápida de fechamento (1 frame encolhendo a caixa antes de sumir)
3026
+ caixa_ant = self._fechar_overlay_linhas
3027
+ self._fechar_overlay_frame = 0
3028
+ self._fechar_overlay_linhas = []
3029
+ if len(caixa_ant) > 5 and limite >= 6:
3030
+ recorte = max(4, int(len(caixa_ant) * 0.48))
3031
+ caixa_vis = caixa_ant[:recorte - 1] + [caixa_ant[-1]]
3032
+ frame, _, _ = tui_core.desenhar_overlay_centrado(
3033
+ frame, caixa_vis, self.largura, limite, cor_fundo_ansi='', esmaecer_fundo=False
3034
+ )
3035
+ self._registrar_menu(frame, cortado)
3036
+ self._registrar_wizard(frame, cortado)
3037
+ self._registrar_modal(frame, cortado)
2625
3038
  else:
2626
3039
  self._registrar_menu(frame, cortado)
2627
3040
  self._registrar_wizard(frame, cortado)
2628
3041
  self._registrar_modal(frame, cortado)
2629
3042
  self.desenhar(frame)
2630
3043
  self.revisao_vista = self.coletor.revisao
3044
+ self._update_revisao_vista = self.atualizacoes.revisao
2631
3045
 
2632
3046
  # -- teclado e mouse ------------------------------------------------------
2633
3047
  def ler_tecla(self, timeout: float):
@@ -2751,9 +3165,15 @@ class Painel:
2751
3165
  return None
2752
3166
 
2753
3167
  def _precisa_animar(self) -> bool:
2754
- """Indica se ha algo vivo para animar (restart, abertura de dialogo, tarefa ou geracao em voo)."""
3168
+ """Indica se ha algo vivo para animar (abertura, fechamento, digitacao, restart, tarefa ou live)."""
2755
3169
  if getattr(self, '_restart_overlay', None):
2756
3170
  return True
3171
+ if getattr(self, '_intro_frame', 99) < 3:
3172
+ return True
3173
+ if getattr(self, '_fechar_overlay_frame', 0) > 0:
3174
+ return True
3175
+ if (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.18:
3176
+ return True
2757
3177
  if self.modo == 'tui' and (self.wizard or self.modal) and getattr(self, '_dialogo_frame', 99) < 2:
2758
3178
  return True
2759
3179
  if self.tarefa_ativa:
@@ -2764,6 +3184,48 @@ class Painel:
2764
3184
  return True
2765
3185
  return False
2766
3186
 
3187
+ # Imersão rápida na abertura da TUI (funciona em `krnell` e ao abrir pelo OpenCode)
3188
+ def _animar_abertura_tui(self, saida) -> None:
3189
+ if os.environ.get('KRNELL_NO_INTRO') == '1' or not sys.stdout.isatty():
3190
+ self._intro_frame = 3
3191
+ return
3192
+ larg, alt = shutil.get_terminal_size((110, 30))
3193
+ if larg < 36 or alt < 14:
3194
+ self._intro_frame = 3
3195
+ return
3196
+ centro_y = max(2, (alt - 5) // 2)
3197
+ pad_x = max(0, (larg - 30) // 2)
3198
+ ver = f'v{versao_local()}'
3199
+ pad_v = max(0, (larg - len(ver) - 9) // 2)
3200
+ saida.write('\x1b[?25l\x1b[2J\x1b[H')
3201
+ for passo in range(1, 4):
3202
+ buf = ['\x1b[?2026h']
3203
+ for i in range(passo):
3204
+ esq_l, dir_l = _LOGO_KRNELL[i]
3205
+ buf.append(
3206
+ f'\x1b[{centro_y + i};1H\x1b[2K'
3207
+ + ' ' * pad_x
3208
+ + ansi('texto') + esq_l + ansi('acento') + dir_l + RESET
3209
+ )
3210
+ sub = '◈ krnell ' + ver
3211
+ bar = ('━' * (passo * 6)) + ('─' * ((3 - passo) * 6))
3212
+ buf.append(
3213
+ f'\x1b[{centro_y + 4};1H\x1b[2K'
3214
+ + ' ' * pad_v
3215
+ + ansi('acento') + sub + RESET
3216
+ )
3217
+ pad_b = max(0, (larg - len(bar)) // 2)
3218
+ buf.append(
3219
+ f'\x1b[{centro_y + 5};1H\x1b[2K'
3220
+ + ' ' * pad_b
3221
+ + ansi('acento2') + bar + RESET
3222
+ + '\x1b[?2026l'
3223
+ )
3224
+ saida.write(''.join(buf))
3225
+ saida.flush()
3226
+ time.sleep(0.055)
3227
+ self._intro_frame = 3
3228
+
2767
3229
  def rodar_tui(self) -> None:
2768
3230
  if not self.ativar_vt():
2769
3231
  self.modo = 'repl'
@@ -2775,9 +3237,10 @@ class Painel:
2775
3237
  self.iniciar_bridge_na_abertura()
2776
3238
  self.iniciar_dashboard_na_abertura()
2777
3239
  saida = sys.stdout
2778
- saida.write('\x1b[?1049h\x1b[?25h')
3240
+ saida.write('\x1b[?1049h\x1b[?25l')
2779
3241
  saida.write('\x1b[?7l')
2780
3242
  saida.flush()
3243
+ self._animar_abertura_tui(saida)
2781
3244
  self._precisa_limpar_tela = True
2782
3245
  try:
2783
3246
  self.atualizar_tela()
@@ -2788,12 +3251,37 @@ class Painel:
2788
3251
  if tecla is None:
2789
3252
  nova_larg, nova_alt = shutil.get_terminal_size((self.largura, self.altura))
2790
3253
  mudou_tamanho = (nova_larg != self.largura or nova_alt != self.altura)
2791
- mudou_dados = self.coletor.revisao != self.revisao_vista
3254
+ mudou_dados = (
3255
+ self.coletor.revisao != self.revisao_vista
3256
+ or self.atualizacoes.revisao != self._update_revisao_vista
3257
+ )
2792
3258
  expirou_msg = bool(self.msg and time.time() > self.msg_ate)
2793
3259
  if expirou_msg:
2794
3260
  self.msg = None
2795
- intervalo_anim = 0.03 if getattr(self, '_dialogo_frame', 99) < 2 else (0.09 if animando else 0.9)
3261
+ intervalo_anim = (
3262
+ 0.035 if (
3263
+ getattr(self, '_dialogo_frame', 99) < 2
3264
+ or getattr(self, '_fechar_overlay_frame', 0) > 0
3265
+ or getattr(self, '_intro_frame', 99) < 3
3266
+ ) else (0.08 if animando else 0.9)
3267
+ )
2796
3268
  tick_anim = (agora - self._anim_ultimo) >= intervalo_anim
3269
+ # Animação de digitação sutil no placeholder da home quando ocioso
3270
+ anim_dica = False
3271
+ if not self.buf and not self.wizard and not self.modal and not self._restart_overlay:
3272
+ dica_alvo = _DICAS_HOME[self._dica_idx % len(_DICAS_HOME)]
3273
+ if self._dica_chars < len(dica_alvo):
3274
+ if (agora - self._dica_ultimo) >= 0.045:
3275
+ self._dica_chars += 2
3276
+ self._dica_ultimo = agora
3277
+ anim_dica = True
3278
+ elif (agora - self._dica_ultimo) >= 5.5:
3279
+ self._dica_idx = (self._dica_idx + 1) % len(_DICAS_HOME)
3280
+ self._dica_chars = 0
3281
+ self._dica_ultimo = agora
3282
+ anim_dica = True
3283
+ if tick_anim and getattr(self, '_intro_frame', 99) < 3:
3284
+ self._intro_frame += 1
2797
3285
  if tick_anim and (animando or (not self.wizard and not self.modal)):
2798
3286
  self._anim_tick = (self._anim_tick + 1) % 100000
2799
3287
  self._anim_ultimo = agora
@@ -2801,8 +3289,10 @@ class Painel:
2801
3289
  self._cache_frame_base = None
2802
3290
  self._dialogo_frame = 99
2803
3291
  self._precisa_limpar_tela = True
2804
- if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
3292
+ if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and animando):
2805
3293
  self.atualizar_tela()
3294
+ elif anim_dica:
3295
+ self.desenhar_linha_entrada()
2806
3296
  continue
2807
3297
  # Coalescing de scroll/setas: drena eventos repetidos pendentes no buffer
2808
3298
  # para manter a rolagem lisa sem travar o terminal.
@@ -2875,11 +3365,30 @@ class Painel:
2875
3365
  print(f'não consegui reexecutar a TUI ({exc}). Execute: krnell')
2876
3366
  return
2877
3367
  return
3368
+ if getattr(self, '_sair_em_background', False):
3369
+ self.proc = None
3370
+ self._soltar_job()
3371
+ estado = ('bridge segue rodando em background — use /exit na TUI para desligar'
3372
+ if self.bridge_online() else 'bridge parado')
3373
+ print(f'painel fechado — {estado}.')
3374
+ return
2878
3375
  tinha_bridge = self._encerrar_com_o_painel()
3376
+ # /exit desliga o bridge de verdade (mesmo que tenha sido iniciado antes em background)
3377
+ if not tinha_bridge and self.bridge_online():
3378
+ try:
3379
+ self._parar_bridge()
3380
+ tinha_bridge = True
3381
+ except Exception:
3382
+ pass
3383
+ try:
3384
+ cfg_fim = ler_config()
3385
+ prov_cfg = ((cfg_fim.get('provedores') or {}).get(cfg_fim.get('provider')) or {})
3386
+ porta_m = kimi.porta_de(prov_cfg.get('base_url') or cfg_fim.get('upstream_base_url') or '')
3387
+ kimi.parar_motor(ROOT, porta_m)
3388
+ except Exception:
3389
+ pass
2879
3390
  if tinha_bridge:
2880
- estado = 'o bridge encerrou junto com o painel (portas fechadas)'
2881
- elif self.bridge_online():
2882
- estado = 'o bridge segue no ar — foi iniciado fora deste painel'
3391
+ estado = 'bridge e motor local encerrados (portas fechadas)'
2883
3392
  else:
2884
3393
  estado = 'bridge parado'
2885
3394
  print(f'painel encerrado — {estado}.')
@@ -2927,9 +3436,19 @@ class Painel:
2927
3436
  self._reexec_solicitado = False
2928
3437
  self.atualizar_tela()
2929
3438
  return
2930
- if tecla == 'esc' and self.wizard and self.wizard.get('tipo') in ('ag_hub', 'wb_hub', 'oauth_hub'):
2931
- self.buf = ''
2932
- self.abrir_hub_connect()
3439
+ if tecla == 'esc':
3440
+ if self.modal:
3441
+ self.modal = None
3442
+ elif self.wizard:
3443
+ voltou = self._voltar_wizard()
3444
+ if not voltou:
3445
+ self.msg = ('aviso', 'fechado')
3446
+ self.msg_ate = time.time() + 2
3447
+ elif self._menu_aberto():
3448
+ # como no OpenCode: o texto fica; o popup volta na próxima tecla
3449
+ self.menu_off = True
3450
+ else:
3451
+ self.buf = ''
2933
3452
  self.atualizar_tela()
2934
3453
  return
2935
3454
  if tecla == 'ctrl_m':
@@ -2957,18 +3476,31 @@ class Painel:
2957
3476
  pass # modal fecha somente com Enter/Esc
2958
3477
  else:
2959
3478
  self.buf += tecla[1]
3479
+ self._digito_pulso = time.monotonic()
2960
3480
  redesenhar = True
2961
3481
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_clique':
2962
3482
  if self.clicar_botao_update(tecla[1], tecla[2]):
2963
3483
  redesenhar = True
2964
3484
  elif self.clicar_botao_copiar(tecla[1], tecla[2]):
2965
3485
  redesenhar = True
2966
- elif self.modal and self.modal.get('copias'):
2967
- redesenhar = self.clicar_modal(tecla[2])
2968
- elif self.wizard and self._wizard_lista():
2969
- redesenhar = self.clicar_wizard(tecla[2])
3486
+ elif self.ponto_no_botao_esc(tecla[1], tecla[2]):
3487
+ if self.modal:
3488
+ self.modal = None
3489
+ else:
3490
+ self._voltar_wizard()
3491
+ redesenhar = True
3492
+ elif self.modal and (self.modal.get('copias') or self.modal.get('acoes')) and self.clicar_modal(tecla[2]):
3493
+ redesenhar = True
3494
+ elif self.wizard and (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback') and self.clicar_wizard(tecla[2]):
3495
+ redesenhar = True
3496
+ elif self.wizard and self._wizard_lista() and self.clicar_scroll_overlay(tecla[1], tecla[2]):
3497
+ redesenhar = True
3498
+ elif (self.modal or self.wizard) and self.clicar_fora_overlay(tecla[1], tecla[2]):
3499
+ redesenhar = True
3500
+ elif self.clicar_menu(tecla[2]):
3501
+ redesenhar = True
2970
3502
  else:
2971
- redesenhar = self.clicar_menu(tecla[2])
3503
+ redesenhar = self.clicar_barra_home(tecla[1], tecla[2])
2972
3504
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_move':
2973
3505
  redesenhar = self.passar_mouse(tecla[1], tecla[2])
2974
3506
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_roda':
@@ -3002,6 +3534,9 @@ class Painel:
3002
3534
  elif self.modal or self.wizard:
3003
3535
  self.modal = self.wizard = None
3004
3536
  else:
3537
+ # Ctrl+C fecha somente a TUI e deixa o bridge rodando em background
3538
+ # (Windows, Linux, Ubuntu e Termux). Use /exit para desligar de verdade.
3539
+ self._sair_em_background = True
3005
3540
  self.saindo = True
3006
3541
  redesenhar = True
3007
3542
  elif tecla == 'cima':
@@ -3215,6 +3750,7 @@ class Painel:
3215
3750
  self.msg_ate = time.time() + segundos
3216
3751
 
3217
3752
  def fechar(self, arg: str = ''):
3753
+ self._sair_em_background = False
3218
3754
  self.saindo = True
3219
3755
 
3220
3756
  def _linhas_ajuda_colunas(self, itens) -> list:
@@ -3898,35 +4434,57 @@ class Painel:
3898
4434
  ag_contas = ag_st.get('accounts') or []
3899
4435
  if ag_contas:
3900
4436
  linhas.append(Text(''))
3901
- linhas.append(Text('antigravity (5h · semanal)', style=FRACO))
4437
+ linhas.append(Text('ANTIGRAVITY (5h · 7d)', style=f'bold {ACENTO2}'))
3902
4438
  for acc in ag_contas:
3903
4439
  email = str(acc.get('email') or 'Google')
3904
4440
  ativa = bool(acc.get('active'))
3905
4441
  t = Text()
3906
4442
  t.append('● ' if ativa else '○ ', style=OK if ativa else FRACO)
3907
- t.append(email, style=TEXTO if ativa else FRACO)
4443
+ t.append(email, style=f'bold {TEXTO}' if ativa else FRACO)
3908
4444
  tier = acc.get('paidTierName') or ''
3909
4445
  if tier:
3910
- t.append(f' · {tier}', style=FRACO)
4446
+ t.append(f' · {tier}', style=FRACO)
3911
4447
  linhas.append(t)
3912
4448
  q_acc = acc.get('quota') if isinstance(acc.get('quota'), dict) else (
3913
4449
  ag_st.get('quota') if ativa and isinstance(ag_st.get('quota'), dict) else {})
4450
+ estreito_q = self.largura < 68
3914
4451
  for item_q in _resumo_cota_antigravity({'quota': q_acc}):
3915
- tq = Text()
3916
- tq.append(f" {item_q['nome']:<8}", style=FRACO)
3917
4452
  b5 = item_q.get('b5h')
3918
4453
  bs = item_q.get('bsem')
3919
- if isinstance(b5, dict) and isinstance(b5.get('remainingFraction'), (int, float)):
3920
- f5 = b5['remainingFraction']
3921
- t5, c5 = _fmt_bucket_curto(b5, '5h')
3922
- tq.append(tui_core.barra_progresso(f5, 6) + ' ' + t5, style=c5)
3923
- if bs:
3924
- tq.append(' ', style=FRACO)
3925
- if isinstance(bs, dict) and isinstance(bs.get('remainingFraction'), (int, float)):
3926
- fs = bs['remainingFraction']
3927
- ts, cs = _fmt_bucket_curto(bs, '7d')
3928
- tq.append(tui_core.barra_progresso(fs, 6) + ' ' + ts, style=cs)
3929
- linhas.append(tq)
4454
+ tem_5h = isinstance(b5, dict) and isinstance(b5.get('remainingFraction'), (int, float))
4455
+ tem_7d = isinstance(bs, dict) and isinstance(bs.get('remainingFraction'), (int, float))
4456
+ if estreito_q:
4457
+ # No celular: 1 linha limpa por janela, sem espremer nem quebrar com "..."
4458
+ if tem_5h:
4459
+ f5 = b5['remainingFraction']
4460
+ t5, c5 = _fmt_bucket_curto(b5, '5h')
4461
+ tq = Text()
4462
+ tq.append(f" {item_q['nome']:<7} ", style=TEXTO)
4463
+ tq.append(tui_core.barra_progresso(f5, 8) + ' ', style=c5)
4464
+ tq.append(t5, style=c5)
4465
+ linhas.append(tq)
4466
+ if tem_7d:
4467
+ fs = bs['remainingFraction']
4468
+ ts, cs = _fmt_bucket_curto(bs, '7d')
4469
+ tq = Text()
4470
+ tq.append((' ' if tem_5h else f" {item_q['nome']:<7} "), style=TEXTO)
4471
+ tq.append(tui_core.barra_progresso(fs, 8) + ' ', style=cs)
4472
+ tq.append(ts, style=cs)
4473
+ linhas.append(tq)
4474
+ else:
4475
+ tq = Text()
4476
+ tq.append(f" {item_q['nome']:<8}", style=TEXTO)
4477
+ if tem_5h:
4478
+ f5 = b5['remainingFraction']
4479
+ t5, c5 = _fmt_bucket_curto(b5, '5h')
4480
+ tq.append(tui_core.barra_progresso(f5, 6) + ' ' + t5, style=c5)
4481
+ if tem_7d:
4482
+ tq.append(' ', style=FRACO)
4483
+ if tem_7d:
4484
+ fs = bs['remainingFraction']
4485
+ ts, cs = _fmt_bucket_curto(bs, '7d')
4486
+ tq.append(tui_core.barra_progresso(fs, 6) + ' ' + ts, style=cs)
4487
+ linhas.append(tq)
3930
4488
  contas_wb = self._contas_workbuddy()
3931
4489
  if contas_wb:
3932
4490
  linhas.append(Text(''))
@@ -3974,7 +4532,7 @@ class Painel:
3974
4532
  style=FRACO))
3975
4533
  linhas.append(Text('o bridge soma sozinho a cada resposta; cotas 5h/7d revalidam ao vivo.', style=FRACO))
3976
4534
  self.modal = {'tipo': 'tokens', 'titulo': 'Quotas & tokens', 'linhas': linhas,
3977
- 'dica': 'live · Enter ou Esc fecha', 'revisao': self.coletor.revisao}
4535
+ 'dica': 'live · Esc ou toque fora fecha', 'revisao': self.coletor.revisao}
3978
4536
 
3979
4537
  def mostrar_stats(self, arg: str = ''):
3980
4538
  itens = ler_requisicoes(3000, linhas_max=3000)
@@ -4079,6 +4637,7 @@ class Painel:
4079
4637
 
4080
4638
  def abrir_hub_connect(self, arg: str = ''):
4081
4639
  """Hub unificado /connect: provedores, OAuth (Antigravity/WorkBuddy), chaves e OpenCode."""
4640
+ self._pilha().clear()
4082
4641
  alvo = (arg or '').strip().lower()
4083
4642
  if alvo in ('antigravity', 'ag', 'google'):
4084
4643
  self.abrir_hub_antigravity()
@@ -4120,32 +4679,33 @@ class Painel:
4120
4679
  return kimi.PORTA_PADRAO
4121
4680
 
4122
4681
  def iniciar_login_antigravity(self):
4123
- """Dispara fluxo OAuth do Antigravity (abre navegador + permite colar callback no Termux/SSH)."""
4682
+ """Dispara fluxo OAuth do Antigravity (abre navegador + botões copiar/abrir + colar callback)."""
4124
4683
  def tarefa():
4125
4684
  porta = self._porta_motor_local()
4126
4685
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=18.0)
4127
- url = kimi.antigravity_login_url(porta)
4686
+ url, state = kimi.antigravity_login_url(porta)
4128
4687
  abriu = tui_core.abrir_url_sistema(url)
4129
4688
  copiou = copiar_area_transferencia(url)
4130
4689
  self._ag_auth_url = url
4131
- self.wizard = {
4690
+ self._ag_auth_state = state
4691
+ self._empilhar_wizard({
4132
4692
  'tipo': 'ag_callback',
4133
4693
  'passo': 'colar',
4134
4694
  'titulo': 'Antigravity · Google OAuth',
4135
- 'dados': {'url': url, 'abriu': abriu, 'copiou': copiou, 'porta': porta},
4136
- }
4137
- nota = ('navegador aberto' if abriu else 'abra o link acima') + (' · copiado' if copiou else '')
4138
- return ('ok', f'OAuth pronto ({nota}) — conclua no navegador ou cole a URL de callback')
4695
+ 'dados': {'url': url, 'state': state, 'abriu': abriu, 'copiou': copiou, 'porta': porta},
4696
+ })
4697
+ nota = ('navegador aberto' if abriu else 'copie ou abra o link') + (' · copiado' if copiou else '')
4698
+ return ('ok', f'OAuth pronto ({nota})')
4139
4699
  self.rodar_tarefa(tarefa, 'iniciando OAuth do Antigravity…')
4140
4700
 
4141
- def tarefa_concluir_antigravity(self, entrada: str):
4701
+ def tarefa_concluir_antigravity(self, entrada: str, state: str = ''):
4142
4702
  porta = self._porta_motor_local()
4143
4703
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=15.0)
4144
- res = kimi.antigravity_completar(entrada, porta=porta)
4704
+ res = kimi.antigravity_completar(entrada, state=state or self._ag_auth_state, porta=porta)
4145
4705
  if not res.get('ok'):
4146
4706
  raise ValueError(res.get('error') or 'falha ao completar OAuth')
4147
4707
  email = res.get('email') or 'conta Google'
4148
- return ('ok', f'Antigravity connected: {email} · use /connect to switch')
4708
+ return ('ok', f'Antigravity connected: {email} · use /model to select')
4149
4709
 
4150
4710
  def tarefa_selecionar_conta_antigravity(self, email: str):
4151
4711
  """Seleciona a conta Google no Antigravity e ativa o provedor se ainda não estiver ativo."""
@@ -4230,19 +4790,46 @@ class Painel:
4230
4790
  url = inicio['auth_url']
4231
4791
  abriu = tui_core.abrir_url_sistema(url)
4232
4792
  copiou = copiar_area_transferencia(url)
4793
+
4794
+ def _copiar_wb():
4795
+ if copiar_area_transferencia(url):
4796
+ self.avisar('link de login copiado', 'ok', 6)
4797
+ else:
4798
+ self.avisar(f'copie manualmente: {url}', 'aviso', 10)
4799
+
4800
+ def _abrir_wb():
4801
+ if tui_core.abrir_url_sistema(url):
4802
+ self.avisar('abrindo no navegador…', 'ok', 6)
4803
+ else:
4804
+ copiar_area_transferencia(url)
4805
+ self.avisar('navegador não abriu — link copiado para colar no browser', 'aviso', 8)
4806
+
4807
+ estado_txt = ('navegador aberto · ' if abriu else 'abra no navegador · ') + (
4808
+ 'link copiado · ' if copiou else ''
4809
+ ) + 'aguardando login…'
4810
+ linhas_wb = [
4811
+ Text('Conclua o login no navegador (celular ou outro PC).', style=TEXTO),
4812
+ Text(tui_core.truncate_vis(url, 66), style=FRACO),
4813
+ Text(''),
4814
+ Text('Copiar link de login'),
4815
+ Text('Abrir no navegador'),
4816
+ Text(''),
4817
+ Text(estado_txt, style=ACENTO2),
4818
+ ]
4819
+ acoes_wb = [
4820
+ None,
4821
+ None,
4822
+ None,
4823
+ {'rotulo': 'Copiar link de login', 'detalhe': 'toque / clique', 'badge': '⎘', 'cor': ACENTO, 'fn': _copiar_wb},
4824
+ {'rotulo': 'Abrir no navegador', 'detalhe': 'browser', 'badge': '↗', 'cor': ACENTO2, 'fn': _abrir_wb},
4825
+ None,
4826
+ None,
4827
+ ]
4233
4828
  self.modal = {
4234
- 'titulo': 'Login WorkBuddy',
4235
- 'linhas': [Text('1. abra o endereço abaixo no navegador'),
4236
- Text(url, style=f'bold {ACENTO2}'),
4237
- Text('pode ser em outro PC ou no celular: o login vale no servidor',
4238
- style=FRACO),
4239
- Text('2. entre com a conta do WorkBuddy (WeChat, QQ, e-mail…)'),
4240
- Text('3. volte aqui: a conta entra sozinha quando o login terminar',
4241
- style=FRACO),
4242
- Text(('navegador aberto · ' if abriu else 'abra o endereço manualmente · ')
4243
- + ('endereço copiado · ' if copiou else '')
4244
- + 'aguardando…', style=FRACO)],
4245
- 'dica': 'Esc fecha o quadro · o login continua em segundo plano',
4829
+ 'titulo': 'Login · WorkBuddy',
4830
+ 'linhas': linhas_wb,
4831
+ 'acoes': acoes_wb,
4832
+ 'dica': 'toque nos botões acima · Esc fecha (login segue em 2º plano)',
4246
4833
  }
4247
4834
  threading.Thread(target=self._concluir_login_workbuddy, args=(inicio,),
4248
4835
  daemon=True, name='workbuddy-login').start()
@@ -4520,8 +5107,9 @@ class Painel:
4520
5107
  dados = w.get('dados') or {}
4521
5108
  url = dados.get('url') or ''
4522
5109
  return [
4523
- Text(url or 'use + Conectar conta Google primeiro', style=ACENTO2),
4524
- Text('cole a URL de callback ou pressione Esc se já concluiu', style=FRACO),
5110
+ Text('1. Abra o link abaixo no navegador e faça login com o Google.', style=TEXTO),
5111
+ Text(tui_core.truncate_vis(url, max(24, self.largura - 10)) if url else 'use + Add account primeiro', style=FRACO),
5112
+ Text('2. Se o retorno não concluir sozinho, cole a URL final e dê Enter.', style=FRACO),
4525
5113
  ]
4526
5114
  if w.get('tipo') == 'add':
4527
5115
  passo = w.get('passo')
@@ -4560,42 +5148,55 @@ class Painel:
4560
5148
  itens_l = dados_l[0] if dados_l else []
4561
5149
  idx = int(escolha) - 1
4562
5150
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4563
- self.wizard = None
4564
5151
  if escolha == 'ag_hub':
4565
- self.abrir_hub_antigravity()
5152
+ self._empilhar_wizard({'tipo': 'ag_hub', 'passo': 'menu', 'titulo': 'Antigravity', 'dados': {}})
4566
5153
  elif escolha == 'nv_ativar':
5154
+ self._pilha().clear()
5155
+ self.wizard = None
4567
5156
  self.acao_trocar_provider('nvidia')
4568
5157
  elif escolha == 'wb_hub':
4569
- self.wizard = {'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}}
5158
+ self._empilhar_wizard({'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}})
4570
5159
  elif escolha == 'oc_ativar':
5160
+ self._pilha().clear()
5161
+ self.wizard = None
4571
5162
  self.acao_trocar_provider('opencode')
4572
5163
  elif escolha == 'oauth_hub':
4573
- self.wizard = {'tipo': 'oauth_hub', 'passo': 'menu',
4574
- 'titulo': 'OAuth', 'dados': {}}
5164
+ self._empilhar_wizard({'tipo': 'oauth_hub', 'passo': 'menu',
5165
+ 'titulo': 'OAuth', 'dados': {}})
4575
5166
  elif escolha.startswith('preset:'):
4576
5167
  slug = escolha.split(':', 1)[1]
4577
5168
  preset = provedores_catalogo.PRESET_POR_SLUG.get(slug)
4578
5169
  if not preset:
5170
+ self.wizard = None
4579
5171
  self.avisar('provedor desconhecido', 'erro')
4580
5172
  elif slug == 'ollama':
5173
+ self._pilha().clear()
5174
+ self.wizard = None
4581
5175
  self.rodar_tarefa(lambda: self.tarefa_conectar_preset(slug, ''),
4582
5176
  'conectando Ollama…')
4583
5177
  else:
4584
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4585
- 'titulo': preset['nome'],
4586
- 'dados': {'destino': slug, 'preset': slug}}
5178
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
5179
+ 'titulo': preset['nome'],
5180
+ 'dados': {'destino': slug, 'preset': slug}})
4587
5181
  elif escolha.startswith('key:'):
4588
5182
  destino = escolha.split(':', 1)[1]
4589
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4590
- 'titulo': destino,
4591
- 'dados': {'destino': destino}}
5183
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
5184
+ 'titulo': destino,
5185
+ 'dados': {'destino': destino}})
4592
5186
  elif escolha == 'custom_add':
4593
- self.abrir_wizard_add()
5187
+ self._empilhar_wizard({'tipo': 'add', 'passo': 'nome', 'titulo': 'Novo provedor',
5188
+ 'dados': {}})
4594
5189
  elif escolha == 'sync_opencode':
5190
+ self._pilha().clear()
5191
+ self.wizard = None
4595
5192
  self.acao_opencode()
4596
5193
  elif escolha.startswith('prov:'):
5194
+ self._pilha().clear()
5195
+ self.wizard = None
4597
5196
  self.acao_trocar_provider(escolha.split(':', 1)[1])
4598
5197
  else:
5198
+ self._pilha().clear()
5199
+ self.wizard = None
4599
5200
  self.avisar('cancelado', 'aviso')
4600
5201
  return
4601
5202
  if tipo in ('connect_api', 'oauth_hub'):
@@ -4631,33 +5232,40 @@ class Painel:
4631
5232
  itens_l = dados_l[0] if dados_l else []
4632
5233
  idx = int(escolha) - 1
4633
5234
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4634
- self.wizard = None
4635
5235
  if escolha == 'ag_login':
4636
5236
  self.iniciar_login_antigravity()
4637
5237
  elif escolha == 'ag_paste':
4638
- self.wizard = {'tipo': 'ag_callback', 'passo': 'colar',
4639
- 'titulo': 'Antigravity · Callback',
4640
- 'dados': {'url': self._ag_auth_url or ''}}
5238
+ self._empilhar_wizard({'tipo': 'ag_callback', 'passo': 'colar',
5239
+ 'titulo': 'Antigravity · Callback',
5240
+ 'dados': {'url': self._ag_auth_url or '', 'state': self._ag_auth_state}})
4641
5241
  elif escolha == 'ag_ativar':
5242
+ self._pilha().clear()
5243
+ self.wizard = None
4642
5244
  self.acao_trocar_provider('antigravity')
4643
5245
  elif escolha.startswith('ag_use:'):
5246
+ self._pilha().clear()
5247
+ self.wizard = None
4644
5248
  email = escolha.split(':', 1)[1]
4645
5249
  self.rodar_tarefa(lambda: self.tarefa_selecionar_conta_antigravity(email),
4646
5250
  f'conectando {email}…')
4647
5251
  elif escolha.startswith('ag_rm:'):
5252
+ self._pilha().clear()
5253
+ self.wizard = None
4648
5254
  email = escolha.split(':', 1)[1]
4649
5255
  self.rodar_tarefa(lambda: self.tarefa_remover_conta_antigravity(email),
4650
5256
  f'removendo {email}…')
4651
5257
  elif escolha == 'voltar_connect':
4652
- self.abrir_hub_connect()
5258
+ self._voltar_wizard()
4653
5259
  return
4654
5260
  if tipo == 'ag_callback':
4655
- self.wizard = None
4656
5261
  entrada = (texto or '').strip()
5262
+ state_atual = (w.get('dados') or {}).get('state') or self._ag_auth_state
5263
+ self._pilha().clear()
5264
+ self.wizard = None
4657
5265
  if not entrada:
4658
5266
  self.avisar('login fechado — se completou no navegador, a conta já está ativa', 'ok')
4659
5267
  return
4660
- self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada),
5268
+ self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada, state=state_atual),
4661
5269
  'concluindo OAuth do Antigravity…')
4662
5270
  return
4663
5271
  if tipo == 'wb_hub':
@@ -4747,18 +5355,43 @@ class Painel:
4747
5355
  f'adicionando {nome or "provedor"}…')
4748
5356
  return
4749
5357
  if tipo == 'model' and passo == 'menu':
5358
+ if texto == 'custom_id':
5359
+ self._empilhar_wizard({'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}})
5360
+ return
5361
+ if texto.startswith('pm:'):
5362
+ _, prov_alvo, mod_alvo = texto.split(':', 2)
5363
+ self._pilha().clear()
5364
+ self.wizard = None
5365
+ self.rodar_tarefa(
5366
+ lambda: self.tarefa_definir_modelo(mod_alvo, provedor_alvo=prov_alvo),
5367
+ f'trocando para {prov_alvo} · {mod_alvo}…',
5368
+ )
5369
+ return
5370
+ entradas = w.get('dados', {}).get('entradas') or []
4750
5371
  modelos = w.get('dados', {}).get('modelos') or []
4751
- if not texto.isdigit() or not 1 <= int(texto) <= len(modelos) + 1:
5372
+ total = len(entradas) if entradas else len(modelos)
5373
+ if not texto.isdigit() or not 1 <= int(texto) <= total + 1:
4752
5374
  self.avisar('escolha um modelo da lista ou informe outro ID', 'aviso')
4753
5375
  return
4754
5376
  indice = int(texto) - 1
4755
- if indice == len(modelos):
4756
- w['passo'] = 'id'
5377
+ if indice == total:
5378
+ self._empilhar_wizard({'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}})
5379
+ return
5380
+ if indice < len(entradas):
5381
+ ent = entradas[indice]
5382
+ self._pilha().clear()
5383
+ self.wizard = None
5384
+ self.rodar_tarefa(
5385
+ lambda: self.tarefa_definir_modelo(ent['id'], provedor_alvo=ent['provedor']),
5386
+ f"trocando para {ent['provedor']} · {ent['id']}…",
5387
+ )
4757
5388
  return
5389
+ self._pilha().clear()
4758
5390
  self.wizard = None
4759
5391
  self.abrir_wizard_modelo(modelos[indice])
4760
5392
  return
4761
5393
  if tipo == 'model' and passo == 'id':
5394
+ self._pilha().clear()
4762
5395
  self.wizard = None
4763
5396
  if texto.strip():
4764
5397
  self.abrir_wizard_modelo(texto)
@@ -5057,40 +5690,189 @@ class Painel:
5057
5690
  prefixo = 'provedor restaurado para' if restaurando else 'provedor ativo agora é'
5058
5691
  return ('ok', f'{prefixo} {nome}{extra}{nota}')
5059
5692
 
5693
+ def _catalogo_unificado_modelos(self, cfg: dict) -> tuple[list[dict], list[str]]:
5694
+ """Monta o catálogo unificado estilo OpenCode Select model (sem precisar de /provider).
5695
+
5696
+ Retorna `(grupos, modelos_do_provedor_ativo)`:
5697
+ - Quando o provedor ativo não é motor local, ele vem no topo (com seus modelos reais).
5698
+ - NVIDIA Playground (Free · sem conta): Kimi K3.1 Pro e MiniMax M3.1 Flash sempre visíveis!
5699
+ - Antigravity (Google OAuth): Gemini 4 Neon/Hydrogen e Claude Opus/Sonnet 5.5.
5700
+ - Demais provedores conectados (com chaves/contas salvas).
5701
+ """
5702
+ grupos: list[dict] = []
5703
+ vistos_prov: set[str] = set()
5704
+ modelos_ativo_lista: list[str] = []
5705
+ ativo = str(cfg.get('provider') or '')
5706
+
5707
+ # 0) Se o provedor ativo for externo/customizado, coloca o catálogo dele primeiro
5708
+ if ativo and ativo not in ('nvidia', 'kimi', 'antigravity'):
5709
+ try:
5710
+ if ativo == 'workbuddy':
5711
+ cat = catalogo_workbuddy(cfg)
5712
+ modelos_ativo_lista = [item['id'] for item in cat if item.get('id')]
5713
+ else:
5714
+ modelos_ativo_lista = consultar_modelos(cfg)
5715
+ except Exception:
5716
+ modelos_ativo_lista = []
5717
+ itens_ativo = [{'id': m, 'rotulo': m, 'detalhe': ''} for m in modelos_ativo_lista[:24]]
5718
+ if not itens_ativo:
5719
+ m_cur = modelo_ativo(cfg)
5720
+ if m_cur:
5721
+ itens_ativo = [{'id': m_cur, 'rotulo': m_cur, 'detalhe': ''}]
5722
+ if itens_ativo:
5723
+ preset = provedores_catalogo.PRESET_POR_SLUG.get(ativo)
5724
+ nome_sec = preset['nome'] if preset else ativo
5725
+ grupos.append({'provedor': ativo, 'secao': nome_sec, 'itens': itens_ativo})
5726
+ vistos_prov.add(ativo)
5727
+
5728
+ # 1) NVIDIA Playground (grátis, sem conta) — sempre visível!
5729
+ grupos.append({
5730
+ 'provedor': 'nvidia',
5731
+ 'secao': 'NVIDIA Playground (Free)',
5732
+ 'itens': [
5733
+ {'id': 'kimi-k3.1-pro', 'rotulo': 'Kimi K3.1 Pro', 'detalhe': 'Free'},
5734
+ {'id': 'minimax-m3.1-flash', 'rotulo': 'MiniMax M3.1 Flash', 'detalhe': 'Free'},
5735
+ ],
5736
+ })
5737
+ vistos_prov.update({'nvidia', 'kimi'})
5738
+ if ativo in ('nvidia', 'kimi'):
5739
+ modelos_ativo_lista = list(kimi.MODELOS_NVIDIA)
5740
+
5741
+ # 2) Antigravity (Google OAuth)
5742
+ snap = getattr(self, '_snap_visto', None) or self.coletor.ler() or {}
5743
+ ag_contas = ((snap.get('ag_status') or {}).get('accounts') or []) if isinstance(snap, dict) else []
5744
+ if ag_contas or ativo == 'antigravity':
5745
+ rotulos_ag = {
5746
+ 'gemini-4-neon': 'Gemini 4 Neon',
5747
+ 'gemini-4-hydrogen': 'Gemini 4 Hydrogen',
5748
+ 'claude-opus-5-5': 'Claude Opus 5.5',
5749
+ 'claude-sonnet-5-5': 'Claude Sonnet 5.5',
5750
+ }
5751
+ tag_ag = f'{len(ag_contas)}c' if ag_contas else 'OAuth'
5752
+ grupos.append({
5753
+ 'provedor': 'antigravity',
5754
+ 'secao': 'Antigravity (Google)',
5755
+ 'itens': [
5756
+ {'id': mid, 'rotulo': rotulos_ag.get(mid, mid), 'detalhe': tag_ag}
5757
+ for mid in kimi.MODELOS_ANTIGRAVITY
5758
+ ],
5759
+ })
5760
+ vistos_prov.add('antigravity')
5761
+ if ativo == 'antigravity':
5762
+ modelos_ativo_lista = list(kimi.MODELOS_ANTIGRAVITY)
5763
+
5764
+ # 3) Demais provedores conectados (com chave/conta salva)
5765
+ if 'unorouter' not in vistos_prov and self._tamanho_pool(cfg, 'unorouter'):
5766
+ grupos.append({
5767
+ 'provedor': 'unorouter',
5768
+ 'secao': 'UnoRouter',
5769
+ 'itens': [{'id': 'deepseek-v4.1-flash:free', 'rotulo': 'deepseek-v4.1-flash:free',
5770
+ 'detalhe': f'{self._tamanho_pool(cfg, "unorouter")}k'}],
5771
+ })
5772
+ vistos_prov.add('unorouter')
5773
+ if 'tokenharbor' not in vistos_prov and self._tamanho_pool(cfg, 'tokenharbor'):
5774
+ grupos.append({
5775
+ 'provedor': 'tokenharbor',
5776
+ 'secao': 'TokenHarbor',
5777
+ 'itens': [{'id': 'deepseek-v4.1-flash:free', 'rotulo': 'deepseek-v4.1-flash:free',
5778
+ 'detalhe': f'{self._tamanho_pool(cfg, "tokenharbor")}k'}],
5779
+ })
5780
+ vistos_prov.add('tokenharbor')
5781
+ if 'workbuddy' not in vistos_prov and self._contas_workbuddy():
5782
+ grupos.append({
5783
+ 'provedor': 'workbuddy',
5784
+ 'secao': 'WorkBuddy',
5785
+ 'itens': [{'id': workbuddy.MODELO_PADRAO, 'rotulo': workbuddy.MODELO_PADRAO,
5786
+ 'detalhe': f'{len(self._contas_workbuddy())}c'}],
5787
+ })
5788
+ vistos_prov.add('workbuddy')
5789
+ if 'opencode' not in vistos_prov:
5790
+ m_oc = str(cfg.get('opencode_model') or 'deepseek-v4.1-flash-free').strip()
5791
+ grupos.append({
5792
+ 'provedor': 'opencode',
5793
+ 'secao': 'OpenCode (Free)',
5794
+ 'itens': [{'id': m_oc, 'rotulo': m_oc, 'detalhe': 'Free'}],
5795
+ })
5796
+ vistos_prov.add('opencode')
5797
+ for nome_p, entrada in sorted((cfg.get('provedores') or {}).items()):
5798
+ if nome_p in vistos_prov or not isinstance(entrada, dict):
5799
+ continue
5800
+ if not (entrada.get('apis') or []):
5801
+ continue
5802
+ preset = provedores_catalogo.PRESET_POR_SLUG.get(nome_p)
5803
+ nome_sec = preset['nome'] if preset else nome_p
5804
+ modelo_p = str(entrada.get('model') or (preset['modelo_padrao'] if preset else '') or '').strip()
5805
+ if not modelo_p:
5806
+ continue
5807
+ grupos.append({
5808
+ 'provedor': nome_p,
5809
+ 'secao': nome_sec,
5810
+ 'itens': [{'id': modelo_p, 'rotulo': modelo_p, 'detalhe': f"{len(entrada.get('apis') or [])}k"}],
5811
+ })
5812
+ return grupos, modelos_ativo_lista
5813
+
5060
5814
  def tarefa_listar_modelos(self):
5061
5815
  cfg = ler_config()
5062
- info = {}
5063
- try:
5064
- if (cfg.get('provider') or '') == 'workbuddy':
5065
- catalogo = catalogo_workbuddy(cfg)
5066
- modelos = [item['id'] for item in catalogo if item.get('id')]
5067
- info = {item['id']: item for item in catalogo if item.get('id')}
5068
- else:
5069
- modelos = consultar_modelos(cfg)
5070
- except ValueError as exc:
5071
- self.wizard = {'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}}
5072
- return ('aviso', f'{exc} · você ainda pode informar o ID manualmente')
5073
- limites = workbuddy.ler_limites(ROOT) if (cfg.get('provider') or '') == 'workbuddy' else {}
5074
- self.wizard = {'tipo': 'model', 'passo': 'menu', 'titulo': 'Modelos do provedor',
5075
- 'dados': {'modelos': modelos, 'info': info, 'limites': limites}}
5076
- return ('ok', f'{len(modelos)} modelo(s) de {cfg.get("provider") or "unorouter"} · escolha na lista')
5077
-
5078
- def tarefa_definir_modelo(self, nome: str):
5816
+ grupos, modelos_ativo_lista = self._catalogo_unificado_modelos(cfg)
5817
+ entradas = []
5818
+ for g in grupos:
5819
+ for it in g['itens']:
5820
+ entradas.append({
5821
+ 'provedor': g['provedor'],
5822
+ 'secao': g['secao'],
5823
+ 'id': it['id'],
5824
+ 'rotulo': it['rotulo'],
5825
+ 'detalhe': it.get('detalhe') or '',
5826
+ })
5827
+ modelos_flat = modelos_ativo_lista or [e['id'] for e in entradas]
5828
+ self.wizard = {
5829
+ 'tipo': 'model',
5830
+ 'passo': 'menu',
5831
+ 'titulo': 'Select model',
5832
+ 'dados': {'modelos': modelos_flat, 'entradas': entradas, 'info': {}, 'limites': {}},
5833
+ }
5834
+ return ('ok', f'{len(entradas)} modelo(s) disponíveis · escolha na lista')
5835
+
5836
+ def tarefa_definir_modelo(self, nome: str, provedor_alvo: str | None = None):
5079
5837
  nome = (nome or '').strip()
5080
5838
  if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/+-]{0,199}', nome):
5081
5839
  raise ValueError('informe o ID do modelo, sem espacos: /model ID')
5082
5840
  cfg = ler_config()
5841
+ prov_anterior = str(cfg.get('provider') or '')
5842
+ prov_destino = (provedor_alvo or prov_anterior or 'nvidia').strip().lower()
5843
+ # Compatibilidade: kimi legado e nvidia apontam para o mesmo motor local
5844
+ if prov_destino == 'nvidia' and prov_anterior == 'kimi':
5845
+ prov_destino = 'nvidia'
5083
5846
  atual = modelo_ativo(cfg)
5084
- if nome == atual:
5847
+ if nome == atual and prov_destino == prov_anterior:
5085
5848
  return ('aviso', f'o modelo ativo já é {nome}')
5086
5849
  cfg_anterior = copy.deepcopy(cfg)
5850
+ # Se mudou de provedor junto com o modelo (estilo OpenCode /models), garante bloco do motor
5851
+ if prov_destino != prov_anterior:
5852
+ if prov_destino in ('nvidia', 'kimi', 'antigravity'):
5853
+ provs = cfg.setdefault('provedores', {})
5854
+ base_padrao = f'http://127.0.0.1:{kimi.PORTA_PADRAO}/v1'
5855
+ if prov_destino not in provs or not isinstance(provs.get(prov_destino), dict):
5856
+ provs[prov_destino] = {
5857
+ 'base_url': base_padrao,
5858
+ 'model': nome,
5859
+ 'apis': [{'name': f'{prov_destino}-local', 'key_env': ''}],
5860
+ }
5861
+ else:
5862
+ provs[prov_destino]['model'] = nome
5863
+ cfg['provider'] = prov_destino
5087
5864
  if cfg.get('provider') == 'opencode':
5088
5865
  cfg['opencode_model'] = nome
5089
5866
  cfg['model_enviado'] = ''
5090
5867
  else:
5091
5868
  cfg['upstream_model'] = nome
5092
5869
  cfg['model_enviado'] = nome
5093
- # Valida se o nível de raciocínio atual existe no novo modelo
5870
+ if cfg.get('provider') in ('nvidia', 'kimi', 'antigravity'):
5871
+ provs = cfg.setdefault('provedores', {})
5872
+ if isinstance(provs.get(cfg['provider']), dict):
5873
+ provs[cfg['provider']]['model'] = nome
5874
+ # Ajusta automaticamente o esforço para o teto aceito pelo modelo novo se
5875
+ # o esforço anterior não existir nesse modelo (evita travar troca de modelo).
5094
5876
  aviso_esforco = ''
5095
5877
  prov = str(cfg.get('provider') or '')
5096
5878
  if prov in ('kimi', 'nvidia', 'antigravity'):
@@ -5101,15 +5883,15 @@ class Painel:
5101
5883
  or 'max'
5102
5884
  ).strip().lower()
5103
5885
  if esforco_atual not in aceitos:
5104
- raise ValueError(
5105
- f'{nome} não suporta "{esforco_atual}" — aceita {", ".join(aceitos)} (use /effort {aceitos[-1]} antes)'
5106
- )
5886
+ novo_eff = aceitos[-1]
5887
+ cfg.setdefault('esforco_modelos', {}).setdefault(prov, {})[nome] = novo_eff
5888
+ aviso_esforco = f' · effort {novo_eff}'
5107
5889
  gravar_config_com_contexto(cfg)
5108
5890
  if self.bridge_online():
5109
5891
  extra = self._reiniciar_bridge_seguro(cfg_anterior)
5110
5892
  else:
5111
5893
  extra = ' · vale na próxima partida do bridge'
5112
- return ('ok', f'modelo ativo agora é {nome}{extra}{aviso_esforco}')
5894
+ return ('ok', f'{prov} · {nome}{aviso_esforco}{extra}')
5113
5895
 
5114
5896
  def tarefa_definir_contexto(self, tamanho: str, esperado=None):
5115
5897
  tokens = contexto.parse_contexto(tamanho)
@@ -5240,21 +6022,28 @@ class Painel:
5240
6022
  raise ValueError('o bridge já está no ar')
5241
6023
  BRIDGE_LOG.parent.mkdir(exist_ok=True)
5242
6024
  log = open(BRIDGE_LOG, 'ab')
5243
- flags = 0x08000000 if os.name == 'nt' else 0 # CREATE_NO_WINDOW
6025
+ # Processo destacado (cross-platform: Windows DETACHED/NEW_PROCESS_GROUP,
6026
+ # Linux/Ubuntu/Termux start_new_session) para que Ctrl+C na TUI deixe o
6027
+ # bridge vivo em background e somente /exit ou /stop encerre o servidor.
6028
+ opcoes: dict = {}
6029
+ if os.name == 'nt':
6030
+ opcoes['creationflags'] = (
6031
+ getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
6032
+ | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0x00000200)
6033
+ | getattr(subprocess, 'DETACHED_PROCESS', 0x00000008)
6034
+ )
6035
+ else:
6036
+ opcoes['start_new_session'] = True
5244
6037
  self._soltar_job()
5245
6038
  try:
5246
6039
  self.proc = subprocess.Popen(
5247
6040
  [sys.executable, '-B', str(ROOT / 'bridge.py'), '--config', 'config.json'],
5248
- cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT, creationflags=flags)
6041
+ cwd=str(ROOT), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, **opcoes)
5249
6042
  finally:
5250
6043
  try:
5251
6044
  log.close()
5252
6045
  except OSError:
5253
6046
  pass
5254
- # o bridge vive junto com o painel: X no console, /sair ou queda o encerram
5255
- self._job_bridge = prender_processo_ao_painel(self.proc.pid)
5256
- if os.name == 'nt' and not self._job_bridge:
5257
- self._instalar_guarda_ctrl()
5258
6047
  for _ in range(60):
5259
6048
  time.sleep(0.2)
5260
6049
  if self._bridge_online_direto():