krnell 3.0.6 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/painel.py CHANGED
@@ -16,6 +16,7 @@ import base64
16
16
  import contextlib
17
17
  import copy
18
18
  import ctypes
19
+ from datetime import datetime
19
20
  import signal
20
21
  from html.parser import HTMLParser
21
22
  from http.client import HTTPException
@@ -509,6 +510,47 @@ def _cor_fracao(frac) -> str:
509
510
  return ERRO
510
511
 
511
512
 
513
+ def _fmt_duracao_unica(segundos) -> str:
514
+ """Formata tempo restante em unidade única: 7d, 23h, 59m, 59s."""
515
+ try:
516
+ sec = int(round(float(segundos)))
517
+ except (TypeError, ValueError):
518
+ return ''
519
+ if sec <= 0:
520
+ return '0s'
521
+ if sec >= 86400:
522
+ return f'{sec // 86400}d'
523
+ if sec >= 3600:
524
+ return f'{sec // 3600}h'
525
+ if sec >= 60:
526
+ return f'{sec // 60}m'
527
+ return f'{sec}s'
528
+
529
+
530
+ def _reset_restante_bucket(b: dict | None) -> str:
531
+ if not isinstance(b, dict):
532
+ return ''
533
+ reset_iso = b.get('resetTime')
534
+ if isinstance(reset_iso, str) and reset_iso.strip():
535
+ try:
536
+ iso = reset_iso.strip()
537
+ if iso.endswith('Z'):
538
+ iso = iso[:-1] + '+00:00'
539
+ alvo = datetime.fromisoformat(iso).timestamp()
540
+ return _fmt_duracao_unica(max(0, alvo - time.time()))
541
+ except ValueError:
542
+ pass
543
+ sec = b.get('resetInSeconds')
544
+ if isinstance(sec, (int, float)):
545
+ return _fmt_duracao_unica(max(0, sec))
546
+ human = str(b.get('resetHuman') or '').strip()
547
+ if human:
548
+ # Extrai a primeira unidade (ex.: "6d 23h" -> "6d")
549
+ m = re.search(r'(\d+\s*[dhms])', human)
550
+ return m.group(1).replace(' ', '') if m else human.replace(' ', '')
551
+ return ''
552
+
553
+
512
554
  def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> tuple[str, str]:
513
555
  if not isinstance(b, dict):
514
556
  return '', FRACO
@@ -517,8 +559,8 @@ def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> t
517
559
  return '', FRACO
518
560
  valor = b.get('remainingPercent')
519
561
  pct = float(valor) if isinstance(valor, (int, float)) else float(frac) * 100
520
- reset = str(b.get('resetHuman') or '').replace(' ', '') if com_reset else ''
521
- txt = f'{prefixo} {pct:.1f}%' + (f' ({reset})' if reset and pct < 100 else '')
562
+ reset = _reset_restante_bucket(b) if com_reset else ''
563
+ txt = f'{prefixo} {pct:.1f}%' + (f' ({reset})' if reset else '')
522
564
  return txt, _cor_fracao(frac)
523
565
 
524
566
 
@@ -857,10 +899,42 @@ class Coletor(threading.Thread):
857
899
  # Formatacao
858
900
  # ---------------------------------------------------------------------------
859
901
 
902
+ _TZ_LOCAL_CACHE = None
903
+
904
+
905
+ def _tz_local():
906
+ """Detecta fuso real do dispositivo (inclusive Android/proot quando /etc/localtime está em UTC)."""
907
+ global _TZ_LOCAL_CACHE
908
+ if _TZ_LOCAL_CACHE is not None:
909
+ return _TZ_LOCAL_CACHE
910
+ from zoneinfo import ZoneInfo
911
+ candidatos = [os.environ.get('TZ', '').strip()]
912
+ if not candidatos[0]:
913
+ try:
914
+ prop = subprocess.run(['getprop', 'persist.sys.timezone'], capture_output=True, text=True, timeout=1.0)
915
+ if prop.returncode == 0 and prop.stdout.strip():
916
+ candidatos.append(prop.stdout.strip())
917
+ except OSError:
918
+ pass
919
+ for nome in candidatos:
920
+ if not nome:
921
+ continue
922
+ try:
923
+ _TZ_LOCAL_CACHE = ZoneInfo(nome)
924
+ return _TZ_LOCAL_CACHE
925
+ except Exception:
926
+ continue
927
+ _TZ_LOCAL_CACHE = False
928
+ return _TZ_LOCAL_CACHE
929
+
930
+
860
931
  def fmt_hora(ts) -> str:
861
932
  try:
933
+ tz = _tz_local()
934
+ if tz:
935
+ return datetime.fromtimestamp(float(ts), tz=tz).strftime('%H:%M:%S')
862
936
  return time.strftime('%H:%M:%S', time.localtime(float(ts)))
863
- except (TypeError, ValueError):
937
+ except (TypeError, ValueError, OSError):
864
938
  return '--:--:--'
865
939
 
866
940
 
@@ -1478,15 +1552,23 @@ class Painel:
1478
1552
  lado.append('Antigravity\n', style=FRACO)
1479
1553
  for item in resumo[:2]:
1480
1554
  lado.append(f"{item['nome']:<7}", style=TEXTO)
1481
- t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1555
+ # Ordem limpa: 7d primeiro e 5h depois (sem parênteses cortando);
1556
+ # o tempo de reset vem logo abaixo numa linha dedicada.
1482
1557
  ts, cs = _fmt_bucket_curto(item.get('bsem'), '7d', com_reset=False)
1483
- if t5:
1484
- lado.append(t5, style=c5)
1485
- if t5 and ts:
1486
- lado.append(' ', style=BORDA)
1558
+ t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1487
1559
  if ts:
1488
1560
  lado.append(ts, style=cs)
1561
+ if ts and t5:
1562
+ lado.append(' ', style=BORDA)
1563
+ if t5:
1564
+ lado.append(t5, style=c5)
1489
1565
  lado.append('\n')
1566
+ primeiro_item = resumo[0]
1567
+ r5 = _reset_restante_bucket(primeiro_item.get('b5h'))
1568
+ r7 = _reset_restante_bucket(primeiro_item.get('bsem'))
1569
+ partes_r = [p for p in (f'diário {r5}' if r5 else '', f'semanal {r7}' if r7 else '') if p]
1570
+ if partes_r:
1571
+ lado.append('reseta ' + ' · '.join(partes_r) + '\n', style=FRACO)
1490
1572
  tokens_mes = snap.get('tokens_mes') or {}
1491
1573
  total_mes = int(tokens_mes.get('total') or 0)
1492
1574
  if total_mes:
@@ -1522,12 +1604,18 @@ class Painel:
1522
1604
  resumo = _resumo_cota_antigravity(ag_status)
1523
1605
  for idx, item in enumerate(resumo[:2]):
1524
1606
  if idx:
1525
- segunda.append(' · ' if self.largura < 50 else ' · ', style=BORDA)
1526
- segunda.append(item['nome'][0], style=FRACO)
1527
- for bucket, prefixo in ((item.get('b5h'), '5h'), (item.get('bsem'), '7d')):
1607
+ segunda.append(' · ' if self.largura < 50 else ' │ ', style=BORDA)
1608
+ segunda.append(item['nome'][0], style=ACENTO)
1609
+ for bucket, prefixo in ((item.get('bsem'), '7d'), (item.get('b5h'), '5h')):
1528
1610
  texto, cor = _fmt_bucket_curto(bucket, prefixo, com_reset=False)
1529
1611
  if texto:
1530
1612
  segunda.append(' ' + texto, style=cor)
1613
+ if resumo:
1614
+ r5 = _reset_restante_bucket(resumo[0].get('b5h'))
1615
+ r7 = _reset_restante_bucket(resumo[0].get('bsem'))
1616
+ partes_r = [p for p in (f'diário {r5}' if r5 else '', f'semanal {r7}' if r7 else '') if p]
1617
+ if partes_r and self.largura >= 46:
1618
+ segunda.append(' · reseta ' + ' · '.join(partes_r), style=FRACO)
1531
1619
  if not segunda.plain:
1532
1620
  total = int((snap.get('tokens_mes') or {}).get('total') or 0)
1533
1621
  segunda.append(f'{fmt_tokens_grande(total)} tok this month' if total else
@@ -2610,18 +2698,35 @@ class Painel:
2610
2698
  frame.append('')
2611
2699
  self.ultima_contagem = len(frame)
2612
2700
  base = len(frame)
2613
- buf = ['\x1b[?2026h\x1b[H']
2614
- if getattr(self, '_precisa_limpar_tela', False):
2615
- buf.append('\x1b[2J')
2616
- self._precisa_limpar_tela = False
2617
- for idx, linha in enumerate(frame, 1):
2618
- buf.append(f'\x1b[{idx};1H\x1b[2K' + linha + '\x1b[0m\x1b[K')
2701
+ linhas_novas = [linha + '\x1b[0m' for linha in frame]
2619
2702
  regua = '─' * max(6, largura - 2)
2620
- buf.append(f'\x1b[{base + 1};1H\x1b[2K' + ansi('borda') + '╭' + regua + '╮' + RESET)
2621
- buf.append(self._formatar_caixa(base + 2))
2622
- buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2703
+ linhas_novas.append(ansi('borda') + '╭' + regua + '╮' + RESET)
2704
+ linhas_novas.append(self._formatar_caixa(base + 2))
2705
+ linhas_novas.append(ansi('borda') + '╰' + regua + '╯' + RESET)
2623
2706
  self._status_y = base + 3
2624
- buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2707
+ linhas_novas.append(self._barra_status())
2708
+
2709
+ # Diff por linha: só reescreve o que realmente mudou (exceto em clear/resize),
2710
+ # eliminando o piscamento no Termux e em terminais Android.
2711
+ limpar = bool(getattr(self, '_precisa_limpar_tela', False))
2712
+ anteriores = None if limpar else getattr(self, '_frame_anterior', None)
2713
+ if anteriores is not None and len(anteriores) != len(linhas_novas):
2714
+ anteriores = None
2715
+ buf = ['\x1b[?2026h']
2716
+ if limpar:
2717
+ buf.append('\x1b[H\x1b[2J')
2718
+ self._precisa_limpar_tela = False
2719
+ for idx, texto in enumerate(linhas_novas, 1):
2720
+ if anteriores is not None and anteriores[idx - 1] == texto:
2721
+ continue
2722
+ if idx == base + 2 and texto.startswith('\x1b['):
2723
+ # _formatar_caixa já traz posicionamento \x1b[row;1H\x1b[2K
2724
+ buf.append(texto)
2725
+ else:
2726
+ buf.append(f'\x1b[{idx};1H\x1b[2K' + texto + '\x1b[K')
2727
+ if limpar:
2728
+ buf.append('\x1b[J')
2729
+ self._frame_anterior = list(linhas_novas)
2625
2730
  # Oculta o cursor nativo do terminal em listas/modais e quando a caixa está
2626
2731
  # vazia (evita o ponto/bloco branco piscando sozinho no Termux/celular).
2627
2732
  mostrar_cursor = bool(self.buf) or (self.wizard and not self._wizard_lista())
@@ -3174,8 +3279,11 @@ class Painel:
3174
3279
  return True
3175
3280
  if (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.18:
3176
3281
  return True
3177
- if self.modo == 'tui' and (self.wizard or self.modal) and getattr(self, '_dialogo_frame', 99) < 2:
3178
- return True
3282
+ if self.modo == 'tui' and (self.wizard or self.modal):
3283
+ # Com diálogo aberto (ex.: Antigravity, Connect, Model), congela o
3284
+ # redesenho de fundo para não piscar a tela a cada 80ms enquanto há
3285
+ # requisições live rodando atrás.
3286
+ return getattr(self, '_dialogo_frame', 99) < 2 or self.tarefa_ativa
3179
3287
  if self.tarefa_ativa:
3180
3288
  return True
3181
3289
  snap = getattr(self, '_snap_visto', None) or {}