krnell 3.0.3 → 3.0.5

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
@@ -350,6 +350,17 @@ def consultar_modelos_opencode() -> list[str]:
350
350
  from bridge import sanitize_diagnostic
351
351
 
352
352
  executavel = shutil.which('opencode')
353
+ if not executavel:
354
+ nome = 'opencode.exe' if os.name == 'nt' else 'opencode'
355
+ for cand in (
356
+ Path.home() / '.opencode' / 'bin' / nome,
357
+ Path.home() / '.local' / 'bin' / nome,
358
+ Path.home() / '.bun' / 'bin' / nome,
359
+ Path(os.environ.get('PREFIX', '')) / 'bin' / nome if os.environ.get('PREFIX') else None,
360
+ ):
361
+ if cand and cand.is_file():
362
+ executavel = str(cand)
363
+ break
353
364
  if not executavel:
354
365
  raise ValueError('OpenCode nao encontrado no PATH; instale-o ou informe /model ID manualmente')
355
366
  try:
@@ -1134,6 +1145,8 @@ class Painel:
1134
1145
  self._wizard_item_linhas = {} # linha do wizard -> indice do item
1135
1146
  self._modal_ini = None # linha do frame do 1o item do modal (clique copia)
1136
1147
  self._reqs_visiveis = 10 # quantas requisicoes cabem na janela (roda do mouse)
1148
+ self._wizard_pilha: list[dict] = [] # pilha para Esc voltar 1 nível em vez de cancelar tudo
1149
+ self._esc_zona = None # colunas do botão `esc back` do rodapé (toque/clique)
1137
1150
  self._copiar_zona = None # colunas do botao copiar do rodape (clique)
1138
1151
  self._copiar_hover = False # mouse em cima do botao copiar
1139
1152
  self._status_y = None # linha (0-based) da barra de status
@@ -1149,8 +1162,11 @@ class Painel:
1149
1162
  self._term_posix = None # tui_core.TerminalPosix no Termux/Linux/macOS
1150
1163
  self._overlay_top = None
1151
1164
  self._overlay_left = None
1165
+ self._overlay_width = 0
1166
+ self._overlay_height = 0
1152
1167
  self._overlay_clique = {} # y_relativo -> indice do item no overlay centrado
1153
1168
  self._ag_auth_url = None
1169
+ self._ag_auth_state = ''
1154
1170
  self._anim_tick = 0
1155
1171
  self._anim_ultimo = 0.0
1156
1172
  self._dialogo_frame = 0 # animacao de abertura do dialogo
@@ -1256,29 +1272,32 @@ class Painel:
1256
1272
  # Uma linha de marca, uma de respiro. O update é um pill persistente e
1257
1273
  # opcional, no mesmo lugar em todas as telas, como na TUI do OpenCode.
1258
1274
  cab = Table.grid(expand=True)
1259
- cab.add_column(ratio=1)
1260
- cab.add_column(justify='right')
1275
+ cab.add_column(ratio=1, no_wrap=True)
1276
+ cab.add_column(justify='right', no_wrap=True)
1261
1277
  titulo = Text()
1262
1278
  glifo = _GLIFO_MARCA[tick % len(_GLIFO_MARCA)] if online else '◇'
1263
1279
  titulo.append(f'{glifo} ', style=f'bold {ACENTO}')
1264
1280
  titulo.append('krnell', style=f'bold {TEXTO}')
1265
- titulo.append(f' v{versao_local()}', style=FRACO)
1281
+ if largura >= 34:
1282
+ titulo.append(f' v{versao_local()}' if largura < 48 else f' v{versao_local()}', style=FRACO)
1266
1283
  estado = Text()
1267
1284
  disponivel = self.atualizacoes.disponivel
1268
1285
  rotulo_update = ''
1269
1286
  self._update_zona = None
1270
1287
  if disponivel:
1271
- rotulo_update = f" ↑ update {disponivel['version']} "
1288
+ rotulo_update = (f" ↑{disponivel['version']} " if largura < 52
1289
+ else f" ↑ update {disponivel['version']} ")
1272
1290
  cor_update = ACENTO3 if self._update_hover else ACENTO
1273
1291
  estado.append(rotulo_update, style=f'bold {cor_update} on {FUNDO}')
1274
- estado.append(' ')
1292
+ estado.append(' ' if largura < 52 else ' ')
1275
1293
  if online:
1276
1294
  if (status.get('live') or {}).get('ativas'):
1277
- estado.append(f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working', style=ACENTO2)
1295
+ rot_on = f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} live' if largura < 54 else f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working'
1296
+ estado.append(rot_on, style=ACENTO2)
1278
1297
  else:
1279
- estado.append('● online', style=OK)
1298
+ estado.append('● on' if largura < 40 else '● online', style=OK)
1280
1299
  else:
1281
- estado.append('○ offline', style=ERRO)
1300
+ estado.append('○ off' if largura < 40 else '○ offline', style=ERRO)
1282
1301
  if rotulo_update:
1283
1302
  inicio = max(0, largura - cell_len(estado.plain))
1284
1303
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
@@ -1294,6 +1313,7 @@ class Painel:
1294
1313
  info_compacta = info_compacta[:1]
1295
1314
  linhas_req = max(2, min(espaco_corpo - len(info_compacta), 48))
1296
1315
  estreito = largura < 74
1316
+ ultra_estreito = largura < 46
1297
1317
 
1298
1318
  reqs = snap.get('requests') or []
1299
1319
  visiveis = max(1, linhas_req - 1)
@@ -1313,16 +1333,17 @@ class Painel:
1313
1333
 
1314
1334
  tabela = Table(box=None, expand=True, padding=(0, 1), show_edge=False,
1315
1335
  show_header=False, pad_edge=False)
1316
- tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1317
- tabela.add_column(width=5, no_wrap=True)
1336
+ if not ultra_estreito:
1337
+ tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1338
+ tabela.add_column(width=6, no_wrap=True)
1318
1339
  tabela.add_column(ratio=1, no_wrap=True, overflow='ellipsis')
1319
- tabela.add_column(width=6, justify='right', no_wrap=True)
1340
+ tabela.add_column(width=6 if ultra_estreito else 7, justify='right', no_wrap=True)
1320
1341
  if not estreito:
1321
1342
  tabela.add_column(width=9, justify='right', no_wrap=True)
1322
1343
  tabela.add_column(width=14, no_wrap=True, overflow='ellipsis')
1323
1344
 
1324
1345
  def linha_req(hora, codigo, conta, duracao, tokens='', obs=''):
1325
- valores = [hora, codigo, conta, duracao]
1346
+ valores = [codigo, conta, duracao] if ultra_estreito else [hora, codigo, conta, duracao]
1326
1347
  if not estreito:
1327
1348
  valores.extend([tokens, obs])
1328
1349
  tabela.add_row(*valores)
@@ -1376,7 +1397,20 @@ class Painel:
1376
1397
  else:
1377
1398
  renderaveis.extend(info_compacta)
1378
1399
  renderaveis.append(atividade)
1379
- renderaveis.extend(menu_render)
1400
+ if menu_render:
1401
+ # Mantém o popup "/" sempre colado logo acima da caixa de entrada
1402
+ # (em celular com tela alta ou baixa com teclado aberto).
1403
+ renderaveis_base = self._linhas(renderaveis, largura)
1404
+ linhas_menu = self._linhas(menu_render, largura)
1405
+ limite_frame = max(2, altura - 4)
1406
+ espaco_topo = max(2, limite_frame - len(linhas_menu))
1407
+ topo_pad = list(renderaveis_base[:espaco_topo])
1408
+ while len(topo_pad) < espaco_topo:
1409
+ topo_pad.append('')
1410
+ self._frame_menu_pronto = topo_pad + linhas_menu
1411
+ renderaveis.extend(menu_render)
1412
+ else:
1413
+ self._frame_menu_pronto = None
1380
1414
  renderaveis.extend(modais_render)
1381
1415
  return renderaveis
1382
1416
 
@@ -1416,17 +1450,24 @@ class Painel:
1416
1450
 
1417
1451
  def _info_compacta(self, snap, online, status, cfg, provedor) -> list:
1418
1452
  """Duas linhas no máximo em telas estreitas; o resto mora em /status e /quota."""
1419
- modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(12, self.largura - 24))
1420
- primeira = Text()
1421
- primeira.append(provedor, style=f'bold {ACENTO}')
1453
+ # Nunca duplica `model_enviado` quando estiver no provedor `kimi` legado com modelo Antigravity
1454
+ if cfg.get('provider') == 'kimi' and modelo_ativo(cfg) in kimi.MODELOS_ANTIGRAVITY:
1455
+ provedor_exib = 'antigravity'
1456
+ else:
1457
+ provedor_exib = provedor
1458
+ modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(8, self.largura - len(provedor_exib) - 14))
1459
+ primeira = Text(no_wrap=True, overflow='ellipsis')
1460
+ primeira.append(provedor_exib, style=f'bold {ACENTO}')
1422
1461
  primeira.append(f' {modelo}', style=TEXTO)
1423
- primeira.append(f' · {variante_ativa(cfg, provedor)}', style=FRACO)
1424
- segunda = Text()
1462
+ var = variante_ativa(cfg, provedor)
1463
+ if cell_len(primeira.plain) + len(var) + 5 <= self.largura:
1464
+ primeira.append(f' · {var}', style=FRACO)
1465
+ segunda = Text(no_wrap=True, overflow='ellipsis')
1425
1466
  ag_status = snap.get('ag_status') if isinstance(snap.get('ag_status'), dict) else {}
1426
1467
  resumo = _resumo_cota_antigravity(ag_status)
1427
1468
  for idx, item in enumerate(resumo[:2]):
1428
1469
  if idx:
1429
- segunda.append(' · ', style=BORDA)
1470
+ segunda.append(' · ' if self.largura < 50 else ' · ', style=BORDA)
1430
1471
  segunda.append(item['nome'][0], style=FRACO)
1431
1472
  for bucket, prefixo in ((item.get('b5h'), '5h'), (item.get('bsem'), '7d')):
1432
1473
  texto, cor = _fmt_bucket_curto(bucket, prefixo, com_reset=False)
@@ -1464,7 +1505,9 @@ class Painel:
1464
1505
  if self.modal or self.wizard:
1465
1506
  direita = [(' esc back ', 'fraco', None, 'ess'), botao]
1466
1507
  else:
1467
- direita = [(' ctrl+p commands · ctrl+l connect ', 'fraco', None, 'extra'), botao]
1508
+ direita = [(' commands ', 'fraco', None, 'extra'),
1509
+ (' connect ', 'acento2', None, 'nor'),
1510
+ botao]
1468
1511
  return esquerda, direita
1469
1512
 
1470
1513
  def _barra_status(self) -> str:
@@ -1493,11 +1536,31 @@ class Painel:
1493
1536
  acumulado += w
1494
1537
  espaco = max(1, self.largura - acumulado - larg_dir)
1495
1538
  self._copiar_zona = None
1539
+ self._esc_zona = None
1540
+ self._status_acoes: list[tuple[int, int, str]] = [] # (x_ini, x_fim, acao)
1541
+ # Registra áreas tocáveis na esquerda da barra (provedor/modelo -> /model, esforço -> /effort)
1542
+ if not self.tarefa_ativa and not (self.msg and time.time() <= self.msg_ate):
1543
+ x_cur = 0
1544
+ for idx_seg, (txt_seg, _) in enumerate(cortados):
1545
+ w_seg = cell_len(txt_seg)
1546
+ if w_seg > 0:
1547
+ acao_esq = 'effort' if idx_seg == 2 else 'model'
1548
+ self._status_acoes.append((x_cur, x_cur + w_seg - 1, acao_esq))
1549
+ x_cur += w_seg
1496
1550
  if dr:
1497
- larg_btn = cell_len(dr[-1][0])
1498
- inicio = self.largura - larg_btn
1499
- if inicio >= 1:
1500
- self._copiar_zona = (inicio, self.largura - 1)
1551
+ pos_fim = self.largura
1552
+ for seg in reversed(dr):
1553
+ larg_seg = cell_len(seg[0])
1554
+ inicio = pos_fim - larg_seg
1555
+ if 'copy' in seg[0] and inicio >= 1:
1556
+ self._copiar_zona = (inicio, pos_fim - 1)
1557
+ elif 'esc' in seg[0] and inicio >= 1:
1558
+ self._esc_zona = (inicio, pos_fim - 1)
1559
+ elif 'commands' in seg[0] and inicio >= 1:
1560
+ self._status_acoes.append((inicio, pos_fim - 1, 'palette'))
1561
+ elif 'connect' in seg[0] and inicio >= 1:
1562
+ self._status_acoes.append((inicio, pos_fim - 1, 'connect'))
1563
+ pos_fim = inicio
1501
1564
  return pintar_segmentos(cortados) + ' ' * espaco + pintar_segmentos(dr)
1502
1565
 
1503
1566
  def _texto_status_rich(self, snap=None) -> Text:
@@ -1567,7 +1630,7 @@ class Painel:
1567
1630
 
1568
1631
  def _limite_menu(self) -> int:
1569
1632
  """Quantos itens do menu cabem sem apertar o resto do painel."""
1570
- return max(3, min(10, self.altura - 16))
1633
+ return max(3, min(10, self.altura - 10))
1571
1634
 
1572
1635
  def _sel_menu(self) -> int:
1573
1636
  """Indice do item destacado, ja preso a lista atual de candidatos."""
@@ -1623,7 +1686,7 @@ class Painel:
1623
1686
  fundo elevado e barra de destaque no item escolhido."""
1624
1687
  if not self._menu_aberto():
1625
1688
  return []
1626
- interno = max(8, self.largura - 4) # o vao entre os trilhos ┃
1689
+ interno = max(14, self.largura - 4) # o vao entre os trilhos ┃
1627
1690
 
1628
1691
  def com_trilhos(miolo: Text) -> Text:
1629
1692
  t = Text()
@@ -1634,25 +1697,30 @@ class Painel:
1634
1697
 
1635
1698
  candidatos = self._candidatos_menu()
1636
1699
  if not candidatos:
1637
- return [com_trilhos(Text(' ' + 'nenhum comando corresponde'.ljust(interno - 1),
1638
- style=f'{FRACO} on {FUNDO}'))]
1700
+ msg_vazio = tui_core.pad_vis(' nenhum comando corresponde', interno)
1701
+ return [com_trilhos(Text(msg_vazio, style=f'{FRACO} on {FUNDO}'))]
1639
1702
  inicio, visiveis = self._janela_menu()
1640
1703
  destaque = self._sel_menu() - inicio
1641
- coluna = min(max(len(comando) for comando, _ in MENU_COMANDOS) + 2, interno - 3)
1704
+ coluna = min(max(len(comando) for comando, _ in MENU_COMANDOS) + 2, max(8, interno - 4))
1642
1705
  linhas = []
1643
1706
  for posicao, (comando, descricao) in enumerate(visiveis):
1644
- descricao = descricao[:max(0, interno - 2 - coluna)]
1645
- nome = f'{comando:<{coluna}}'
1646
- miolo = f' {nome}{descricao}'
1707
+ max_desc = max(0, interno - 2 - coluna)
1708
+ desc_vis = tui_core.truncate_vis(descricao, max_desc) if max_desc >= 4 else ''
1709
+ nome = tui_core.pad_vis(comando, coluna)
1710
+ miolo = f' {nome}{desc_vis}'
1711
+ miolo_fixo = tui_core.pad_vis(miolo, interno)
1647
1712
  t = Text()
1648
1713
  if posicao == destaque:
1649
1714
  # o item que o Enter/Tab executa ou o clique escolhe
1650
- t.append(miolo.ljust(interno), style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1715
+ t.append(miolo_fixo, style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1651
1716
  else:
1652
1717
  t.append(' ', style=f'on {FUNDO}')
1653
1718
  t.append(nome, style=f'{TEXTO} on {FUNDO}')
1654
- t.append(descricao, style=f'{FRACO} on {FUNDO}')
1655
- t.append(' ' * (interno - len(miolo)), style=f'on {FUNDO}')
1719
+ if desc_vis:
1720
+ t.append(desc_vis, style=f'{FRACO} on {FUNDO}')
1721
+ falta = max(0, interno - 1 - cell_len(nome) - cell_len(desc_vis))
1722
+ if falta:
1723
+ t.append(' ' * falta, style=f'on {FUNDO}')
1656
1724
  linhas.append(com_trilhos(t))
1657
1725
  acima = inicio
1658
1726
  abaixo = len(candidatos) - (inicio + len(visiveis))
@@ -1662,10 +1730,8 @@ class Painel:
1662
1730
  pedacos.append(f'+{acima} acima')
1663
1731
  if abaixo:
1664
1732
  pedacos.append(f'+{abaixo} abaixo')
1665
- texto = f"… {' · '.join(pedacos)} — ↑↓ e roda rolam · digite para filtrar"
1666
- texto = texto[:interno - 2]
1667
- linhas.append(com_trilhos(Text(' ' + texto.ljust(interno - 1),
1668
- style=f'{FRACO} on {FUNDO}')))
1733
+ texto = tui_core.pad_vis(f" … {' · '.join(pedacos)}", interno)
1734
+ linhas.append(com_trilhos(Text(texto, style=f'{FRACO} on {FUNDO}')))
1669
1735
  return linhas
1670
1736
 
1671
1737
  def _registrar_menu(self, frame: list, cortado: bool = False) -> None:
@@ -1676,7 +1742,7 @@ class Painel:
1676
1742
  self._menu_ini = None
1677
1743
  return
1678
1744
  altura_menu = len(self._linhas(itens, self.largura))
1679
- base = min(len(frame), max(3, self.altura - 4))
1745
+ base = min(len(frame), max(2, self.altura - 4))
1680
1746
  inicio = base - altura_menu
1681
1747
  self._menu_ini = inicio if inicio >= 0 else None
1682
1748
 
@@ -1692,14 +1758,23 @@ class Painel:
1692
1758
  return None
1693
1759
 
1694
1760
  def clicar_menu(self, y: int) -> bool:
1695
- """Clique no menu: roda o comando daquela linha."""
1696
- indice = self.indice_menu_no_clique(y)
1697
- if indice is None:
1761
+ """Clique/toque no menu '/': roda o comando ou rola se tocou na linha de paginação."""
1762
+ candidatos = self._candidatos_menu()
1763
+ if not candidatos or self._menu_ini is None:
1698
1764
  return False
1699
- self.buf = self._candidatos_menu()[indice][0]
1700
- self.menu_sel = indice
1701
- self.ao_enter()
1702
- return True
1765
+ posicao = y - self._menu_ini
1766
+ inicio, visiveis = self._janela_menu()
1767
+ if 0 <= posicao < len(visiveis):
1768
+ indice = inicio + posicao
1769
+ self.buf = candidatos[indice][0]
1770
+ self.menu_sel = indice
1771
+ self.ao_enter()
1772
+ return True
1773
+ # Linha de paginação ("… +2 abaixo") logo abaixo dos itens visíveis: tocar nela rola!
1774
+ if posicao == len(visiveis) and len(candidatos) > len(visiveis):
1775
+ abaixo = len(candidatos) - (inicio + len(visiveis))
1776
+ return self.roda_mouse(1 if abaixo > 0 else -1)
1777
+ return False
1703
1778
 
1704
1779
  def roda_mouse(self, sentido: int) -> bool:
1705
1780
  """Roda: rola a janela do menu e a selecao se reajusta (como no OpenCode);
@@ -1714,24 +1789,43 @@ class Painel:
1714
1789
  if candidatos:
1715
1790
  limite = self._limite_menu()
1716
1791
  maximo = max(0, len(candidatos) - limite)
1717
- self.menu_topo = max(0, min(maximo, self.menu_topo + sentido * 3))
1718
- primeiro = self.menu_topo
1719
- ultimo = min(len(candidatos) - 1, primeiro + limite - 1)
1720
- self.menu_sel = max(primeiro, min(ultimo, self._sel_menu()))
1792
+ passo = 1 if tui_core.is_termux() else 3
1793
+ delta = sentido * passo
1794
+ if maximo > 0:
1795
+ novo_topo = max(0, min(maximo, self.menu_topo + delta))
1796
+ if novo_topo != self.menu_topo:
1797
+ self.menu_topo = novo_topo
1798
+ primeiro = self.menu_topo
1799
+ ultimo = min(len(candidatos) - 1, primeiro + limite - 1)
1800
+ self.menu_sel = max(primeiro, min(ultimo, self._sel_menu() + delta))
1801
+ else:
1802
+ self.menu_sel = max(0, min(len(candidatos) - 1, self._sel_menu() + delta))
1803
+ else:
1804
+ self.menu_sel = max(0, min(len(candidatos) - 1, self._sel_menu() + delta))
1721
1805
  return True
1722
1806
  if self.wizard and self._wizard_lista():
1723
1807
  itens = self._itens_wizard_filtrados()
1724
- limite = self._limite_wizard()
1725
- maximo = max(0, len(itens) - limite)
1726
- topo = max(0, min(maximo, self.wizard.get('topo', 0) + sentido * 3))
1727
- self.wizard['topo'] = topo
1728
- # o destaque acompanha a janela: nunca fica escondido nem "pula" sozinho
1729
- self.wizard['sel'] = max(topo, min(topo + limite - 1, self._sel_wizard()))
1808
+ if itens:
1809
+ limite = self._limite_wizard()
1810
+ maximo = max(0, len(itens) - limite)
1811
+ passo = 1 if tui_core.is_termux() else 3
1812
+ delta = sentido * passo
1813
+ topo_atual = self.wizard.get('topo', 0)
1814
+ if maximo > 0:
1815
+ novo_topo = max(0, min(maximo, topo_atual + delta))
1816
+ self.wizard['topo'] = novo_topo
1817
+ if novo_topo != topo_atual:
1818
+ self.wizard['sel'] = max(novo_topo, min(novo_topo + limite - 1, self._sel_wizard() + delta))
1819
+ else:
1820
+ self.wizard['sel'] = max(0, min(len(itens) - 1, self._sel_wizard() + delta))
1821
+ else:
1822
+ self.wizard['sel'] = max(0, min(len(itens) - 1, self._sel_wizard() + delta))
1730
1823
  return True
1731
1824
  snap = self.coletor.ler()
1732
1825
  reqs = snap.get('requests') or []
1733
1826
  visiveis = max(1, getattr(self, '_reqs_visiveis', 10))
1734
- self.scroll = max(0, min(self.scroll + sentido * 3, max(0, len(reqs) - visiveis)))
1827
+ passo = 1 if tui_core.is_termux() else 3
1828
+ self.scroll = max(0, min(self.scroll + sentido * passo, max(0, len(reqs) - visiveis)))
1735
1829
  return True
1736
1830
 
1737
1831
  def completar_menu(self) -> bool:
@@ -1792,18 +1886,18 @@ class Painel:
1792
1886
  n_un = self._tamanho_pool(cfg, 'unorouter')
1793
1887
  n_th = self._tamanho_pool(cfg, 'tokenharbor')
1794
1888
  itens = [
1795
- ('Antigravity', 'ag_hub', f'{len(ag_contas)}c' if ag_contas else 'OAuth'),
1796
- ('NVIDIA', 'nv_ativar', 'Free'),
1889
+ ('NVIDIA Playground', 'nv_ativar', 'Free · sem conta'),
1890
+ ('OpenCode', 'oc_ativar', 'Free · sem conta'),
1891
+ ('Antigravity', 'ag_hub', f'{len(ag_contas)}c · OAuth' if ag_contas else 'Google OAuth'),
1797
1892
  ('WorkBuddy', 'wb_hub', f'{n_wb}c' if n_wb else 'Login'),
1798
- ('OpenCode', 'oc_ativar', 'Free'),
1799
1893
  ('ChatGPT / Copilot / xAI', 'oauth_hub', 'OAuth'),
1800
- ('UnoRouter', 'key:unorouter', f'{n_un}k' if n_un else 'API'),
1801
- ('TokenHarbor', 'key:tokenharbor', f'{n_th}k' if n_th else 'API'),
1894
+ ('UnoRouter', 'key:unorouter', f'{n_un}k' if n_un else 'API key'),
1895
+ ('TokenHarbor', 'key:tokenharbor', f'{n_th}k' if n_th else 'API key'),
1802
1896
  ]
1803
1897
  for preset in provedores_catalogo.PROVEDORES_API_PRESETS:
1804
1898
  slug = preset['slug']
1805
1899
  n_c = self._tamanho_pool(cfg, slug)
1806
- det = f'{n_c}k' if n_c else ('Local' if slug == 'ollama' else '')
1900
+ det = f'{n_c}k' if n_c else ('Local' if slug == 'ollama' else 'API key')
1807
1901
  itens.append((preset['nome'], f'preset:{slug}', det))
1808
1902
  slugs_padrao = {'workbuddy', 'kimi', 'nvidia', 'antigravity'} | set(provedores_catalogo.PRESET_POR_SLUG)
1809
1903
  for nome_p in sorted((cfg.get('provedores') or {}).keys()):
@@ -1811,14 +1905,14 @@ class Painel:
1811
1905
  continue
1812
1906
  n_c = self._tamanho_pool(cfg, nome_p)
1813
1907
  itens.append((nome_p, f'prov:{nome_p}', f'{n_c}k' if n_c else ''))
1814
- itens.append(('Sync OpenCode', 'sync_opencode', ''))
1815
- itens.append(('+ Custom provider', 'custom_add', ''))
1908
+ itens.append(('Sync OpenCode', 'sync_opencode', 'models + plugin'))
1909
+ itens.append(('+ Custom provider', 'custom_add', 'base URL + key'))
1816
1910
  mapa_atual = {
1817
- 'antigravity': 'ag_hub',
1818
1911
  'nvidia': 'nv_ativar',
1819
1912
  'kimi': 'nv_ativar',
1820
- 'workbuddy': 'wb_hub',
1913
+ 'antigravity': 'ag_hub',
1821
1914
  'opencode': 'oc_ativar',
1915
+ 'workbuddy': 'wb_hub',
1822
1916
  'unorouter': 'key:unorouter',
1823
1917
  'tokenharbor': 'key:tokenharbor',
1824
1918
  }
@@ -1889,6 +1983,23 @@ class Painel:
1889
1983
  return itens, 0
1890
1984
  if tipo == 'model':
1891
1985
  dados = w.get('dados', {})
1986
+ entradas = dados.get('entradas') or []
1987
+ atual = modelo_ativo(cfg)
1988
+ prov_atual = str(cfg.get('provider') or '')
1989
+ if prov_atual == 'kimi':
1990
+ prov_atual = 'nvidia'
1991
+ if entradas:
1992
+ itens = []
1993
+ indice = None
1994
+ for i, ent in enumerate(entradas):
1995
+ chave = f"pm:{ent['provedor']}:{ent['id']}"
1996
+ itens.append((ent['rotulo'], chave, ent.get('detalhe') or ''))
1997
+ if indice is None and ent['id'] == atual and ent['provedor'] == prov_atual:
1998
+ indice = i
1999
+ if indice is None:
2000
+ indice = next((i for i, ent in enumerate(entradas) if ent['id'] == atual), 0)
2001
+ itens.append(('informar outro ID…', 'custom_id', '/model ID'))
2002
+ return itens, indice
1892
2003
  modelos = dados.get('modelos') or []
1893
2004
  info = dados.get('info') or {}
1894
2005
  total_contas = len(workbuddy.ler_contas(ROOT)) or 0
@@ -1912,7 +2023,6 @@ class Painel:
1912
2023
  partes.append(marca + (f' (~{horas:.0f}h)' if horas else ''))
1913
2024
  itens.append((modelo, str(i), ' · '.join(partes)))
1914
2025
  itens.append(('informar outro ID…', str(len(modelos) + 1), '/model ID'))
1915
- atual = modelo_ativo(cfg)
1916
2026
  indice = indice_modelo_ativo(modelos, atual)
1917
2027
  return itens, indice
1918
2028
  if tipo == 'esforco':
@@ -2033,7 +2143,9 @@ class Painel:
2033
2143
  Usa o mapa gravado no desenho (_wizard_item_linhas): assim cabecalho,
2034
2144
  descricao e rodape nao deslocam o clique nem o hover.
2035
2145
  """
2036
- if not (self.wizard and self._wizard_lista()) or self._wizard_ini is None:
2146
+ if not self.wizard or self._wizard_ini is None:
2147
+ return None
2148
+ if not (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback'):
2037
2149
  return None
2038
2150
  return getattr(self, '_wizard_item_linhas', {}).get(y - self._wizard_ini)
2039
2151
 
@@ -2059,11 +2171,31 @@ class Painel:
2059
2171
  return topo, itens[topo:topo + limite]
2060
2172
 
2061
2173
  def clicar_wizard(self, y: int) -> bool:
2062
- """Clique num item da lista do wizard: destaca e confirma (mouseUp)."""
2174
+ """Clique/toque num item ou botão do wizard."""
2063
2175
  indice = self.indice_wizard_no_clique(y)
2064
2176
  if indice is None:
2065
2177
  return False
2178
+ if self.wizard and self.wizard.get('tipo') == 'ag_callback':
2179
+ url = str((self.wizard.get('dados') or {}).get('url') or self._ag_auth_url or '')
2180
+ if not url:
2181
+ return False
2182
+ if indice == 0:
2183
+ if copiar_area_transferencia(url):
2184
+ self.avisar('link OAuth copiado — abra no navegador', 'ok', 6)
2185
+ else:
2186
+ self.avisar(f'copie manualmente: {url}', 'aviso', 10)
2187
+ return True
2188
+ if indice == 1:
2189
+ if tui_core.abrir_url_sistema(url):
2190
+ self.avisar('abrindo link OAuth no navegador…', 'ok', 6)
2191
+ else:
2192
+ copiar_area_transferencia(url)
2193
+ self.avisar('navegador não abriu — link copiado para colar no browser', 'aviso', 8)
2194
+ return True
2195
+ return False
2066
2196
  lista = self._itens_wizard_filtrados()
2197
+ if not (0 <= indice < len(lista)):
2198
+ return False
2067
2199
  self.wizard['sel'] = indice
2068
2200
  self.buf = ''
2069
2201
  self.passo_wizard(lista[indice][1])
@@ -2093,8 +2225,14 @@ class Painel:
2093
2225
  idx_sel = self._overlay_clique.get(y - self._modal_ini)
2094
2226
  if idx_sel is None:
2095
2227
  return None
2228
+ acoes = (self.modal or {}).get('acoes') or []
2096
2229
  copias = (self.modal or {}).get('copias') or []
2097
- validos = [i for i, c in enumerate(copias) if c]
2230
+ linhas = (self.modal or {}).get('linhas') or []
2231
+ validos = [
2232
+ i for i in range(len(linhas))
2233
+ if (i < len(acoes) and isinstance(acoes[i], dict))
2234
+ or (i < len(copias) and copias[i])
2235
+ ]
2098
2236
  return validos[idx_sel] if 0 <= idx_sel < len(validos) else None
2099
2237
  posicao = y - self._modal_ini
2100
2238
  linhas = (self.modal or {}).get('linhas') or []
@@ -2103,10 +2241,17 @@ class Painel:
2103
2241
  return None
2104
2242
 
2105
2243
  def clicar_modal(self, y: int) -> bool:
2106
- """Clique num endereço do modal: copia para a área de transferência e avisa."""
2244
+ """Clique/toque num botão ou link do modal: executa ação ou copia URL."""
2107
2245
  indice = self.indice_modal_no_clique(y)
2108
2246
  if indice is None:
2109
2247
  return False
2248
+ acoes = (self.modal or {}).get('acoes') or []
2249
+ if indice < len(acoes) and isinstance(acoes[indice], dict):
2250
+ ac = acoes[indice]
2251
+ fn = ac.get('fn')
2252
+ if callable(fn):
2253
+ fn()
2254
+ return True
2110
2255
  copias = (self.modal or {}).get('copias') or []
2111
2256
  alvo = copias[indice] if indice < len(copias) else None
2112
2257
  if not alvo:
@@ -2132,6 +2277,137 @@ class Painel:
2132
2277
  return f'http://{nome}.local{sufixo}/v1'
2133
2278
  return f'http://127.0.0.1{sufixo}/v1'
2134
2279
 
2280
+ def _pilha(self) -> list:
2281
+ pilha = getattr(self, '_wizard_pilha', None)
2282
+ if pilha is None:
2283
+ pilha = []
2284
+ self._wizard_pilha = pilha
2285
+ return pilha
2286
+
2287
+ def _empilhar_wizard(self, novo: dict) -> None:
2288
+ """Abre um sub-passo do wizard guardando o anterior para Esc voltar 1 nível."""
2289
+ if self.wizard is not None:
2290
+ self._pilha().append(copy.deepcopy(self.wizard))
2291
+ self.wizard = novo
2292
+ self.buf = ''
2293
+
2294
+ def _voltar_wizard(self) -> bool:
2295
+ """Volta um passo na pilha de dialogs; retorna True se voltou, False se fechou."""
2296
+ self.buf = ''
2297
+ pilha = self._pilha()
2298
+ if pilha:
2299
+ self.wizard = pilha.pop()
2300
+ return True
2301
+ if self.wizard:
2302
+ tipo = self.wizard.get('tipo')
2303
+ passo = self.wizard.get('passo')
2304
+ if tipo == 'add' and passo == 'segredo':
2305
+ self.wizard['passo'] = 'base'
2306
+ return True
2307
+ if tipo == 'add' and passo == 'base':
2308
+ self.wizard['passo'] = 'nome'
2309
+ return True
2310
+ if tipo in ('ag_hub', 'wb_hub', 'oauth_hub'):
2311
+ self.abrir_hub_connect()
2312
+ return True
2313
+ if tipo == 'ag_callback':
2314
+ self.abrir_hub_antigravity()
2315
+ return True
2316
+ self.wizard = None
2317
+ return False
2318
+
2319
+ def ponto_no_botao_esc(self, x: int, y: int) -> bool:
2320
+ """Toque/clique no botão `esc back` do rodapé ou no `esc` do topo do dialog."""
2321
+ if not (self.modal or self.wizard):
2322
+ return False
2323
+ zona = getattr(self, '_esc_zona', None)
2324
+ if zona and y == self._status_y and zona[0] <= x <= zona[1]:
2325
+ return True
2326
+ top = getattr(self, '_overlay_top', None)
2327
+ left = getattr(self, '_overlay_left', None)
2328
+ w_ov = getattr(self, '_overlay_width', 0)
2329
+ if top is not None and left is not None and w_ov >= 12:
2330
+ if y == top + 1 and (left + w_ov - 8) <= x <= (left + w_ov - 1):
2331
+ return True
2332
+ return False
2333
+
2334
+ def clicar_fora_overlay(self, x: int, y: int) -> bool:
2335
+ """Toque fora da caixa do dialog volta um nível / fecha (conforto no celular)."""
2336
+ if not (self.modal or self.wizard):
2337
+ return False
2338
+ top = getattr(self, '_overlay_top', None)
2339
+ left = getattr(self, '_overlay_left', None)
2340
+ h_ov = getattr(self, '_overlay_height', 0)
2341
+ w_ov = getattr(self, '_overlay_width', 0)
2342
+ if top is None or left is None or not h_ov or not w_ov:
2343
+ return False
2344
+ # Não interfere na linha de entrada nem na barra de status
2345
+ if y >= max(1, self.altura - 4):
2346
+ return False
2347
+ dentro = (top <= y < top + h_ov) and (left <= x < left + w_ov)
2348
+ if not dentro:
2349
+ if self.modal:
2350
+ self.modal = None
2351
+ else:
2352
+ self._voltar_wizard()
2353
+ return True
2354
+ return False
2355
+
2356
+ def clicar_barra_home(self, x: int, y: int) -> bool:
2357
+ """Navegação por toque na home (sem setas nem Enter):
2358
+ - tocar na linha de status (modelo -> /model, esforço -> /effort, connect -> /connect, commands -> paleta)
2359
+ - tocar na linha compacta de cota (Antigravity) -> abre /quota
2360
+ - tocar na caixa de entrada vazia -> abre o menu `/` de comandos
2361
+ """
2362
+ if self.modal or self.wizard:
2363
+ return False
2364
+ if y == self._status_y:
2365
+ for ini, fim, acao in getattr(self, '_status_acoes', []):
2366
+ if ini <= x <= fim:
2367
+ if acao == 'model':
2368
+ self.abrir_wizard_modelo()
2369
+ elif acao == 'effort':
2370
+ self.abrir_wizard_variante()
2371
+ elif acao == 'connect':
2372
+ self.abrir_hub_connect()
2373
+ elif acao == 'palette':
2374
+ self.abrir_paleta()
2375
+ return True
2376
+ return False
2377
+ # Tocar na caixa de entrada vazia abre/fecha o menu de comandos "/"
2378
+ linha_caixa = (self._status_y - 2) if self._status_y is not None else -1
2379
+ if y == linha_caixa and not self.buf:
2380
+ self.buf = '/'
2381
+ self.menu_off = False
2382
+ self.menu_sel = 0
2383
+ return True
2384
+ # Tocar na linha de cotas da home (linha 3 em telas estreitas ou coluna direita) abre /quota
2385
+ if not self._menu_aberto():
2386
+ if self.largura < 96 and y == 3:
2387
+ self.mostrar_tokens()
2388
+ return True
2389
+ if self.largura >= 96 and y in (2, 3, 4) and x >= int(self.largura * 0.72):
2390
+ self.mostrar_tokens()
2391
+ return True
2392
+ return False
2393
+
2394
+ def clicar_scroll_overlay(self, x: int, y: int) -> bool:
2395
+ """Toque na linha de paginação do diálogo rola a lista pra baixo (ou pra cima na esquerda)."""
2396
+ if not (self.wizard and self._wizard_lista()):
2397
+ return False
2398
+ top = getattr(self, '_overlay_top', None)
2399
+ left = getattr(self, '_overlay_left', None)
2400
+ h_ov = getattr(self, '_overlay_height', 0)
2401
+ w_ov = getattr(self, '_overlay_width', 0)
2402
+ if top is None or left is None or h_ov < 6 or w_ov < 16:
2403
+ return False
2404
+ # Linha de paginação fica logo acima do rodapé (h_ov - 4) ou no rodapé (h_ov - 2)
2405
+ y_rel = y - top
2406
+ if y_rel in (h_ov - 4, h_ov - 3, h_ov - 2) and left <= x < left + w_ov:
2407
+ sentido = -1 if x < (left + w_ov // 2) else 1
2408
+ return self.roda_mouse(sentido)
2409
+ return False
2410
+
2135
2411
  def ponto_no_botao_copiar(self, x: int, y: int) -> bool:
2136
2412
  """O ponto (x, y) do terminal está sobre o botão copiar do rodapé?"""
2137
2413
  zona = self._copiar_zona
@@ -2256,26 +2532,38 @@ class Painel:
2256
2532
  def desenhar(self, frame: list) -> None:
2257
2533
  # Em modo TUI:
2258
2534
  # 1) Evita redesenho com flicker usando BSU/ESU (Synchronized Output DEC 2026)
2259
- # 2) Cache de frame base enquanto um dialogo esta aberto (scroll/busca no dialogo vira instantaneo)
2535
+ # 2) Posiciona cada linha explicitamente (\x1b[row;1H) em vez de depender de \n
2536
+ # — nunca produz escadinha nem lixo de frame antigo ao dar zoom no Termux/Linux
2537
+ # 3) Ancora o rodapé (caixa + status) no fundo real da tela para ficar confortável no celular
2260
2538
  saida = sys.stdout
2261
- altura = self.altura
2262
- largura = self.largura
2263
- max_frame = max(3, altura - 4)
2264
- if len(frame) > max_frame:
2265
- frame = frame[:max_frame]
2539
+ altura = max(6, self.altura)
2540
+ largura = max(20, self.largura)
2541
+ max_frame = max(2, altura - 4)
2542
+ frame = list(frame[:max_frame])
2543
+ # Preenche ate o topo da caixa de entrada para limpar linhas antigas apos zoom/resize
2544
+ while len(frame) < max_frame:
2545
+ frame.append('')
2266
2546
  self.ultima_contagem = len(frame)
2267
2547
  base = len(frame)
2268
2548
  buf = ['\x1b[?2026h\x1b[H']
2269
- for linha in frame:
2270
- buf.append(linha + '\x1b[0m\x1b[K\n')
2271
- regua = '─' * max(8, largura - 2)
2272
- buf.append(f'\x1b[{base + 1};1H' + ansi('borda') + '╭' + regua + '╮' + RESET + '\x1b[K')
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')
2554
+ regua = '─' * max(6, largura - 2)
2555
+ buf.append(f'\x1b[{base + 1};1H\x1b[2K' + ansi('borda') + '╭' + regua + '╮' + RESET)
2273
2556
  buf.append(self._formatar_caixa(base + 2))
2274
- buf.append(f'\x1b[{base + 3};1H' + ansi('borda') + '╰' + regua + '╯' + RESET + '\x1b[K')
2557
+ buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2275
2558
  self._status_y = base + 3
2276
2559
  buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2277
- coluna = min(getattr(self, '_coluna_cursor', 5), max(2, self.largura - 1))
2278
- buf.append(f'\x1b[{base + 2};{coluna}H\x1b[?2026l')
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()):
2563
+ buf.append('\x1b[?25l\x1b[?2026l')
2564
+ else:
2565
+ coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
2566
+ buf.append(f'\x1b[?25h\x1b[{base + 2};{coluna}H\x1b[?2026l')
2279
2567
  saida.write(''.join(buf))
2280
2568
  saida.flush()
2281
2569
 
@@ -2296,8 +2584,9 @@ class Painel:
2296
2584
  r_ov = getattr(self, '_restart_overlay', None)
2297
2585
  if not self.modal and not self.wizard and not r_ov:
2298
2586
  return None
2299
- w_box = max(30, min(self.largura - 4, 78))
2300
- limite = max(4, min(14, self.altura - 12))
2587
+ w_box = max(22, min(self.largura - 2 if self.largura < 56 else self.largura - 4, 78))
2588
+ # Reserva espaço para cabeçalho/busca/rodapé do diálogo para nunca estourar telas baixas
2589
+ limite = max(2, min(14, self.altura - 11))
2301
2590
  cores = self._cores_dialogo()
2302
2591
 
2303
2592
  if r_ov:
@@ -2310,7 +2599,7 @@ class Painel:
2310
2599
  {'tipo': 'texto', 'rotulo': '', 'cor': FRACO},
2311
2600
  {'tipo': 'texto', 'rotulo': f' {atual}', 'cor': TEXTO},
2312
2601
  ]
2313
- w_r = min(max(44, self.largura - 14), 60)
2602
+ w_r = max(24, min(self.largura - 2, 60))
2314
2603
  rich_lines, _ = tui_core.construir_dialogo_opencode(
2315
2604
  titulo='◈ krnell',
2316
2605
  largura_caixa=w_r,
@@ -2327,24 +2616,39 @@ class Painel:
2327
2616
 
2328
2617
  if self.modal:
2329
2618
  titulo = str(self.modal.get('titulo') or 'Detalhes')
2330
- dica = str(self.modal.get('dica') or 'Enter ou Esc fecha')
2619
+ dica = str(self.modal.get('dica') or 'Esc voltar')
2331
2620
  linhas_mod = self.modal.get('linhas') or []
2332
2621
  copias = self.modal.get('copias') or []
2622
+ acoes = self.modal.get('acoes') or []
2333
2623
  itens = []
2334
2624
  for idx, l in enumerate(linhas_mod):
2335
- txt = l.plain if isinstance(l, Text) else str(l)
2336
- if idx < len(copias) and copias[idx]:
2337
- itens.append({'tipo': 'item', 'rotulo': txt, 'detalhe': 'clique p/ copiar',
2338
- 'badge': '↳', 'badge_cor': ACENTO2, 'chave': str(idx)})
2625
+ if idx < len(acoes) and isinstance(acoes[idx], dict):
2626
+ ac = acoes[idx]
2627
+ itens.append({
2628
+ 'tipo': 'item',
2629
+ 'rotulo': str(ac.get('rotulo') or (l.plain if isinstance(l, Text) else str(l))),
2630
+ 'detalhe': str(ac.get('detalhe') or ''),
2631
+ 'badge': str(ac.get('badge') or '▸'),
2632
+ 'badge_cor': ac.get('cor') or ACENTO2,
2633
+ 'ativo': bool(ac.get('ativo')),
2634
+ 'chave': str(idx),
2635
+ })
2636
+ elif idx < len(copias) and copias[idx]:
2637
+ txt = l.plain if isinstance(l, Text) else str(l)
2638
+ itens.append({'tipo': 'item', 'rotulo': txt, 'detalhe': 'toque p/ copiar',
2639
+ 'badge': '⎘', 'badge_cor': ACENTO2, 'chave': str(idx)})
2640
+ elif isinstance(l, Text):
2641
+ itens.append({'tipo': 'texto', 'rotulo': l.plain, 'rich': l, 'cor': TEXTO})
2339
2642
  else:
2340
- itens.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO})
2643
+ itens.append({'tipo': 'texto', 'rotulo': str(l), 'cor': TEXTO})
2644
+ limite_mod = max(3, min(len(itens), max(3, self.altura - 8)))
2341
2645
  rich_lines, mapa_clique = tui_core.construir_dialogo_opencode(
2342
2646
  titulo=titulo,
2343
2647
  largura_caixa=w_box,
2344
2648
  itens=itens,
2345
- foco=-1,
2649
+ foco=0 if acoes else -1,
2346
2650
  topo=0,
2347
- limite=max(limite, len(itens)),
2651
+ limite=limite_mod,
2348
2652
  rodape=dica,
2349
2653
  cores=cores,
2350
2654
  mostrar_busca=False,
@@ -2362,11 +2666,13 @@ class Painel:
2362
2666
  # Agrupa discretamente em 3 seções limpas (estilo OpenCode)
2363
2667
  itens_dlg = []
2364
2668
  def _secao_de(chave: str) -> str:
2365
- if chave in ('ag_hub', 'nv_ativar', 'wb_hub', 'oc_ativar', 'oauth_hub'):
2366
- return 'Accounts & Free'
2669
+ if chave in ('nv_ativar', 'oc_ativar'):
2670
+ return 'Built-in (Free · No Account)'
2671
+ if chave in ('ag_hub', 'wb_hub', 'oauth_hub'):
2672
+ return 'Accounts & OAuth'
2367
2673
  if chave in ('sync_opencode', 'custom_add'):
2368
2674
  return 'More'
2369
- return 'API Providers'
2675
+ return 'API Keys'
2370
2676
  sec_ant = None
2371
2677
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2372
2678
  for rotulo, chave, detalhe in filtrados:
@@ -2389,6 +2695,31 @@ class Painel:
2389
2695
  'ativo': eh_atual,
2390
2696
  'chave': chave,
2391
2697
  })
2698
+ elif self.wizard.get('tipo') == 'model' and (self.wizard.get('dados') or {}).get('entradas'):
2699
+ # Agrupa por provedor exatamente como o Select model do OpenCode
2700
+ entradas_map = {
2701
+ f"pm:{e['provedor']}:{e['id']}": e['secao']
2702
+ for e in (self.wizard.get('dados') or {}).get('entradas') or []
2703
+ }
2704
+ itens_dlg = []
2705
+ sec_ant = None
2706
+ chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2707
+ for rotulo, chave, detalhe in filtrados:
2708
+ sec = entradas_map.get(chave, 'Custom')
2709
+ if not self.buf.strip() and sec != sec_ant:
2710
+ itens_dlg.append({'tipo': 'secao', 'rotulo': sec})
2711
+ sec_ant = sec
2712
+ eh_atual = chave_atual is not None and chave == chave_atual
2713
+ badge = '●' if eh_atual else ('+' if chave == 'custom_id' else ' ')
2714
+ itens_dlg.append({
2715
+ 'tipo': 'item',
2716
+ 'rotulo': rotulo,
2717
+ 'detalhe': detalhe,
2718
+ 'badge': badge,
2719
+ 'badge_cor': OK if eh_atual else (ACENTO2 if chave == 'custom_id' else FRACO),
2720
+ 'ativo': eh_atual,
2721
+ 'chave': chave,
2722
+ })
2392
2723
  else:
2393
2724
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2394
2725
  itens_dlg = []
@@ -2433,8 +2764,29 @@ class Painel:
2433
2764
  mascarar = bool(w.get('passo') in ('chave', 'segredo'))
2434
2765
  itens_txt = []
2435
2766
  for l in linhas_w:
2436
- txt = l.plain if isinstance(l, Text) else str(l)
2437
- itens_txt.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO if txt else FRACO})
2767
+ if isinstance(l, Text):
2768
+ itens_txt.append({'tipo': 'texto', 'rotulo': l.plain, 'rich': l, 'cor': TEXTO if l.plain else FRACO})
2769
+ else:
2770
+ txt = str(l)
2771
+ itens_txt.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO if txt else FRACO})
2772
+ if w.get('tipo') == 'ag_callback' and (w.get('dados') or {}).get('url'):
2773
+ itens_txt.append({'tipo': 'texto', 'rotulo': '', 'cor': FRACO})
2774
+ itens_txt.append({
2775
+ 'tipo': 'item',
2776
+ 'rotulo': 'Copiar link OAuth',
2777
+ 'detalhe': 'toque / clique',
2778
+ 'badge': '⎘',
2779
+ 'badge_cor': ACENTO,
2780
+ 'chave': 'ag_copy_url',
2781
+ })
2782
+ itens_txt.append({
2783
+ 'tipo': 'item',
2784
+ 'rotulo': 'Abrir no navegador',
2785
+ 'detalhe': 'browser',
2786
+ 'badge': '↗',
2787
+ 'badge_cor': ACENTO2,
2788
+ 'chave': 'ag_open_url',
2789
+ })
2438
2790
  # Placeholder minimalista conforme o passo
2439
2791
  passo_w = w.get('passo')
2440
2792
  placeholder_w = {
@@ -2453,7 +2805,7 @@ class Painel:
2453
2805
  limite=max(8, len(itens_txt)),
2454
2806
  busca=self.buf,
2455
2807
  placeholder=placeholder_w,
2456
- rodape='Enter confirma · Esc cancela',
2808
+ rodape='Enter confirma · Esc voltar',
2457
2809
  cores=cores,
2458
2810
  mascarar_busca=mascarar,
2459
2811
  mostrar_busca=True,
@@ -2477,13 +2829,16 @@ class Painel:
2477
2829
  contagem = cell_len(dica)
2478
2830
  elif not self.wizard:
2479
2831
  dica = '/ commands · Ctrl+L connect · Ctrl+P palette'
2480
- if cell_len(dica) > largura - 10:
2481
- dica = '/connect · /help'
2832
+ if cell_len(dica) > largura - 8:
2833
+ dica = '/ commands · /connect'
2834
+ if cell_len(dica) > largura - 8:
2835
+ dica = '/help'
2836
+ dica = tui_core.truncate_vis(dica, max(1, largura - 7))
2482
2837
  partes.extend([ansi('fraco'), dica, RESET])
2483
2838
  contagem = cell_len(dica)
2484
- pad = max(1, largura - 5 - contagem)
2839
+ pad = max(0, largura - 6 - contagem)
2485
2840
  partes.extend([' ' * pad, ansi('borda'), '│', RESET])
2486
- self._coluna_cursor = 5 + cell_len(visivel)
2841
+ self._coluna_cursor = min(5 + cell_len(visivel), max(2, largura - 1))
2487
2842
  return ''.join(partes)
2488
2843
 
2489
2844
  def _escrever_caixa(self, saida, linha: int) -> None:
@@ -2495,6 +2850,8 @@ class Painel:
2495
2850
 
2496
2851
  def atualizar_tela(self) -> None:
2497
2852
  self.largura, self.altura = shutil.get_terminal_size((110, 30))
2853
+ self.largura = max(24, self.largura)
2854
+ self.altura = max(8, self.altura)
2498
2855
  snap = self.coletor.ler()
2499
2856
  self._snap_visto = snap
2500
2857
  if (self.modal or {}).get('tipo') == 'tokens' and \
@@ -2513,26 +2870,39 @@ class Painel:
2513
2870
  cortado = cache[2]
2514
2871
  else:
2515
2872
  renderaveis = self.render(snap)
2516
- frame = self._linhas(renderaveis, self.largura)
2517
- cortado = len(frame) > limite
2873
+ pronto = getattr(self, '_frame_menu_pronto', None)
2874
+ if pronto is not None:
2875
+ frame = list(pronto)
2876
+ cortado = False
2877
+ else:
2878
+ frame = self._linhas(renderaveis, self.largura)
2879
+ cortado = len(frame) > limite
2518
2880
  frame = frame[:limite]
2519
2881
  self._cache_frame_base = (chave_base, list(frame), cortado)
2520
2882
  self._overlay_top = None
2521
2883
  self._overlay_left = None
2884
+ self._overlay_width = 0
2885
+ self._overlay_height = 0
2522
2886
  self._overlay_clique = {}
2523
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.
2524
2890
  modal_identidade = ('tokens-live' if (self.modal or {}).get('tipo') == 'tokens' else id(self.modal))
2525
2891
  dialogo_atual = (id(self.wizard), (self.wizard or {}).get('tipo'), (self.wizard or {}).get('passo'), modal_identidade, em_restart)
2526
2892
  if tem_overlay and dialogo_atual != getattr(self, '_dialogo_id', None):
2527
2893
  self._dialogo_id = dialogo_atual
2528
- self._dialogo_frame = 0
2894
+ self._dialogo_frame = 99 if (self.largura < 80 or self.altura < 24 or tui_core.is_termux()) else 0
2529
2895
  elif not tem_overlay:
2530
2896
  self._dialogo_id = None
2531
2897
  self._dialogo_frame = 99
2898
+ # Em telas baixas, garante que o frame do overlay nunca passe da area util
2532
2899
  if tem_overlay:
2533
2900
  ov = self._construir_overlay_linhas()
2534
2901
  if ov is not None:
2535
2902
  caixa_linhas, mapa_clique, _w_box = ov
2903
+ if len(caixa_linhas) > limite and limite >= 4:
2904
+ caixa_linhas = caixa_linhas[:limite - 1] + [caixa_linhas[-1]]
2905
+ mapa_clique = {k: v for k, v in mapa_clique.items() if k < limite - 1}
2536
2906
  # Animação de entrada suave (2 frames rápidos, sem travar teclado)
2537
2907
  if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 6:
2538
2908
  passo_a = self._dialogo_frame
@@ -2551,14 +2921,16 @@ class Painel:
2551
2921
  )
2552
2922
  self._overlay_top = top
2553
2923
  self._overlay_left = left
2924
+ self._overlay_width = _w_box
2925
+ self._overlay_height = len(caixa_vis)
2554
2926
  self._overlay_clique = mapa_clique
2555
2927
  self._menu_ini = None
2556
- if self.wizard and self._wizard_lista():
2928
+ if self.wizard and (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback'):
2557
2929
  self._wizard_ini = top
2558
2930
  self._wizard_item_linhas = mapa_clique
2559
2931
  else:
2560
2932
  self._wizard_ini = None
2561
- if self.modal and self.modal.get('copias'):
2933
+ if self.modal and (self.modal.get('copias') or self.modal.get('acoes')):
2562
2934
  self._modal_ini = top
2563
2935
  else:
2564
2936
  self._modal_ini = None
@@ -2722,6 +3094,7 @@ class Painel:
2722
3094
  saida.write('\x1b[?1049h\x1b[?25h')
2723
3095
  saida.write('\x1b[?7l')
2724
3096
  saida.flush()
3097
+ self._precisa_limpar_tela = True
2725
3098
  try:
2726
3099
  self.atualizar_tela()
2727
3100
  while not self.saindo:
@@ -2729,6 +3102,8 @@ class Painel:
2729
3102
  tecla = self.ler_tecla(0.03 if getattr(self, '_dialogo_frame', 99) < 2 else (0.08 if animando else 0.25))
2730
3103
  agora = time.monotonic()
2731
3104
  if tecla is None:
3105
+ nova_larg, nova_alt = shutil.get_terminal_size((self.largura, self.altura))
3106
+ mudou_tamanho = (nova_larg != self.largura or nova_alt != self.altura)
2732
3107
  mudou_dados = self.coletor.revisao != self.revisao_vista
2733
3108
  expirou_msg = bool(self.msg and time.time() > self.msg_ate)
2734
3109
  if expirou_msg:
@@ -2738,7 +3113,11 @@ class Painel:
2738
3113
  if tick_anim and (animando or (not self.wizard and not self.modal)):
2739
3114
  self._anim_tick = (self._anim_tick + 1) % 100000
2740
3115
  self._anim_ultimo = agora
2741
- if mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
3116
+ if mudou_tamanho:
3117
+ self._cache_frame_base = None
3118
+ self._dialogo_frame = 99
3119
+ 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))):
2742
3121
  self.atualizar_tela()
2743
3122
  continue
2744
3123
  # Coalescing de scroll/setas: drena eventos repetidos pendentes no buffer
@@ -2826,6 +3205,9 @@ class Painel:
2826
3205
  buf_antes = self.buf
2827
3206
  menu_antes = self._menu_aberto()
2828
3207
  if tecla == 'resize':
3208
+ self._cache_frame_base = None
3209
+ self._dialogo_frame = 99
3210
+ self._precisa_limpar_tela = True
2829
3211
  self.atualizar_tela()
2830
3212
  return
2831
3213
  if tecla in ('ctrl_p', 'ctrl_k'):
@@ -2861,9 +3243,19 @@ class Painel:
2861
3243
  self._reexec_solicitado = False
2862
3244
  self.atualizar_tela()
2863
3245
  return
2864
- if tecla == 'esc' and self.wizard and self.wizard.get('tipo') in ('ag_hub', 'wb_hub', 'oauth_hub'):
2865
- self.buf = ''
2866
- self.abrir_hub_connect()
3246
+ if tecla == 'esc':
3247
+ if self.modal:
3248
+ self.modal = None
3249
+ elif self.wizard:
3250
+ voltou = self._voltar_wizard()
3251
+ if not voltou:
3252
+ self.msg = ('aviso', 'fechado')
3253
+ self.msg_ate = time.time() + 2
3254
+ elif self._menu_aberto():
3255
+ # como no OpenCode: o texto fica; o popup volta na próxima tecla
3256
+ self.menu_off = True
3257
+ else:
3258
+ self.buf = ''
2867
3259
  self.atualizar_tela()
2868
3260
  return
2869
3261
  if tecla == 'ctrl_m':
@@ -2897,12 +3289,24 @@ class Painel:
2897
3289
  redesenhar = True
2898
3290
  elif self.clicar_botao_copiar(tecla[1], tecla[2]):
2899
3291
  redesenhar = True
2900
- elif self.modal and self.modal.get('copias'):
2901
- redesenhar = self.clicar_modal(tecla[2])
2902
- elif self.wizard and self._wizard_lista():
2903
- redesenhar = self.clicar_wizard(tecla[2])
3292
+ elif self.ponto_no_botao_esc(tecla[1], tecla[2]):
3293
+ if self.modal:
3294
+ self.modal = None
3295
+ else:
3296
+ self._voltar_wizard()
3297
+ redesenhar = True
3298
+ elif self.modal and (self.modal.get('copias') or self.modal.get('acoes')) and self.clicar_modal(tecla[2]):
3299
+ redesenhar = True
3300
+ elif self.wizard and (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback') and self.clicar_wizard(tecla[2]):
3301
+ redesenhar = True
3302
+ elif self.wizard and self._wizard_lista() and self.clicar_scroll_overlay(tecla[1], tecla[2]):
3303
+ redesenhar = True
3304
+ elif (self.modal or self.wizard) and self.clicar_fora_overlay(tecla[1], tecla[2]):
3305
+ redesenhar = True
3306
+ elif self.clicar_menu(tecla[2]):
3307
+ redesenhar = True
2904
3308
  else:
2905
- redesenhar = self.clicar_menu(tecla[2])
3309
+ redesenhar = self.clicar_barra_home(tecla[1], tecla[2])
2906
3310
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_move':
2907
3311
  redesenhar = self.passar_mouse(tecla[1], tecla[2])
2908
3312
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_roda':
@@ -3255,6 +3659,10 @@ class Painel:
3255
3659
  cfg = ler_config()
3256
3660
  if cfg.get('dashboard_auto_open', True) is False:
3257
3661
  return
3662
+ # No Termux não tenta abrir navegador automaticamente na abertura
3663
+ # (o usuário ainda pode usar /web quando quiser).
3664
+ if tui_core.is_termux():
3665
+ return
3258
3666
  try:
3259
3667
  url = dashboard_web.local_dashboard_url(cfg)
3260
3668
  except (TypeError, ValueError):
@@ -3828,35 +4236,57 @@ class Painel:
3828
4236
  ag_contas = ag_st.get('accounts') or []
3829
4237
  if ag_contas:
3830
4238
  linhas.append(Text(''))
3831
- linhas.append(Text('antigravity (5h · semanal)', style=FRACO))
4239
+ linhas.append(Text('ANTIGRAVITY (5h · 7d)', style=f'bold {ACENTO2}'))
3832
4240
  for acc in ag_contas:
3833
4241
  email = str(acc.get('email') or 'Google')
3834
4242
  ativa = bool(acc.get('active'))
3835
4243
  t = Text()
3836
4244
  t.append('● ' if ativa else '○ ', style=OK if ativa else FRACO)
3837
- t.append(email, style=TEXTO if ativa else FRACO)
4245
+ t.append(email, style=f'bold {TEXTO}' if ativa else FRACO)
3838
4246
  tier = acc.get('paidTierName') or ''
3839
4247
  if tier:
3840
- t.append(f' · {tier}', style=FRACO)
4248
+ t.append(f' · {tier}', style=FRACO)
3841
4249
  linhas.append(t)
3842
4250
  q_acc = acc.get('quota') if isinstance(acc.get('quota'), dict) else (
3843
4251
  ag_st.get('quota') if ativa and isinstance(ag_st.get('quota'), dict) else {})
4252
+ estreito_q = self.largura < 68
3844
4253
  for item_q in _resumo_cota_antigravity({'quota': q_acc}):
3845
- tq = Text()
3846
- tq.append(f" {item_q['nome']:<8}", style=FRACO)
3847
4254
  b5 = item_q.get('b5h')
3848
4255
  bs = item_q.get('bsem')
3849
- if isinstance(b5, dict) and isinstance(b5.get('remainingFraction'), (int, float)):
3850
- f5 = b5['remainingFraction']
3851
- t5, c5 = _fmt_bucket_curto(b5, '5h')
3852
- tq.append(tui_core.barra_progresso(f5, 6) + ' ' + t5, style=c5)
3853
- if bs:
3854
- tq.append(' ', style=FRACO)
3855
- if isinstance(bs, dict) and isinstance(bs.get('remainingFraction'), (int, float)):
3856
- fs = bs['remainingFraction']
3857
- ts, cs = _fmt_bucket_curto(bs, '7d')
3858
- tq.append(tui_core.barra_progresso(fs, 6) + ' ' + ts, style=cs)
3859
- linhas.append(tq)
4256
+ tem_5h = isinstance(b5, dict) and isinstance(b5.get('remainingFraction'), (int, float))
4257
+ tem_7d = isinstance(bs, dict) and isinstance(bs.get('remainingFraction'), (int, float))
4258
+ if estreito_q:
4259
+ # No celular: 1 linha limpa por janela, sem espremer nem quebrar com "..."
4260
+ if tem_5h:
4261
+ f5 = b5['remainingFraction']
4262
+ t5, c5 = _fmt_bucket_curto(b5, '5h')
4263
+ tq = Text()
4264
+ tq.append(f" {item_q['nome']:<7} ", style=TEXTO)
4265
+ tq.append(tui_core.barra_progresso(f5, 8) + ' ', style=c5)
4266
+ tq.append(t5, style=c5)
4267
+ linhas.append(tq)
4268
+ if tem_7d:
4269
+ fs = bs['remainingFraction']
4270
+ ts, cs = _fmt_bucket_curto(bs, '7d')
4271
+ tq = Text()
4272
+ tq.append((' ' if tem_5h else f" {item_q['nome']:<7} "), style=TEXTO)
4273
+ tq.append(tui_core.barra_progresso(fs, 8) + ' ', style=cs)
4274
+ tq.append(ts, style=cs)
4275
+ linhas.append(tq)
4276
+ else:
4277
+ tq = Text()
4278
+ tq.append(f" {item_q['nome']:<8}", style=TEXTO)
4279
+ if tem_5h:
4280
+ f5 = b5['remainingFraction']
4281
+ t5, c5 = _fmt_bucket_curto(b5, '5h')
4282
+ tq.append(tui_core.barra_progresso(f5, 6) + ' ' + t5, style=c5)
4283
+ if tem_7d:
4284
+ tq.append(' ', style=FRACO)
4285
+ if tem_7d:
4286
+ fs = bs['remainingFraction']
4287
+ ts, cs = _fmt_bucket_curto(bs, '7d')
4288
+ tq.append(tui_core.barra_progresso(fs, 6) + ' ' + ts, style=cs)
4289
+ linhas.append(tq)
3860
4290
  contas_wb = self._contas_workbuddy()
3861
4291
  if contas_wb:
3862
4292
  linhas.append(Text(''))
@@ -3904,7 +4334,7 @@ class Painel:
3904
4334
  style=FRACO))
3905
4335
  linhas.append(Text('o bridge soma sozinho a cada resposta; cotas 5h/7d revalidam ao vivo.', style=FRACO))
3906
4336
  self.modal = {'tipo': 'tokens', 'titulo': 'Quotas & tokens', 'linhas': linhas,
3907
- 'dica': 'live · Enter ou Esc fecha', 'revisao': self.coletor.revisao}
4337
+ 'dica': 'live · Esc ou toque fora fecha', 'revisao': self.coletor.revisao}
3908
4338
 
3909
4339
  def mostrar_stats(self, arg: str = ''):
3910
4340
  itens = ler_requisicoes(3000, linhas_max=3000)
@@ -4009,6 +4439,7 @@ class Painel:
4009
4439
 
4010
4440
  def abrir_hub_connect(self, arg: str = ''):
4011
4441
  """Hub unificado /connect: provedores, OAuth (Antigravity/WorkBuddy), chaves e OpenCode."""
4442
+ self._pilha().clear()
4012
4443
  alvo = (arg or '').strip().lower()
4013
4444
  if alvo in ('antigravity', 'ag', 'google'):
4014
4445
  self.abrir_hub_antigravity()
@@ -4050,32 +4481,33 @@ class Painel:
4050
4481
  return kimi.PORTA_PADRAO
4051
4482
 
4052
4483
  def iniciar_login_antigravity(self):
4053
- """Dispara fluxo OAuth do Antigravity (abre navegador + permite colar callback no Termux/SSH)."""
4484
+ """Dispara fluxo OAuth do Antigravity (abre navegador + botões copiar/abrir + colar callback)."""
4054
4485
  def tarefa():
4055
4486
  porta = self._porta_motor_local()
4056
4487
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=18.0)
4057
- url = kimi.antigravity_login_url(porta)
4488
+ url, state = kimi.antigravity_login_url(porta)
4058
4489
  abriu = tui_core.abrir_url_sistema(url)
4059
4490
  copiou = copiar_area_transferencia(url)
4060
4491
  self._ag_auth_url = url
4061
- self.wizard = {
4492
+ self._ag_auth_state = state
4493
+ self._empilhar_wizard({
4062
4494
  'tipo': 'ag_callback',
4063
4495
  'passo': 'colar',
4064
4496
  'titulo': 'Antigravity · Google OAuth',
4065
- 'dados': {'url': url, 'abriu': abriu, 'copiou': copiou, 'porta': porta},
4066
- }
4067
- nota = ('navegador aberto' if abriu else 'abra o link acima') + (' · copiado' if copiou else '')
4068
- return ('ok', f'OAuth pronto ({nota}) — conclua no navegador ou cole a URL de callback')
4497
+ 'dados': {'url': url, 'state': state, 'abriu': abriu, 'copiou': copiou, 'porta': porta},
4498
+ })
4499
+ nota = ('navegador aberto' if abriu else 'copie ou abra o link') + (' · copiado' if copiou else '')
4500
+ return ('ok', f'OAuth pronto ({nota})')
4069
4501
  self.rodar_tarefa(tarefa, 'iniciando OAuth do Antigravity…')
4070
4502
 
4071
- def tarefa_concluir_antigravity(self, entrada: str):
4503
+ def tarefa_concluir_antigravity(self, entrada: str, state: str = ''):
4072
4504
  porta = self._porta_motor_local()
4073
4505
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=15.0)
4074
- res = kimi.antigravity_completar(entrada, porta=porta)
4506
+ res = kimi.antigravity_completar(entrada, state=state or self._ag_auth_state, porta=porta)
4075
4507
  if not res.get('ok'):
4076
4508
  raise ValueError(res.get('error') or 'falha ao completar OAuth')
4077
4509
  email = res.get('email') or 'conta Google'
4078
- return ('ok', f'Antigravity connected: {email} · use /connect to switch')
4510
+ return ('ok', f'Antigravity connected: {email} · use /model to select')
4079
4511
 
4080
4512
  def tarefa_selecionar_conta_antigravity(self, email: str):
4081
4513
  """Seleciona a conta Google no Antigravity e ativa o provedor se ainda não estiver ativo."""
@@ -4160,19 +4592,46 @@ class Painel:
4160
4592
  url = inicio['auth_url']
4161
4593
  abriu = tui_core.abrir_url_sistema(url)
4162
4594
  copiou = copiar_area_transferencia(url)
4595
+
4596
+ def _copiar_wb():
4597
+ if copiar_area_transferencia(url):
4598
+ self.avisar('link de login copiado', 'ok', 6)
4599
+ else:
4600
+ self.avisar(f'copie manualmente: {url}', 'aviso', 10)
4601
+
4602
+ def _abrir_wb():
4603
+ if tui_core.abrir_url_sistema(url):
4604
+ self.avisar('abrindo no navegador…', 'ok', 6)
4605
+ else:
4606
+ copiar_area_transferencia(url)
4607
+ self.avisar('navegador não abriu — link copiado para colar no browser', 'aviso', 8)
4608
+
4609
+ estado_txt = ('navegador aberto · ' if abriu else 'abra no navegador · ') + (
4610
+ 'link copiado · ' if copiou else ''
4611
+ ) + 'aguardando login…'
4612
+ linhas_wb = [
4613
+ Text('Conclua o login no navegador (celular ou outro PC).', style=TEXTO),
4614
+ Text(tui_core.truncate_vis(url, 66), style=FRACO),
4615
+ Text(''),
4616
+ Text('Copiar link de login'),
4617
+ Text('Abrir no navegador'),
4618
+ Text(''),
4619
+ Text(estado_txt, style=ACENTO2),
4620
+ ]
4621
+ acoes_wb = [
4622
+ None,
4623
+ None,
4624
+ None,
4625
+ {'rotulo': 'Copiar link de login', 'detalhe': 'toque / clique', 'badge': '⎘', 'cor': ACENTO, 'fn': _copiar_wb},
4626
+ {'rotulo': 'Abrir no navegador', 'detalhe': 'browser', 'badge': '↗', 'cor': ACENTO2, 'fn': _abrir_wb},
4627
+ None,
4628
+ None,
4629
+ ]
4163
4630
  self.modal = {
4164
- 'titulo': 'Login WorkBuddy',
4165
- 'linhas': [Text('1. abra o endereço abaixo no navegador'),
4166
- Text(url, style=f'bold {ACENTO2}'),
4167
- Text('pode ser em outro PC ou no celular: o login vale no servidor',
4168
- style=FRACO),
4169
- Text('2. entre com a conta do WorkBuddy (WeChat, QQ, e-mail…)'),
4170
- Text('3. volte aqui: a conta entra sozinha quando o login terminar',
4171
- style=FRACO),
4172
- Text(('navegador aberto · ' if abriu else 'abra o endereço manualmente · ')
4173
- + ('endereço copiado · ' if copiou else '')
4174
- + 'aguardando…', style=FRACO)],
4175
- 'dica': 'Esc fecha o quadro · o login continua em segundo plano',
4631
+ 'titulo': 'Login · WorkBuddy',
4632
+ 'linhas': linhas_wb,
4633
+ 'acoes': acoes_wb,
4634
+ 'dica': 'toque nos botões acima · Esc fecha (login segue em 2º plano)',
4176
4635
  }
4177
4636
  threading.Thread(target=self._concluir_login_workbuddy, args=(inicio,),
4178
4637
  daemon=True, name='workbuddy-login').start()
@@ -4450,8 +4909,9 @@ class Painel:
4450
4909
  dados = w.get('dados') or {}
4451
4910
  url = dados.get('url') or ''
4452
4911
  return [
4453
- Text(url or 'use + Conectar conta Google primeiro', style=ACENTO2),
4454
- Text('cole a URL de callback ou pressione Esc se já concluiu', style=FRACO),
4912
+ Text('1. Abra o link abaixo no navegador e faça login com o Google.', style=TEXTO),
4913
+ Text(tui_core.truncate_vis(url, max(24, self.largura - 10)) if url else 'use + Add account primeiro', style=FRACO),
4914
+ Text('2. Se o retorno não concluir sozinho, cole a URL final e dê Enter.', style=FRACO),
4455
4915
  ]
4456
4916
  if w.get('tipo') == 'add':
4457
4917
  passo = w.get('passo')
@@ -4490,42 +4950,55 @@ class Painel:
4490
4950
  itens_l = dados_l[0] if dados_l else []
4491
4951
  idx = int(escolha) - 1
4492
4952
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4493
- self.wizard = None
4494
4953
  if escolha == 'ag_hub':
4495
- self.abrir_hub_antigravity()
4954
+ self._empilhar_wizard({'tipo': 'ag_hub', 'passo': 'menu', 'titulo': 'Antigravity', 'dados': {}})
4496
4955
  elif escolha == 'nv_ativar':
4956
+ self._pilha().clear()
4957
+ self.wizard = None
4497
4958
  self.acao_trocar_provider('nvidia')
4498
4959
  elif escolha == 'wb_hub':
4499
- self.wizard = {'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}}
4960
+ self._empilhar_wizard({'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}})
4500
4961
  elif escolha == 'oc_ativar':
4962
+ self._pilha().clear()
4963
+ self.wizard = None
4501
4964
  self.acao_trocar_provider('opencode')
4502
4965
  elif escolha == 'oauth_hub':
4503
- self.wizard = {'tipo': 'oauth_hub', 'passo': 'menu',
4504
- 'titulo': 'OAuth', 'dados': {}}
4966
+ self._empilhar_wizard({'tipo': 'oauth_hub', 'passo': 'menu',
4967
+ 'titulo': 'OAuth', 'dados': {}})
4505
4968
  elif escolha.startswith('preset:'):
4506
4969
  slug = escolha.split(':', 1)[1]
4507
4970
  preset = provedores_catalogo.PRESET_POR_SLUG.get(slug)
4508
4971
  if not preset:
4972
+ self.wizard = None
4509
4973
  self.avisar('provedor desconhecido', 'erro')
4510
4974
  elif slug == 'ollama':
4975
+ self._pilha().clear()
4976
+ self.wizard = None
4511
4977
  self.rodar_tarefa(lambda: self.tarefa_conectar_preset(slug, ''),
4512
4978
  'conectando Ollama…')
4513
4979
  else:
4514
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4515
- 'titulo': preset['nome'],
4516
- 'dados': {'destino': slug, 'preset': slug}}
4980
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
4981
+ 'titulo': preset['nome'],
4982
+ 'dados': {'destino': slug, 'preset': slug}})
4517
4983
  elif escolha.startswith('key:'):
4518
4984
  destino = escolha.split(':', 1)[1]
4519
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4520
- 'titulo': destino,
4521
- 'dados': {'destino': destino}}
4985
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
4986
+ 'titulo': destino,
4987
+ 'dados': {'destino': destino}})
4522
4988
  elif escolha == 'custom_add':
4523
- self.abrir_wizard_add()
4989
+ self._empilhar_wizard({'tipo': 'add', 'passo': 'nome', 'titulo': 'Novo provedor',
4990
+ 'dados': {}})
4524
4991
  elif escolha == 'sync_opencode':
4992
+ self._pilha().clear()
4993
+ self.wizard = None
4525
4994
  self.acao_opencode()
4526
4995
  elif escolha.startswith('prov:'):
4996
+ self._pilha().clear()
4997
+ self.wizard = None
4527
4998
  self.acao_trocar_provider(escolha.split(':', 1)[1])
4528
4999
  else:
5000
+ self._pilha().clear()
5001
+ self.wizard = None
4529
5002
  self.avisar('cancelado', 'aviso')
4530
5003
  return
4531
5004
  if tipo in ('connect_api', 'oauth_hub'):
@@ -4561,33 +5034,40 @@ class Painel:
4561
5034
  itens_l = dados_l[0] if dados_l else []
4562
5035
  idx = int(escolha) - 1
4563
5036
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4564
- self.wizard = None
4565
5037
  if escolha == 'ag_login':
4566
5038
  self.iniciar_login_antigravity()
4567
5039
  elif escolha == 'ag_paste':
4568
- self.wizard = {'tipo': 'ag_callback', 'passo': 'colar',
4569
- 'titulo': 'Antigravity · Callback',
4570
- 'dados': {'url': self._ag_auth_url or ''}}
5040
+ self._empilhar_wizard({'tipo': 'ag_callback', 'passo': 'colar',
5041
+ 'titulo': 'Antigravity · Callback',
5042
+ 'dados': {'url': self._ag_auth_url or '', 'state': self._ag_auth_state}})
4571
5043
  elif escolha == 'ag_ativar':
5044
+ self._pilha().clear()
5045
+ self.wizard = None
4572
5046
  self.acao_trocar_provider('antigravity')
4573
5047
  elif escolha.startswith('ag_use:'):
5048
+ self._pilha().clear()
5049
+ self.wizard = None
4574
5050
  email = escolha.split(':', 1)[1]
4575
5051
  self.rodar_tarefa(lambda: self.tarefa_selecionar_conta_antigravity(email),
4576
5052
  f'conectando {email}…')
4577
5053
  elif escolha.startswith('ag_rm:'):
5054
+ self._pilha().clear()
5055
+ self.wizard = None
4578
5056
  email = escolha.split(':', 1)[1]
4579
5057
  self.rodar_tarefa(lambda: self.tarefa_remover_conta_antigravity(email),
4580
5058
  f'removendo {email}…')
4581
5059
  elif escolha == 'voltar_connect':
4582
- self.abrir_hub_connect()
5060
+ self._voltar_wizard()
4583
5061
  return
4584
5062
  if tipo == 'ag_callback':
4585
- self.wizard = None
4586
5063
  entrada = (texto or '').strip()
5064
+ state_atual = (w.get('dados') or {}).get('state') or self._ag_auth_state
5065
+ self._pilha().clear()
5066
+ self.wizard = None
4587
5067
  if not entrada:
4588
5068
  self.avisar('login fechado — se completou no navegador, a conta já está ativa', 'ok')
4589
5069
  return
4590
- self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada),
5070
+ self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada, state=state_atual),
4591
5071
  'concluindo OAuth do Antigravity…')
4592
5072
  return
4593
5073
  if tipo == 'wb_hub':
@@ -4677,18 +5157,43 @@ class Painel:
4677
5157
  f'adicionando {nome or "provedor"}…')
4678
5158
  return
4679
5159
  if tipo == 'model' and passo == 'menu':
5160
+ if texto == 'custom_id':
5161
+ self._empilhar_wizard({'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}})
5162
+ return
5163
+ if texto.startswith('pm:'):
5164
+ _, prov_alvo, mod_alvo = texto.split(':', 2)
5165
+ self._pilha().clear()
5166
+ self.wizard = None
5167
+ self.rodar_tarefa(
5168
+ lambda: self.tarefa_definir_modelo(mod_alvo, provedor_alvo=prov_alvo),
5169
+ f'trocando para {prov_alvo} · {mod_alvo}…',
5170
+ )
5171
+ return
5172
+ entradas = w.get('dados', {}).get('entradas') or []
4680
5173
  modelos = w.get('dados', {}).get('modelos') or []
4681
- if not texto.isdigit() or not 1 <= int(texto) <= len(modelos) + 1:
5174
+ total = len(entradas) if entradas else len(modelos)
5175
+ if not texto.isdigit() or not 1 <= int(texto) <= total + 1:
4682
5176
  self.avisar('escolha um modelo da lista ou informe outro ID', 'aviso')
4683
5177
  return
4684
5178
  indice = int(texto) - 1
4685
- if indice == len(modelos):
4686
- w['passo'] = 'id'
5179
+ if indice == total:
5180
+ self._empilhar_wizard({'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}})
4687
5181
  return
5182
+ if indice < len(entradas):
5183
+ ent = entradas[indice]
5184
+ self._pilha().clear()
5185
+ self.wizard = None
5186
+ self.rodar_tarefa(
5187
+ lambda: self.tarefa_definir_modelo(ent['id'], provedor_alvo=ent['provedor']),
5188
+ f"trocando para {ent['provedor']} · {ent['id']}…",
5189
+ )
5190
+ return
5191
+ self._pilha().clear()
4688
5192
  self.wizard = None
4689
5193
  self.abrir_wizard_modelo(modelos[indice])
4690
5194
  return
4691
5195
  if tipo == 'model' and passo == 'id':
5196
+ self._pilha().clear()
4692
5197
  self.wizard = None
4693
5198
  if texto.strip():
4694
5199
  self.abrir_wizard_modelo(texto)
@@ -4829,9 +5334,18 @@ class Painel:
4829
5334
  if achado:
4830
5335
  return achado
4831
5336
  nome = 'opencode.exe' if os.name == 'nt' else 'opencode'
4832
- local = Path.home() / '.opencode' / 'bin' / nome
4833
- if local.is_file():
4834
- return str(local)
5337
+ prefix = os.environ.get('PREFIX', '')
5338
+ candidatos = [
5339
+ Path.home() / '.opencode' / 'bin' / nome,
5340
+ Path.home() / '.local' / 'bin' / nome,
5341
+ Path.home() / '.bun' / 'bin' / nome,
5342
+ Path.home() / '.npm-global' / 'bin' / nome,
5343
+ ]
5344
+ if prefix:
5345
+ candidatos.append(Path(prefix) / 'bin' / nome)
5346
+ for local in candidatos:
5347
+ if local.is_file():
5348
+ return str(local)
4835
5349
  raise ValueError('OpenCode não encontrado — instale em https://opencode.ai e tente de novo')
4836
5350
 
4837
5351
  def executar_login_oauth_opencode(self, alvo: str, metodo: str):
@@ -4978,40 +5492,189 @@ class Painel:
4978
5492
  prefixo = 'provedor restaurado para' if restaurando else 'provedor ativo agora é'
4979
5493
  return ('ok', f'{prefixo} {nome}{extra}{nota}')
4980
5494
 
5495
+ def _catalogo_unificado_modelos(self, cfg: dict) -> tuple[list[dict], list[str]]:
5496
+ """Monta o catálogo unificado estilo OpenCode Select model (sem precisar de /provider).
5497
+
5498
+ Retorna `(grupos, modelos_do_provedor_ativo)`:
5499
+ - Quando o provedor ativo não é motor local, ele vem no topo (com seus modelos reais).
5500
+ - NVIDIA Playground (Free · sem conta): Kimi K3.1 Pro e MiniMax M3.1 Flash sempre visíveis!
5501
+ - Antigravity (Google OAuth): Gemini 4 Neon/Hydrogen e Claude Opus/Sonnet 5.5.
5502
+ - Demais provedores conectados (com chaves/contas salvas).
5503
+ """
5504
+ grupos: list[dict] = []
5505
+ vistos_prov: set[str] = set()
5506
+ modelos_ativo_lista: list[str] = []
5507
+ ativo = str(cfg.get('provider') or '')
5508
+
5509
+ # 0) Se o provedor ativo for externo/customizado, coloca o catálogo dele primeiro
5510
+ if ativo and ativo not in ('nvidia', 'kimi', 'antigravity'):
5511
+ try:
5512
+ if ativo == 'workbuddy':
5513
+ cat = catalogo_workbuddy(cfg)
5514
+ modelos_ativo_lista = [item['id'] for item in cat if item.get('id')]
5515
+ else:
5516
+ modelos_ativo_lista = consultar_modelos(cfg)
5517
+ except Exception:
5518
+ modelos_ativo_lista = []
5519
+ itens_ativo = [{'id': m, 'rotulo': m, 'detalhe': ''} for m in modelos_ativo_lista[:24]]
5520
+ if not itens_ativo:
5521
+ m_cur = modelo_ativo(cfg)
5522
+ if m_cur:
5523
+ itens_ativo = [{'id': m_cur, 'rotulo': m_cur, 'detalhe': ''}]
5524
+ if itens_ativo:
5525
+ preset = provedores_catalogo.PRESET_POR_SLUG.get(ativo)
5526
+ nome_sec = preset['nome'] if preset else ativo
5527
+ grupos.append({'provedor': ativo, 'secao': nome_sec, 'itens': itens_ativo})
5528
+ vistos_prov.add(ativo)
5529
+
5530
+ # 1) NVIDIA Playground (grátis, sem conta) — sempre visível!
5531
+ grupos.append({
5532
+ 'provedor': 'nvidia',
5533
+ 'secao': 'NVIDIA Playground (Free)',
5534
+ 'itens': [
5535
+ {'id': 'kimi-k3.1-pro', 'rotulo': 'Kimi K3.1 Pro', 'detalhe': 'Free'},
5536
+ {'id': 'minimax-m3.1-flash', 'rotulo': 'MiniMax M3.1 Flash', 'detalhe': 'Free'},
5537
+ ],
5538
+ })
5539
+ vistos_prov.update({'nvidia', 'kimi'})
5540
+ if ativo in ('nvidia', 'kimi'):
5541
+ modelos_ativo_lista = list(kimi.MODELOS_NVIDIA)
5542
+
5543
+ # 2) Antigravity (Google OAuth)
5544
+ snap = getattr(self, '_snap_visto', None) or self.coletor.ler() or {}
5545
+ ag_contas = ((snap.get('ag_status') or {}).get('accounts') or []) if isinstance(snap, dict) else []
5546
+ if ag_contas or ativo == 'antigravity':
5547
+ rotulos_ag = {
5548
+ 'gemini-4-neon': 'Gemini 4 Neon',
5549
+ 'gemini-4-hydrogen': 'Gemini 4 Hydrogen',
5550
+ 'claude-opus-5-5': 'Claude Opus 5.5',
5551
+ 'claude-sonnet-5-5': 'Claude Sonnet 5.5',
5552
+ }
5553
+ tag_ag = f'{len(ag_contas)}c' if ag_contas else 'OAuth'
5554
+ grupos.append({
5555
+ 'provedor': 'antigravity',
5556
+ 'secao': 'Antigravity (Google)',
5557
+ 'itens': [
5558
+ {'id': mid, 'rotulo': rotulos_ag.get(mid, mid), 'detalhe': tag_ag}
5559
+ for mid in kimi.MODELOS_ANTIGRAVITY
5560
+ ],
5561
+ })
5562
+ vistos_prov.add('antigravity')
5563
+ if ativo == 'antigravity':
5564
+ modelos_ativo_lista = list(kimi.MODELOS_ANTIGRAVITY)
5565
+
5566
+ # 3) Demais provedores conectados (com chave/conta salva)
5567
+ if 'unorouter' not in vistos_prov and self._tamanho_pool(cfg, 'unorouter'):
5568
+ grupos.append({
5569
+ 'provedor': 'unorouter',
5570
+ 'secao': 'UnoRouter',
5571
+ 'itens': [{'id': 'deepseek-v4.1-flash:free', 'rotulo': 'deepseek-v4.1-flash:free',
5572
+ 'detalhe': f'{self._tamanho_pool(cfg, "unorouter")}k'}],
5573
+ })
5574
+ vistos_prov.add('unorouter')
5575
+ if 'tokenharbor' not in vistos_prov and self._tamanho_pool(cfg, 'tokenharbor'):
5576
+ grupos.append({
5577
+ 'provedor': 'tokenharbor',
5578
+ 'secao': 'TokenHarbor',
5579
+ 'itens': [{'id': 'deepseek-v4.1-flash:free', 'rotulo': 'deepseek-v4.1-flash:free',
5580
+ 'detalhe': f'{self._tamanho_pool(cfg, "tokenharbor")}k'}],
5581
+ })
5582
+ vistos_prov.add('tokenharbor')
5583
+ if 'workbuddy' not in vistos_prov and self._contas_workbuddy():
5584
+ grupos.append({
5585
+ 'provedor': 'workbuddy',
5586
+ 'secao': 'WorkBuddy',
5587
+ 'itens': [{'id': workbuddy.MODELO_PADRAO, 'rotulo': workbuddy.MODELO_PADRAO,
5588
+ 'detalhe': f'{len(self._contas_workbuddy())}c'}],
5589
+ })
5590
+ vistos_prov.add('workbuddy')
5591
+ if 'opencode' not in vistos_prov:
5592
+ m_oc = str(cfg.get('opencode_model') or 'deepseek-v4.1-flash-free').strip()
5593
+ grupos.append({
5594
+ 'provedor': 'opencode',
5595
+ 'secao': 'OpenCode (Free)',
5596
+ 'itens': [{'id': m_oc, 'rotulo': m_oc, 'detalhe': 'Free'}],
5597
+ })
5598
+ vistos_prov.add('opencode')
5599
+ for nome_p, entrada in sorted((cfg.get('provedores') or {}).items()):
5600
+ if nome_p in vistos_prov or not isinstance(entrada, dict):
5601
+ continue
5602
+ if not (entrada.get('apis') or []):
5603
+ continue
5604
+ preset = provedores_catalogo.PRESET_POR_SLUG.get(nome_p)
5605
+ nome_sec = preset['nome'] if preset else nome_p
5606
+ modelo_p = str(entrada.get('model') or (preset['modelo_padrao'] if preset else '') or '').strip()
5607
+ if not modelo_p:
5608
+ continue
5609
+ grupos.append({
5610
+ 'provedor': nome_p,
5611
+ 'secao': nome_sec,
5612
+ 'itens': [{'id': modelo_p, 'rotulo': modelo_p, 'detalhe': f"{len(entrada.get('apis') or [])}k"}],
5613
+ })
5614
+ return grupos, modelos_ativo_lista
5615
+
4981
5616
  def tarefa_listar_modelos(self):
4982
5617
  cfg = ler_config()
4983
- info = {}
4984
- try:
4985
- if (cfg.get('provider') or '') == 'workbuddy':
4986
- catalogo = catalogo_workbuddy(cfg)
4987
- modelos = [item['id'] for item in catalogo if item.get('id')]
4988
- info = {item['id']: item for item in catalogo if item.get('id')}
4989
- else:
4990
- modelos = consultar_modelos(cfg)
4991
- except ValueError as exc:
4992
- self.wizard = {'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}}
4993
- return ('aviso', f'{exc} · você ainda pode informar o ID manualmente')
4994
- limites = workbuddy.ler_limites(ROOT) if (cfg.get('provider') or '') == 'workbuddy' else {}
4995
- self.wizard = {'tipo': 'model', 'passo': 'menu', 'titulo': 'Modelos do provedor',
4996
- 'dados': {'modelos': modelos, 'info': info, 'limites': limites}}
4997
- return ('ok', f'{len(modelos)} modelo(s) de {cfg.get("provider") or "unorouter"} · escolha na lista')
4998
-
4999
- def tarefa_definir_modelo(self, nome: str):
5618
+ grupos, modelos_ativo_lista = self._catalogo_unificado_modelos(cfg)
5619
+ entradas = []
5620
+ for g in grupos:
5621
+ for it in g['itens']:
5622
+ entradas.append({
5623
+ 'provedor': g['provedor'],
5624
+ 'secao': g['secao'],
5625
+ 'id': it['id'],
5626
+ 'rotulo': it['rotulo'],
5627
+ 'detalhe': it.get('detalhe') or '',
5628
+ })
5629
+ modelos_flat = modelos_ativo_lista or [e['id'] for e in entradas]
5630
+ self.wizard = {
5631
+ 'tipo': 'model',
5632
+ 'passo': 'menu',
5633
+ 'titulo': 'Select model',
5634
+ 'dados': {'modelos': modelos_flat, 'entradas': entradas, 'info': {}, 'limites': {}},
5635
+ }
5636
+ return ('ok', f'{len(entradas)} modelo(s) disponíveis · escolha na lista')
5637
+
5638
+ def tarefa_definir_modelo(self, nome: str, provedor_alvo: str | None = None):
5000
5639
  nome = (nome or '').strip()
5001
5640
  if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/+-]{0,199}', nome):
5002
5641
  raise ValueError('informe o ID do modelo, sem espacos: /model ID')
5003
5642
  cfg = ler_config()
5643
+ prov_anterior = str(cfg.get('provider') or '')
5644
+ prov_destino = (provedor_alvo or prov_anterior or 'nvidia').strip().lower()
5645
+ # Compatibilidade: kimi legado e nvidia apontam para o mesmo motor local
5646
+ if prov_destino == 'nvidia' and prov_anterior == 'kimi':
5647
+ prov_destino = 'nvidia'
5004
5648
  atual = modelo_ativo(cfg)
5005
- if nome == atual:
5649
+ if nome == atual and prov_destino == prov_anterior:
5006
5650
  return ('aviso', f'o modelo ativo já é {nome}')
5007
5651
  cfg_anterior = copy.deepcopy(cfg)
5652
+ # Se mudou de provedor junto com o modelo (estilo OpenCode /models), garante bloco do motor
5653
+ if prov_destino != prov_anterior:
5654
+ if prov_destino in ('nvidia', 'kimi', 'antigravity'):
5655
+ provs = cfg.setdefault('provedores', {})
5656
+ base_padrao = f'http://127.0.0.1:{kimi.PORTA_PADRAO}/v1'
5657
+ if prov_destino not in provs or not isinstance(provs.get(prov_destino), dict):
5658
+ provs[prov_destino] = {
5659
+ 'base_url': base_padrao,
5660
+ 'model': nome,
5661
+ 'apis': [{'name': f'{prov_destino}-local', 'key_env': ''}],
5662
+ }
5663
+ else:
5664
+ provs[prov_destino]['model'] = nome
5665
+ cfg['provider'] = prov_destino
5008
5666
  if cfg.get('provider') == 'opencode':
5009
5667
  cfg['opencode_model'] = nome
5010
5668
  cfg['model_enviado'] = ''
5011
5669
  else:
5012
5670
  cfg['upstream_model'] = nome
5013
5671
  cfg['model_enviado'] = nome
5014
- # Valida se o nível de raciocínio atual existe no novo modelo
5672
+ if cfg.get('provider') in ('nvidia', 'kimi', 'antigravity'):
5673
+ provs = cfg.setdefault('provedores', {})
5674
+ if isinstance(provs.get(cfg['provider']), dict):
5675
+ provs[cfg['provider']]['model'] = nome
5676
+ # Ajusta automaticamente o esforço para o teto aceito pelo modelo novo se
5677
+ # o esforço anterior não existir nesse modelo (evita travar troca de modelo).
5015
5678
  aviso_esforco = ''
5016
5679
  prov = str(cfg.get('provider') or '')
5017
5680
  if prov in ('kimi', 'nvidia', 'antigravity'):
@@ -5022,15 +5685,15 @@ class Painel:
5022
5685
  or 'max'
5023
5686
  ).strip().lower()
5024
5687
  if esforco_atual not in aceitos:
5025
- raise ValueError(
5026
- f'{nome} não suporta "{esforco_atual}" — aceita {", ".join(aceitos)} (use /effort {aceitos[-1]} antes)'
5027
- )
5688
+ novo_eff = aceitos[-1]
5689
+ cfg.setdefault('esforco_modelos', {}).setdefault(prov, {})[nome] = novo_eff
5690
+ aviso_esforco = f' · effort {novo_eff}'
5028
5691
  gravar_config_com_contexto(cfg)
5029
5692
  if self.bridge_online():
5030
5693
  extra = self._reiniciar_bridge_seguro(cfg_anterior)
5031
5694
  else:
5032
5695
  extra = ' · vale na próxima partida do bridge'
5033
- return ('ok', f'modelo ativo agora é {nome}{extra}{aviso_esforco}')
5696
+ return ('ok', f'{prov} · {nome}{aviso_esforco}{extra}')
5034
5697
 
5035
5698
  def tarefa_definir_contexto(self, tamanho: str, esperado=None):
5036
5699
  tokens = contexto.parse_contexto(tamanho)