krnell 3.0.4 → 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
@@ -1145,6 +1145,8 @@ class Painel:
1145
1145
  self._wizard_item_linhas = {} # linha do wizard -> indice do item
1146
1146
  self._modal_ini = None # linha do frame do 1o item do modal (clique copia)
1147
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)
1148
1150
  self._copiar_zona = None # colunas do botao copiar do rodape (clique)
1149
1151
  self._copiar_hover = False # mouse em cima do botao copiar
1150
1152
  self._status_y = None # linha (0-based) da barra de status
@@ -1160,8 +1162,11 @@ class Painel:
1160
1162
  self._term_posix = None # tui_core.TerminalPosix no Termux/Linux/macOS
1161
1163
  self._overlay_top = None
1162
1164
  self._overlay_left = None
1165
+ self._overlay_width = 0
1166
+ self._overlay_height = 0
1163
1167
  self._overlay_clique = {} # y_relativo -> indice do item no overlay centrado
1164
1168
  self._ag_auth_url = None
1169
+ self._ag_auth_state = ''
1165
1170
  self._anim_tick = 0
1166
1171
  self._anim_ultimo = 0.0
1167
1172
  self._dialogo_frame = 0 # animacao de abertura do dialogo
@@ -1287,12 +1292,12 @@ class Painel:
1287
1292
  estado.append(' ' if largura < 52 else ' ')
1288
1293
  if online:
1289
1294
  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'
1295
+ rot_on = f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} live' if largura < 54 else f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working'
1291
1296
  estado.append(rot_on, style=ACENTO2)
1292
1297
  else:
1293
- estado.append('● on' if largura < 38 else '● online', style=OK)
1298
+ estado.append('● on' if largura < 40 else '● online', style=OK)
1294
1299
  else:
1295
- estado.append('○ off' if largura < 38 else '○ offline', style=ERRO)
1300
+ estado.append('○ off' if largura < 40 else '○ offline', style=ERRO)
1296
1301
  if rotulo_update:
1297
1302
  inicio = max(0, largura - cell_len(estado.plain))
1298
1303
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
@@ -1330,9 +1335,9 @@ class Painel:
1330
1335
  show_header=False, pad_edge=False)
1331
1336
  if not ultra_estreito:
1332
1337
  tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1333
- tabela.add_column(width=5, no_wrap=True)
1338
+ tabela.add_column(width=6, no_wrap=True)
1334
1339
  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)
1340
+ tabela.add_column(width=6 if ultra_estreito else 7, justify='right', no_wrap=True)
1336
1341
  if not estreito:
1337
1342
  tabela.add_column(width=9, justify='right', no_wrap=True)
1338
1343
  tabela.add_column(width=14, no_wrap=True, overflow='ellipsis')
@@ -1445,9 +1450,14 @@ class Painel:
1445
1450
 
1446
1451
  def _info_compacta(self, snap, online, status, cfg, provedor) -> list:
1447
1452
  """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))
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))
1449
1459
  primeira = Text(no_wrap=True, overflow='ellipsis')
1450
- primeira.append(provedor, style=f'bold {ACENTO}')
1460
+ primeira.append(provedor_exib, style=f'bold {ACENTO}')
1451
1461
  primeira.append(f' {modelo}', style=TEXTO)
1452
1462
  var = variante_ativa(cfg, provedor)
1453
1463
  if cell_len(primeira.plain) + len(var) + 5 <= self.largura:
@@ -1495,7 +1505,9 @@ class Painel:
1495
1505
  if self.modal or self.wizard:
1496
1506
  direita = [(' esc back ', 'fraco', None, 'ess'), botao]
1497
1507
  else:
1498
- direita = [(' ctrl+p commands · ctrl+l connect ', 'fraco', None, 'extra'), botao]
1508
+ direita = [(' commands ', 'fraco', None, 'extra'),
1509
+ (' connect ', 'acento2', None, 'nor'),
1510
+ botao]
1499
1511
  return esquerda, direita
1500
1512
 
1501
1513
  def _barra_status(self) -> str:
@@ -1524,11 +1536,31 @@ class Painel:
1524
1536
  acumulado += w
1525
1537
  espaco = max(1, self.largura - acumulado - larg_dir)
1526
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
1527
1550
  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)
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
1532
1564
  return pintar_segmentos(cortados) + ' ' * espaco + pintar_segmentos(dr)
1533
1565
 
1534
1566
  def _texto_status_rich(self, snap=None) -> Text:
@@ -1598,7 +1630,7 @@ class Painel:
1598
1630
 
1599
1631
  def _limite_menu(self) -> int:
1600
1632
  """Quantos itens do menu cabem sem apertar o resto do painel."""
1601
- return max(3, min(10, self.altura - 16))
1633
+ return max(3, min(10, self.altura - 10))
1602
1634
 
1603
1635
  def _sel_menu(self) -> int:
1604
1636
  """Indice do item destacado, ja preso a lista atual de candidatos."""
@@ -1654,7 +1686,7 @@ class Painel:
1654
1686
  fundo elevado e barra de destaque no item escolhido."""
1655
1687
  if not self._menu_aberto():
1656
1688
  return []
1657
- interno = max(8, self.largura - 4) # o vao entre os trilhos ┃
1689
+ interno = max(14, self.largura - 4) # o vao entre os trilhos ┃
1658
1690
 
1659
1691
  def com_trilhos(miolo: Text) -> Text:
1660
1692
  t = Text()
@@ -1665,25 +1697,30 @@ class Painel:
1665
1697
 
1666
1698
  candidatos = self._candidatos_menu()
1667
1699
  if not candidatos:
1668
- return [com_trilhos(Text(' ' + 'nenhum comando corresponde'.ljust(interno - 1),
1669
- 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}'))]
1670
1702
  inicio, visiveis = self._janela_menu()
1671
1703
  destaque = self._sel_menu() - inicio
1672
- 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))
1673
1705
  linhas = []
1674
1706
  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}'
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)
1678
1712
  t = Text()
1679
1713
  if posicao == destaque:
1680
1714
  # o item que o Enter/Tab executa ou o clique escolhe
1681
- t.append(miolo.ljust(interno), style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1715
+ t.append(miolo_fixo, style=f'bold {TEXTO_ACENTO} on {ACENTO}')
1682
1716
  else:
1683
1717
  t.append(' ', style=f'on {FUNDO}')
1684
1718
  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}')
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}')
1687
1724
  linhas.append(com_trilhos(t))
1688
1725
  acima = inicio
1689
1726
  abaixo = len(candidatos) - (inicio + len(visiveis))
@@ -1693,10 +1730,8 @@ class Painel:
1693
1730
  pedacos.append(f'+{acima} acima')
1694
1731
  if abaixo:
1695
1732
  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}')))
1733
+ texto = tui_core.pad_vis(f" … {' · '.join(pedacos)}", interno)
1734
+ linhas.append(com_trilhos(Text(texto, style=f'{FRACO} on {FUNDO}')))
1700
1735
  return linhas
1701
1736
 
1702
1737
  def _registrar_menu(self, frame: list, cortado: bool = False) -> None:
@@ -1723,14 +1758,23 @@ class Painel:
1723
1758
  return None
1724
1759
 
1725
1760
  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:
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:
1729
1764
  return False
1730
- self.buf = self._candidatos_menu()[indice][0]
1731
- self.menu_sel = indice
1732
- self.ao_enter()
1733
- 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
1734
1778
 
1735
1779
  def roda_mouse(self, sentido: int) -> bool:
1736
1780
  """Roda: rola a janela do menu e a selecao se reajusta (como no OpenCode);
@@ -1745,24 +1789,43 @@ class Painel:
1745
1789
  if candidatos:
1746
1790
  limite = self._limite_menu()
1747
1791
  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()))
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))
1752
1805
  return True
1753
1806
  if self.wizard and self._wizard_lista():
1754
1807
  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()))
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))
1761
1823
  return True
1762
1824
  snap = self.coletor.ler()
1763
1825
  reqs = snap.get('requests') or []
1764
1826
  visiveis = max(1, getattr(self, '_reqs_visiveis', 10))
1765
- 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)))
1766
1829
  return True
1767
1830
 
1768
1831
  def completar_menu(self) -> bool:
@@ -1823,18 +1886,18 @@ class Painel:
1823
1886
  n_un = self._tamanho_pool(cfg, 'unorouter')
1824
1887
  n_th = self._tamanho_pool(cfg, 'tokenharbor')
1825
1888
  itens = [
1826
- ('Antigravity', 'ag_hub', f'{len(ag_contas)}c' if ag_contas else 'OAuth'),
1827
- ('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'),
1828
1892
  ('WorkBuddy', 'wb_hub', f'{n_wb}c' if n_wb else 'Login'),
1829
- ('OpenCode', 'oc_ativar', 'Free'),
1830
1893
  ('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'),
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'),
1833
1896
  ]
1834
1897
  for preset in provedores_catalogo.PROVEDORES_API_PRESETS:
1835
1898
  slug = preset['slug']
1836
1899
  n_c = self._tamanho_pool(cfg, slug)
1837
- 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')
1838
1901
  itens.append((preset['nome'], f'preset:{slug}', det))
1839
1902
  slugs_padrao = {'workbuddy', 'kimi', 'nvidia', 'antigravity'} | set(provedores_catalogo.PRESET_POR_SLUG)
1840
1903
  for nome_p in sorted((cfg.get('provedores') or {}).keys()):
@@ -1842,14 +1905,14 @@ class Painel:
1842
1905
  continue
1843
1906
  n_c = self._tamanho_pool(cfg, nome_p)
1844
1907
  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', ''))
1908
+ itens.append(('Sync OpenCode', 'sync_opencode', 'models + plugin'))
1909
+ itens.append(('+ Custom provider', 'custom_add', 'base URL + key'))
1847
1910
  mapa_atual = {
1848
- 'antigravity': 'ag_hub',
1849
1911
  'nvidia': 'nv_ativar',
1850
1912
  'kimi': 'nv_ativar',
1851
- 'workbuddy': 'wb_hub',
1913
+ 'antigravity': 'ag_hub',
1852
1914
  'opencode': 'oc_ativar',
1915
+ 'workbuddy': 'wb_hub',
1853
1916
  'unorouter': 'key:unorouter',
1854
1917
  'tokenharbor': 'key:tokenharbor',
1855
1918
  }
@@ -1920,6 +1983,23 @@ class Painel:
1920
1983
  return itens, 0
1921
1984
  if tipo == 'model':
1922
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
1923
2003
  modelos = dados.get('modelos') or []
1924
2004
  info = dados.get('info') or {}
1925
2005
  total_contas = len(workbuddy.ler_contas(ROOT)) or 0
@@ -1943,7 +2023,6 @@ class Painel:
1943
2023
  partes.append(marca + (f' (~{horas:.0f}h)' if horas else ''))
1944
2024
  itens.append((modelo, str(i), ' · '.join(partes)))
1945
2025
  itens.append(('informar outro ID…', str(len(modelos) + 1), '/model ID'))
1946
- atual = modelo_ativo(cfg)
1947
2026
  indice = indice_modelo_ativo(modelos, atual)
1948
2027
  return itens, indice
1949
2028
  if tipo == 'esforco':
@@ -2064,7 +2143,9 @@ class Painel:
2064
2143
  Usa o mapa gravado no desenho (_wizard_item_linhas): assim cabecalho,
2065
2144
  descricao e rodape nao deslocam o clique nem o hover.
2066
2145
  """
2067
- 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'):
2068
2149
  return None
2069
2150
  return getattr(self, '_wizard_item_linhas', {}).get(y - self._wizard_ini)
2070
2151
 
@@ -2090,11 +2171,31 @@ class Painel:
2090
2171
  return topo, itens[topo:topo + limite]
2091
2172
 
2092
2173
  def clicar_wizard(self, y: int) -> bool:
2093
- """Clique num item da lista do wizard: destaca e confirma (mouseUp)."""
2174
+ """Clique/toque num item ou botão do wizard."""
2094
2175
  indice = self.indice_wizard_no_clique(y)
2095
2176
  if indice is None:
2096
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
2097
2196
  lista = self._itens_wizard_filtrados()
2197
+ if not (0 <= indice < len(lista)):
2198
+ return False
2098
2199
  self.wizard['sel'] = indice
2099
2200
  self.buf = ''
2100
2201
  self.passo_wizard(lista[indice][1])
@@ -2124,8 +2225,14 @@ class Painel:
2124
2225
  idx_sel = self._overlay_clique.get(y - self._modal_ini)
2125
2226
  if idx_sel is None:
2126
2227
  return None
2228
+ acoes = (self.modal or {}).get('acoes') or []
2127
2229
  copias = (self.modal or {}).get('copias') or []
2128
- 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
+ ]
2129
2236
  return validos[idx_sel] if 0 <= idx_sel < len(validos) else None
2130
2237
  posicao = y - self._modal_ini
2131
2238
  linhas = (self.modal or {}).get('linhas') or []
@@ -2134,10 +2241,17 @@ class Painel:
2134
2241
  return None
2135
2242
 
2136
2243
  def clicar_modal(self, y: int) -> bool:
2137
- """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."""
2138
2245
  indice = self.indice_modal_no_clique(y)
2139
2246
  if indice is None:
2140
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
2141
2255
  copias = (self.modal or {}).get('copias') or []
2142
2256
  alvo = copias[indice] if indice < len(copias) else None
2143
2257
  if not alvo:
@@ -2163,6 +2277,137 @@ class Painel:
2163
2277
  return f'http://{nome}.local{sufixo}/v1'
2164
2278
  return f'http://127.0.0.1{sufixo}/v1'
2165
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
+
2166
2411
  def ponto_no_botao_copiar(self, x: int, y: int) -> bool:
2167
2412
  """O ponto (x, y) do terminal está sobre o botão copiar do rodapé?"""
2168
2413
  zona = self._copiar_zona
@@ -2312,8 +2557,13 @@ class Painel:
2312
2557
  buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2313
2558
  self._status_y = base + 3
2314
2559
  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')
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')
2317
2567
  saida.write(''.join(buf))
2318
2568
  saida.flush()
2319
2569
 
@@ -2366,23 +2616,37 @@ class Painel:
2366
2616
 
2367
2617
  if self.modal:
2368
2618
  titulo = str(self.modal.get('titulo') or 'Detalhes')
2369
- dica = str(self.modal.get('dica') or 'Enter ou Esc fecha')
2619
+ dica = str(self.modal.get('dica') or 'Esc voltar')
2370
2620
  linhas_mod = self.modal.get('linhas') or []
2371
2621
  copias = self.modal.get('copias') or []
2622
+ acoes = self.modal.get('acoes') or []
2372
2623
  itens = []
2373
2624
  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)})
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})
2378
2642
  else:
2379
- itens.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO})
2380
- limite_mod = max(2, min(len(itens), max(2, self.altura - 9)))
2643
+ itens.append({'tipo': 'texto', 'rotulo': str(l), 'cor': TEXTO})
2644
+ limite_mod = max(3, min(len(itens), max(3, self.altura - 8)))
2381
2645
  rich_lines, mapa_clique = tui_core.construir_dialogo_opencode(
2382
2646
  titulo=titulo,
2383
2647
  largura_caixa=w_box,
2384
2648
  itens=itens,
2385
- foco=-1,
2649
+ foco=0 if acoes else -1,
2386
2650
  topo=0,
2387
2651
  limite=limite_mod,
2388
2652
  rodape=dica,
@@ -2402,11 +2666,13 @@ class Painel:
2402
2666
  # Agrupa discretamente em 3 seções limpas (estilo OpenCode)
2403
2667
  itens_dlg = []
2404
2668
  def _secao_de(chave: str) -> str:
2405
- if chave in ('ag_hub', 'nv_ativar', 'wb_hub', 'oc_ativar', 'oauth_hub'):
2406
- 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'
2407
2673
  if chave in ('sync_opencode', 'custom_add'):
2408
2674
  return 'More'
2409
- return 'API Providers'
2675
+ return 'API Keys'
2410
2676
  sec_ant = None
2411
2677
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2412
2678
  for rotulo, chave, detalhe in filtrados:
@@ -2429,6 +2695,31 @@ class Painel:
2429
2695
  'ativo': eh_atual,
2430
2696
  'chave': chave,
2431
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
+ })
2432
2723
  else:
2433
2724
  chave_atual = itens_raw[dados[1]][1] if dados and dados[1] is not None and dados[1] < len(itens_raw) else None
2434
2725
  itens_dlg = []
@@ -2473,8 +2764,29 @@ class Painel:
2473
2764
  mascarar = bool(w.get('passo') in ('chave', 'segredo'))
2474
2765
  itens_txt = []
2475
2766
  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})
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
+ })
2478
2790
  # Placeholder minimalista conforme o passo
2479
2791
  passo_w = w.get('passo')
2480
2792
  placeholder_w = {
@@ -2493,7 +2805,7 @@ class Painel:
2493
2805
  limite=max(8, len(itens_txt)),
2494
2806
  busca=self.buf,
2495
2807
  placeholder=placeholder_w,
2496
- rodape='Enter confirma · Esc cancela',
2808
+ rodape='Enter confirma · Esc voltar',
2497
2809
  cores=cores,
2498
2810
  mascarar_busca=mascarar,
2499
2811
  mostrar_busca=True,
@@ -2569,6 +2881,8 @@ class Painel:
2569
2881
  self._cache_frame_base = (chave_base, list(frame), cortado)
2570
2882
  self._overlay_top = None
2571
2883
  self._overlay_left = None
2884
+ self._overlay_width = 0
2885
+ self._overlay_height = 0
2572
2886
  self._overlay_clique = {}
2573
2887
  # Quando um diálogo novo abre na TUI, anima brevemente a revelação (slide/expand)
2574
2888
  # Em telas pequenas/estreitas (Termux/celular) ou após resize, pula o slide para
@@ -2607,14 +2921,16 @@ class Painel:
2607
2921
  )
2608
2922
  self._overlay_top = top
2609
2923
  self._overlay_left = left
2924
+ self._overlay_width = _w_box
2925
+ self._overlay_height = len(caixa_vis)
2610
2926
  self._overlay_clique = mapa_clique
2611
2927
  self._menu_ini = None
2612
- if self.wizard and self._wizard_lista():
2928
+ if self.wizard and (self._wizard_lista() or self.wizard.get('tipo') == 'ag_callback'):
2613
2929
  self._wizard_ini = top
2614
2930
  self._wizard_item_linhas = mapa_clique
2615
2931
  else:
2616
2932
  self._wizard_ini = None
2617
- if self.modal and self.modal.get('copias'):
2933
+ if self.modal and (self.modal.get('copias') or self.modal.get('acoes')):
2618
2934
  self._modal_ini = top
2619
2935
  else:
2620
2936
  self._modal_ini = None
@@ -2927,9 +3243,19 @@ class Painel:
2927
3243
  self._reexec_solicitado = False
2928
3244
  self.atualizar_tela()
2929
3245
  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()
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 = ''
2933
3259
  self.atualizar_tela()
2934
3260
  return
2935
3261
  if tecla == 'ctrl_m':
@@ -2963,12 +3289,24 @@ class Painel:
2963
3289
  redesenhar = True
2964
3290
  elif self.clicar_botao_copiar(tecla[1], tecla[2]):
2965
3291
  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])
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
2970
3308
  else:
2971
- redesenhar = self.clicar_menu(tecla[2])
3309
+ redesenhar = self.clicar_barra_home(tecla[1], tecla[2])
2972
3310
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_move':
2973
3311
  redesenhar = self.passar_mouse(tecla[1], tecla[2])
2974
3312
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_roda':
@@ -3898,35 +4236,57 @@ class Painel:
3898
4236
  ag_contas = ag_st.get('accounts') or []
3899
4237
  if ag_contas:
3900
4238
  linhas.append(Text(''))
3901
- linhas.append(Text('antigravity (5h · semanal)', style=FRACO))
4239
+ linhas.append(Text('ANTIGRAVITY (5h · 7d)', style=f'bold {ACENTO2}'))
3902
4240
  for acc in ag_contas:
3903
4241
  email = str(acc.get('email') or 'Google')
3904
4242
  ativa = bool(acc.get('active'))
3905
4243
  t = Text()
3906
4244
  t.append('● ' if ativa else '○ ', style=OK if ativa else FRACO)
3907
- t.append(email, style=TEXTO if ativa else FRACO)
4245
+ t.append(email, style=f'bold {TEXTO}' if ativa else FRACO)
3908
4246
  tier = acc.get('paidTierName') or ''
3909
4247
  if tier:
3910
- t.append(f' · {tier}', style=FRACO)
4248
+ t.append(f' · {tier}', style=FRACO)
3911
4249
  linhas.append(t)
3912
4250
  q_acc = acc.get('quota') if isinstance(acc.get('quota'), dict) else (
3913
4251
  ag_st.get('quota') if ativa and isinstance(ag_st.get('quota'), dict) else {})
4252
+ estreito_q = self.largura < 68
3914
4253
  for item_q in _resumo_cota_antigravity({'quota': q_acc}):
3915
- tq = Text()
3916
- tq.append(f" {item_q['nome']:<8}", style=FRACO)
3917
4254
  b5 = item_q.get('b5h')
3918
4255
  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)
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)
3930
4290
  contas_wb = self._contas_workbuddy()
3931
4291
  if contas_wb:
3932
4292
  linhas.append(Text(''))
@@ -3974,7 +4334,7 @@ class Painel:
3974
4334
  style=FRACO))
3975
4335
  linhas.append(Text('o bridge soma sozinho a cada resposta; cotas 5h/7d revalidam ao vivo.', style=FRACO))
3976
4336
  self.modal = {'tipo': 'tokens', 'titulo': 'Quotas & tokens', 'linhas': linhas,
3977
- 'dica': 'live · Enter ou Esc fecha', 'revisao': self.coletor.revisao}
4337
+ 'dica': 'live · Esc ou toque fora fecha', 'revisao': self.coletor.revisao}
3978
4338
 
3979
4339
  def mostrar_stats(self, arg: str = ''):
3980
4340
  itens = ler_requisicoes(3000, linhas_max=3000)
@@ -4079,6 +4439,7 @@ class Painel:
4079
4439
 
4080
4440
  def abrir_hub_connect(self, arg: str = ''):
4081
4441
  """Hub unificado /connect: provedores, OAuth (Antigravity/WorkBuddy), chaves e OpenCode."""
4442
+ self._pilha().clear()
4082
4443
  alvo = (arg or '').strip().lower()
4083
4444
  if alvo in ('antigravity', 'ag', 'google'):
4084
4445
  self.abrir_hub_antigravity()
@@ -4120,32 +4481,33 @@ class Painel:
4120
4481
  return kimi.PORTA_PADRAO
4121
4482
 
4122
4483
  def iniciar_login_antigravity(self):
4123
- """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)."""
4124
4485
  def tarefa():
4125
4486
  porta = self._porta_motor_local()
4126
4487
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=18.0)
4127
- url = kimi.antigravity_login_url(porta)
4488
+ url, state = kimi.antigravity_login_url(porta)
4128
4489
  abriu = tui_core.abrir_url_sistema(url)
4129
4490
  copiou = copiar_area_transferencia(url)
4130
4491
  self._ag_auth_url = url
4131
- self.wizard = {
4492
+ self._ag_auth_state = state
4493
+ self._empilhar_wizard({
4132
4494
  'tipo': 'ag_callback',
4133
4495
  'passo': 'colar',
4134
4496
  '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')
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})')
4139
4501
  self.rodar_tarefa(tarefa, 'iniciando OAuth do Antigravity…')
4140
4502
 
4141
- def tarefa_concluir_antigravity(self, entrada: str):
4503
+ def tarefa_concluir_antigravity(self, entrada: str, state: str = ''):
4142
4504
  porta = self._porta_motor_local()
4143
4505
  kimi.garantir_motor_ativo(ROOT, porta=porta, timeout=15.0)
4144
- res = kimi.antigravity_completar(entrada, porta=porta)
4506
+ res = kimi.antigravity_completar(entrada, state=state or self._ag_auth_state, porta=porta)
4145
4507
  if not res.get('ok'):
4146
4508
  raise ValueError(res.get('error') or 'falha ao completar OAuth')
4147
4509
  email = res.get('email') or 'conta Google'
4148
- return ('ok', f'Antigravity connected: {email} · use /connect to switch')
4510
+ return ('ok', f'Antigravity connected: {email} · use /model to select')
4149
4511
 
4150
4512
  def tarefa_selecionar_conta_antigravity(self, email: str):
4151
4513
  """Seleciona a conta Google no Antigravity e ativa o provedor se ainda não estiver ativo."""
@@ -4230,19 +4592,46 @@ class Painel:
4230
4592
  url = inicio['auth_url']
4231
4593
  abriu = tui_core.abrir_url_sistema(url)
4232
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
+ ]
4233
4630
  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',
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)',
4246
4635
  }
4247
4636
  threading.Thread(target=self._concluir_login_workbuddy, args=(inicio,),
4248
4637
  daemon=True, name='workbuddy-login').start()
@@ -4520,8 +4909,9 @@ class Painel:
4520
4909
  dados = w.get('dados') or {}
4521
4910
  url = dados.get('url') or ''
4522
4911
  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),
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),
4525
4915
  ]
4526
4916
  if w.get('tipo') == 'add':
4527
4917
  passo = w.get('passo')
@@ -4560,42 +4950,55 @@ class Painel:
4560
4950
  itens_l = dados_l[0] if dados_l else []
4561
4951
  idx = int(escolha) - 1
4562
4952
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4563
- self.wizard = None
4564
4953
  if escolha == 'ag_hub':
4565
- self.abrir_hub_antigravity()
4954
+ self._empilhar_wizard({'tipo': 'ag_hub', 'passo': 'menu', 'titulo': 'Antigravity', 'dados': {}})
4566
4955
  elif escolha == 'nv_ativar':
4956
+ self._pilha().clear()
4957
+ self.wizard = None
4567
4958
  self.acao_trocar_provider('nvidia')
4568
4959
  elif escolha == 'wb_hub':
4569
- self.wizard = {'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}}
4960
+ self._empilhar_wizard({'tipo': 'wb_hub', 'passo': 'menu', 'titulo': 'WorkBuddy', 'dados': {}})
4570
4961
  elif escolha == 'oc_ativar':
4962
+ self._pilha().clear()
4963
+ self.wizard = None
4571
4964
  self.acao_trocar_provider('opencode')
4572
4965
  elif escolha == 'oauth_hub':
4573
- self.wizard = {'tipo': 'oauth_hub', 'passo': 'menu',
4574
- 'titulo': 'OAuth', 'dados': {}}
4966
+ self._empilhar_wizard({'tipo': 'oauth_hub', 'passo': 'menu',
4967
+ 'titulo': 'OAuth', 'dados': {}})
4575
4968
  elif escolha.startswith('preset:'):
4576
4969
  slug = escolha.split(':', 1)[1]
4577
4970
  preset = provedores_catalogo.PRESET_POR_SLUG.get(slug)
4578
4971
  if not preset:
4972
+ self.wizard = None
4579
4973
  self.avisar('provedor desconhecido', 'erro')
4580
4974
  elif slug == 'ollama':
4975
+ self._pilha().clear()
4976
+ self.wizard = None
4581
4977
  self.rodar_tarefa(lambda: self.tarefa_conectar_preset(slug, ''),
4582
4978
  'conectando Ollama…')
4583
4979
  else:
4584
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4585
- 'titulo': preset['nome'],
4586
- 'dados': {'destino': slug, 'preset': slug}}
4980
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
4981
+ 'titulo': preset['nome'],
4982
+ 'dados': {'destino': slug, 'preset': slug}})
4587
4983
  elif escolha.startswith('key:'):
4588
4984
  destino = escolha.split(':', 1)[1]
4589
- self.wizard = {'tipo': 'api', 'passo': 'chave',
4590
- 'titulo': destino,
4591
- 'dados': {'destino': destino}}
4985
+ self._empilhar_wizard({'tipo': 'api', 'passo': 'chave',
4986
+ 'titulo': destino,
4987
+ 'dados': {'destino': destino}})
4592
4988
  elif escolha == 'custom_add':
4593
- self.abrir_wizard_add()
4989
+ self._empilhar_wizard({'tipo': 'add', 'passo': 'nome', 'titulo': 'Novo provedor',
4990
+ 'dados': {}})
4594
4991
  elif escolha == 'sync_opencode':
4992
+ self._pilha().clear()
4993
+ self.wizard = None
4595
4994
  self.acao_opencode()
4596
4995
  elif escolha.startswith('prov:'):
4996
+ self._pilha().clear()
4997
+ self.wizard = None
4597
4998
  self.acao_trocar_provider(escolha.split(':', 1)[1])
4598
4999
  else:
5000
+ self._pilha().clear()
5001
+ self.wizard = None
4599
5002
  self.avisar('cancelado', 'aviso')
4600
5003
  return
4601
5004
  if tipo in ('connect_api', 'oauth_hub'):
@@ -4631,33 +5034,40 @@ class Painel:
4631
5034
  itens_l = dados_l[0] if dados_l else []
4632
5035
  idx = int(escolha) - 1
4633
5036
  escolha = itens_l[idx][1] if 0 <= idx < len(itens_l) else ''
4634
- self.wizard = None
4635
5037
  if escolha == 'ag_login':
4636
5038
  self.iniciar_login_antigravity()
4637
5039
  elif escolha == 'ag_paste':
4638
- self.wizard = {'tipo': 'ag_callback', 'passo': 'colar',
4639
- 'titulo': 'Antigravity · Callback',
4640
- '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}})
4641
5043
  elif escolha == 'ag_ativar':
5044
+ self._pilha().clear()
5045
+ self.wizard = None
4642
5046
  self.acao_trocar_provider('antigravity')
4643
5047
  elif escolha.startswith('ag_use:'):
5048
+ self._pilha().clear()
5049
+ self.wizard = None
4644
5050
  email = escolha.split(':', 1)[1]
4645
5051
  self.rodar_tarefa(lambda: self.tarefa_selecionar_conta_antigravity(email),
4646
5052
  f'conectando {email}…')
4647
5053
  elif escolha.startswith('ag_rm:'):
5054
+ self._pilha().clear()
5055
+ self.wizard = None
4648
5056
  email = escolha.split(':', 1)[1]
4649
5057
  self.rodar_tarefa(lambda: self.tarefa_remover_conta_antigravity(email),
4650
5058
  f'removendo {email}…')
4651
5059
  elif escolha == 'voltar_connect':
4652
- self.abrir_hub_connect()
5060
+ self._voltar_wizard()
4653
5061
  return
4654
5062
  if tipo == 'ag_callback':
4655
- self.wizard = None
4656
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
4657
5067
  if not entrada:
4658
5068
  self.avisar('login fechado — se completou no navegador, a conta já está ativa', 'ok')
4659
5069
  return
4660
- self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada),
5070
+ self.rodar_tarefa(lambda: self.tarefa_concluir_antigravity(entrada, state=state_atual),
4661
5071
  'concluindo OAuth do Antigravity…')
4662
5072
  return
4663
5073
  if tipo == 'wb_hub':
@@ -4747,18 +5157,43 @@ class Painel:
4747
5157
  f'adicionando {nome or "provedor"}…')
4748
5158
  return
4749
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 []
4750
5173
  modelos = w.get('dados', {}).get('modelos') or []
4751
- 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:
4752
5176
  self.avisar('escolha um modelo da lista ou informe outro ID', 'aviso')
4753
5177
  return
4754
5178
  indice = int(texto) - 1
4755
- if indice == len(modelos):
4756
- w['passo'] = 'id'
5179
+ if indice == total:
5180
+ self._empilhar_wizard({'tipo': 'model', 'passo': 'id', 'titulo': 'Trocar modelo', 'dados': {}})
4757
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()
4758
5192
  self.wizard = None
4759
5193
  self.abrir_wizard_modelo(modelos[indice])
4760
5194
  return
4761
5195
  if tipo == 'model' and passo == 'id':
5196
+ self._pilha().clear()
4762
5197
  self.wizard = None
4763
5198
  if texto.strip():
4764
5199
  self.abrir_wizard_modelo(texto)
@@ -5057,40 +5492,189 @@ class Painel:
5057
5492
  prefixo = 'provedor restaurado para' if restaurando else 'provedor ativo agora é'
5058
5493
  return ('ok', f'{prefixo} {nome}{extra}{nota}')
5059
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
+
5060
5616
  def tarefa_listar_modelos(self):
5061
5617
  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):
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):
5079
5639
  nome = (nome or '').strip()
5080
5640
  if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/+-]{0,199}', nome):
5081
5641
  raise ValueError('informe o ID do modelo, sem espacos: /model ID')
5082
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'
5083
5648
  atual = modelo_ativo(cfg)
5084
- if nome == atual:
5649
+ if nome == atual and prov_destino == prov_anterior:
5085
5650
  return ('aviso', f'o modelo ativo já é {nome}')
5086
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
5087
5666
  if cfg.get('provider') == 'opencode':
5088
5667
  cfg['opencode_model'] = nome
5089
5668
  cfg['model_enviado'] = ''
5090
5669
  else:
5091
5670
  cfg['upstream_model'] = nome
5092
5671
  cfg['model_enviado'] = nome
5093
- # 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).
5094
5678
  aviso_esforco = ''
5095
5679
  prov = str(cfg.get('provider') or '')
5096
5680
  if prov in ('kimi', 'nvidia', 'antigravity'):
@@ -5101,15 +5685,15 @@ class Painel:
5101
5685
  or 'max'
5102
5686
  ).strip().lower()
5103
5687
  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
- )
5688
+ novo_eff = aceitos[-1]
5689
+ cfg.setdefault('esforco_modelos', {}).setdefault(prov, {})[nome] = novo_eff
5690
+ aviso_esforco = f' · effort {novo_eff}'
5107
5691
  gravar_config_com_contexto(cfg)
5108
5692
  if self.bridge_online():
5109
5693
  extra = self._reiniciar_bridge_seguro(cfg_anterior)
5110
5694
  else:
5111
5695
  extra = ' · vale na próxima partida do bridge'
5112
- return ('ok', f'modelo ativo agora é {nome}{extra}{aviso_esforco}')
5696
+ return ('ok', f'{prov} · {nome}{aviso_esforco}{extra}')
5113
5697
 
5114
5698
  def tarefa_definir_contexto(self, tamanho: str, esperado=None):
5115
5699
  tokens = contexto.parse_contexto(tamanho)