From 62d7f3364920f545971ca6e4d223e8e44a7b0c02 Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Mon, 16 Nov 2026 01:40:54 -0300 Subject: [PATCH 1/3] =?UTF-8?q?fix(tui):=20partida=20leve=20=E2=80=94=20um?= =?UTF-8?q?=20rel=C3=B3gio=20de=20quadros,=20carga=20na=20primeira=20visit?= =?UTF-8?q?a=20e=20leitura=20=C3=BAnica=20do=20registro=20no=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 1 + docs/tui.md | 10 +- internal/detect/detect.go | 11 + internal/detect/windows.go | 31 ++- internal/detect/windows_cache_test.go | 82 ++++++++ internal/tui/model.go | 65 +++++- internal/tui/partida_perf_test.go | 286 ++++++++++++++++++++++++++ internal/tui/run_test.go | 3 +- internal/tui/theme.go | 9 +- 9 files changed, 479 insertions(+), 19 deletions(-) create mode 100644 internal/detect/windows_cache_test.go create mode 100644 internal/tui/partida_perf_test.go diff --git a/CLAUDE.md b/CLAUDE.md index f026792..1d218a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,6 +63,7 @@ Ferramenta em Go para preparar máquinas Windows, Linux e macOS com um comando ( - `scripts/release.sh --version vX.Y.Z [--out dist] [--dry-run] [--sign-macos]` (fase 6): release LOCAL (sem Actions). Compila os 6 alvos (`CGO_ENABLED=0 -trimpath -buildvcs=false`, `-ldflags` com `Version/Commit/Date` do módulo lido por `go list -m`) para `dist/toolkit__[.exe]` (binário cru), copia `unix.sh`/`win.ps1`, e gera `checksums.txt` (sha256sum) por ÚLTIMO (assinar muda o binário). Assinatura (`codesign --options runtime --timestamp`, identidade só por `TOOLKIT_SIGN_IDENTITY`, sem valor padrão no repo) e notarização (`ditto` + `xcrun notarytool submit --wait`) são funções separadas, DESLIGADAS por padrão (`--sign-macos`). `NOTARY_KEY_ID`, `NOTARY_ISSUER`, `NOTARY_P8_OP_REF` (referência do 1Password) e `TOOLKIT_SIGN_IDENTITY` vêm do ambiente ou de `~/.config/toolkit/release.env` (`TOOLKIT_RELEASE_ENV`, permissão 600/400 exigida), NUNCA do repo; faltando algum, falha antes de compilar. Guardas antes de compilar/apagar: árvore limpa e tag `vX.Y.Z` existente e igual a HEAD (o binário leva `Commit=HEAD`); `--out` resolvido pelo caminho real, só subdiretório do repo (recusa vazio, `/`, o repo, `.git`, link simbólico e diretório com arquivo versionado). O .p8 sai de `op read` para arquivo temporário 600 apagado por trap e nunca é impresso. Não publica: o `gh release create ... --draft` é manual, só com OK do Paulo. `release_test.sh` (no `ci.sh`) roda numa CÓPIA do repo em diretório temporário (git init + tag) e usa `op`/`codesign`/`xcrun`/`ditto` FALSOS num PATH temporário (nada é assinado nem notarizado de verdade), confere dry-run sem efeito, 6 binários + checksums válidos, versão embutida, assinatura só nos 2 darwin com checksums depois dela, p8 com perm 600 e apagado, e que o script não tem credencial literal. - TUI por ÁREAS (redesign, fase 3 de 7): `tui.NewWithAreas`/`RunAreas`, `AreaDef`/`Area`, seções em lista plana `Model.tabs`; `0` a `5` vão à área, Tab troca de seção dentro dela, linha 2 com `admin: sim/não` (`Options.IsAdmin`), `InfoTab` para Início e Rede/Análise; `New(o, tabs...)` é o modo legado. Ver `docs/tui.md` ("Áreas e seções"). - Início da TUI (redesign, fase 4 de 7; `internal/tui/inicio_tab.go`, `internal/cli/tui_inicio.go`, `docs/tui.md`): a área 0 é uma lista de OBJETIVOS ("O que você quer fazer?", sete itens com frase didática e etiqueta por GOOS/admin, sem ler nada do sistema). Enter e `1`..`7` abrem a área/seção do item pelo contrato opcional `tui.KeyClaimer` (só em navegação normal) e a mensagem `tui.GoToMsg{Area, Section}`, que a RAIZ trata em `Model.goTo` (ignora Revisão, execução, modal, pergunta e seção capturando; a confirmação nunca é abandonada, com teste integrado usando PrivacyTab/NativeAppsTab reais). O destino é achado pelas áreas montadas (chave da área + título da seção), não por índice fixo. +- TUI: partida leve (v0.4.0, `docs/tui.md`): a raiz mantém UM relógio de quadros (seções pedem `Theme.Tick()` = `tickWantMsg`, a raiz deduplica; nunca agendar tick por seção), carrega só a seção ativa no `Init` e as outras na primeira visita (`Model.wake`), e o `detect` do Windows lê o registro UMA vez por prazo (`readWindowsRegistry`, `Invalidate`). Testes em `internal/tui/partida_perf_test.go`. - `internal/tui` (fase 4, PR1): `Model` (raiz: tamanho, aba ativa, ajuda, sair; Bubble Tea v2 `charm.land/bubbletea/v2`, Lip Gloss v2, Bubbles v2, versões exatas), interface `Tab` (`Title/Short/Update/View(w,h)/Keys/Status/More/Selected`), `Theme` (tokens; `Mono` = NO_COLOR sem nenhuma sequência de estilo e layout idêntico ao colorido), layout fixo (cabeçalho com abas e versão, régua, corpo H-5, régua com `↓ mais N`, estado, teclas), tela única abaixo de 60x16, abas estreitas abaixo de 70. `DefaultTabs` são só o estado vazio até cada aba ganhar a sua (PRs seguintes). Testes: golden em `testdata/` (80x24, 60x17, ajuda; `UPDATE_GOLDEN=1` regera e se revisa o diff), tela sempre com H linhas e <= W colunas, texto de fora sem escape. `internal/textsafe`: `Printable`/`Line`, usado por `cli.printable` e por todo texto de fora da TUI. Especificação completa em `docs/tui.md` (variante A e as decisões 1-5 confirmadas pelo Paulo). - `internal/tui` Revisão, execução e Log (fase 4, PR4: `exec.go`, `review.go`, `model_exec.go`, `logtab.go`): interfaces `Planner` (`Plan(ctx, Selection) Plan`: o MESMO passe do `toolkit install --dry-run`, nunca um segundo planejador; `Plan` traz Summary, Env, Warnings, Changes, Commands já 'como será executado', Problems, NothingToDo) e `Runner` (`Run(ctx, Selection, chan<- Event)`; fecha o canal; reaproveita `providers.InstallApp` e `recipes.Engine`). A raiz ganhou o modo (`modeNav` -> `modeReview` -> `modeRun`): Enter nas abas (sem marcados só avisa) abre a Revisão (carrega com spinner; foco inicial em Voltar; Tab troca o botão; `s` ou Enter em Executar executa; com Problems/NothingToDo/erro só Voltar e `s` não faz nada; comandos longos quebram com recuo e `\` e NUNCA são cortados). Executar vai à aba Log; durante a execução as outras abas são só leitura (espaço, Enter, v e / bloqueados com aviso); `q`/Ctrl+C pergunta 'Interromper? ... [s/N]' (só `s` cancela o ctx: item atual encerrado e fila descartada); evento `EventRebootPrompt` vira pergunta [s/N] e a resposta volta pelo `Reply`. `LogTab`: itens (símbolo+palavra+duração) em cima, log do item sob o cursor embaixo, `\r` substitui a última linha, `f` segue o fim, PgUp desliga o seguir, resumo 'Terminou com N falhas · N ok · N falhou' com o cursor na primeira falha, aviso '! Não deu para gravar o log em arquivo'. Cada Revisão tem um `id` e a seleção planejada (`reviewScreen.id/sel`): `planReadyMsg` de outra Revisão é ignorado e Executar entrega ao executor a seleção PLANEJADA, não a das abas. Um diálogo [s/N] por vez (`open/answer`): só s/S (sim) e n/N/Esc (não) respondem, outra tecla é ignorada; um pedido de reinício que chega com o diálogo de interrupção aberto espera a vez (e recebe 'não' se a execução for interrompida); a resposta ao `Reply` nunca bloqueia o loop (`deliver`: envio imediato, senão goroutine que desiste quando a execução termina). `wrap` quebra por largura de CÉLULA e por GRAFEMA (`splitCells` com `rivo/uniseg`, medindo com `lipgloss.Width`: ❤️ = U+2764+U+FE0F ocupa 2 células, sequência ZWJ e combinante são um grafema só) e nunca corta; resumo e ambiente do plano também quebram. O ZWJ (U+200D, caractere de formatação) aparece como `\\u200d` por política do `textsafe`. Todo texto (plano, nomes, log, erros) por `textsafe`. A implementação real de `Planner`/`Runner` (cli) e o `printPlan` com GOOS/euid do runner real entram no PR que liga `toolkit` sem args. - `toolkit` sem argumentos (fase 4, PR5b, `internal/cli/tui.go`): `runRoot` abre a TUI só quando `shouldOpenTUI` (stdin E stdout são terminal; a entrada E a saída usam a MESMA detecção, `fileIsTerminal` = `charmbracelet/x/term.IsTerminal` por fd (`stdinIsTerminal` também; dispositivo de caractere não basta: /dev/null e /dev/zero também são, e `toolkit install x bundle achado, da varredura de /Applications e ~/Applications macAt time.Time // quando a varredura foi feita (vale cacheTTL) macBuilt bool + + // leitura do registro do Windows (windows.go): uma por prazo, para todos os apps. winMu fica preso durante a + // leitura de propósito (perguntas simultâneas esperam a mesma). + winMu sync.Mutex + winOut []byte + winOK bool + winAt time.Time + winBuilt bool } // cacheTTL é por quanto tempo a varredura de .app por bundle_id é reaproveitada: a TUI pergunta o estado de @@ -74,6 +82,9 @@ func (d *Detector) Invalidate() { d.mu.Lock() d.macIndex, d.macBuilt = nil, false d.mu.Unlock() + d.winMu.Lock() + d.winOut, d.winBuilt = nil, false + d.winMu.Unlock() } // New cria o detector sobre o Runner (só leituras). diff --git a/internal/detect/windows.go b/internal/detect/windows.go index 3925437..9882b75 100644 --- a/internal/detect/windows.go +++ b/internal/detect/windows.go @@ -104,13 +104,36 @@ func incomplete(status map[rootKey]string, roots ...[]rootKey) bool { return false } +// readWindowsRegistry roda o script UMA vez e reaproveita a saída pelo prazo do cache (cacheTTL), tanto o sucesso +// quanto a falha: a TUI pergunta o estado de cada app do catálogo e cada pergunta rodava um PowerShell que lê todo o +// registro (centenas de ms de CPU por app, vários em paralelo na partida). Perguntas simultâneas esperam a mesma +// leitura (o lock fica preso enquanto ela roda). Cancelamento não é guardado. Invalidate descarta (depois de +// instalar ou remover algo). +func (d *Detector) readWindowsRegistry(ctx context.Context) ([]byte, bool) { + d.winMu.Lock() + defer d.winMu.Unlock() + if d.winBuilt && d.now().Sub(d.winAt) < cacheTTL { + return d.winOut, d.winOK + } + res, err := d.rn.Run(ctx, d.readOnly(exec.Cmd{Name: windowsPowerShell, + Args: []string{"-NoProfile", "-NonInteractive", "-Command", uninstallScript}, Timeout: 30 * time.Second})) + if ctx.Err() != nil { + return nil, false // cancelado: não vira cache + } + ok := err == nil && res.ExitCode == 0 && len(res.Stdout) <= maxUninstallOutput + d.winOut, d.winOK, d.winAt, d.winBuilt = nil, ok, d.now(), true + if ok { + d.winOut = res.Stdout + } + return d.winOut, ok +} + func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, bool) { if (spec.DisplayName == "" && spec.AppPath == "") || d.rn == nil { return Found{}, false } - res, err := d.rn.Run(ctx, d.readOnly(exec.Cmd{Name: windowsPowerShell, - Args: []string{"-NoProfile", "-NonInteractive", "-Command", uninstallScript}, Timeout: 30 * time.Second})) - if err != nil || res.ExitCode != 0 || len(res.Stdout) > maxUninstallOutput { + out, readOK := d.readWindowsRegistry(ctx) + if !readOK { // Nada foi lido: não é "não instalado", é detecção incompleta. return Found{Incomplete: true}, false } @@ -121,7 +144,7 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, viaPath *Found ) status := map[rootKey]string{} - for _, line := range strings.Split(string(res.Stdout), "\n") { + for _, line := range strings.Split(string(out), "\n") { f := strings.Split(strings.TrimRight(line, "\r"), "\t") switch { case len(f) == 4 && f[0] == "S": diff --git a/internal/detect/windows_cache_test.go b/internal/detect/windows_cache_test.go new file mode 100644 index 0000000..ab7d449 --- /dev/null +++ b/internal/detect/windows_cache_test.go @@ -0,0 +1,82 @@ +package detect + +import ( + "context" + "sync" + "testing" + + "github.com/PiluTech/toolkit/internal/exec" +) + +// A TUI pergunta o estado de cada app do catálogo e, no Windows, cada pergunta rodava um PowerShell que lê TODO o +// registro de desinstalação (centenas de ms de CPU por app, 4 em paralelo na partida). Uma leitura serve a todos. +func TestWindowsUmaLeituraDoRegistroServeTodosOsApps(t *testing.T) { + s := winStub(u("HKLM", "Git", "2.45.1", "P"), u("HKLM", "Discord", "1.0", "P")) + d := New(s, Options{GOOS: "windows"}) + git, dis := winApp(t, "display_name: Git"), winApp(t, "display_name: Discord") + for i := 0; i < 10; i++ { + if f, ok := find(t, d, git); !ok || f.Version != "2.45.1" { + t.Fatalf("git: %+v %v", f, ok) + } + if _, ok := find(t, d, dis); !ok { + t.Fatal("discord") + } + } + if len(s.calls) != 1 { + t.Fatalf("PowerShell rodou %d vezes para 20 perguntas (esperado 1)", len(s.calls)) + } + d.Invalidate() // depois de instalar ou remover algo a leitura é refeita + find(t, d, git) + if len(s.calls) != 2 { + t.Fatalf("Invalidate deve forçar uma leitura nova: %d", len(s.calls)) + } +} + +func TestWindowsPerguntasSimultaneasFazemUmaLeitura(t *testing.T) { + s := winStub(u("HKLM", "Git", "2.45.1", "P")) + d := New(s, Options{GOOS: "windows"}) + a := winApp(t, "display_name: Git") + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, _, _ = d.Find(context.Background(), a) + }() + } + wg.Wait() + if len(s.calls) != 1 { + t.Fatalf("8 perguntas simultâneas fizeram %d leituras (esperado 1)", len(s.calls)) + } +} + +// Leitura que falhou também vale pelo prazo: 40 apps não rodam 40 PowerShell de 30 s cada num registro quebrado; o +// resultado continua "leitura incompleta", nunca "não instalado". +func TestWindowsFalhaDaLeituraTambemEhReaproveitada(t *testing.T) { + failing := &stub{handle: func(_ exec.Cmd) (exec.Result, error) { return exec.Result{ExitCode: 1}, nil }} + d := New(failing, Options{GOOS: "windows"}) + a := winApp(t, "display_name: Git") + for i := 0; i < 5; i++ { + if f, ok := find(t, d, a); ok || !f.Incomplete { + t.Fatalf("falha deve ser leitura incompleta: %+v %v", f, ok) + } + } + if len(failing.calls) != 1 { + t.Fatalf("%d execuções para 5 perguntas (esperado 1)", len(failing.calls)) + } +} + +// Cancelamento NÃO é cacheado: a próxima pergunta, com contexto vivo, lê de verdade. +func TestWindowsCancelamentoNaoViraCache(t *testing.T) { + s := winStub(u("HKLM", "Git", "2.45.1", "P")) + d := New(s, Options{GOOS: "windows"}) + a := winApp(t, "display_name: Git") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := d.Find(ctx, a); err == nil { + t.Fatal("contexto cancelado devolve erro") + } + if f, ok := find(t, d, a); !ok || f.Version != "2.45.1" { + t.Fatalf("depois do cancelamento a leitura é feita: %+v %v", f, ok) + } +} diff --git a/internal/tui/model.go b/internal/tui/model.go index ae2ea13..4be6e31 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -79,6 +79,13 @@ type Model struct { // resultados de execuções por índice de aba (a faixa da aba de origem); origins são as abas que tinham marcados results map[int]*Result origins []int + + // inited: seções cujo Init (a carga) já foi pedido. A abertura carrega só a ativa; as outras, na primeira visita. + inited map[int]bool + started bool // o Init já rodou (só depois dele o Update carrega seções novas) + + // ticking: há UM quadro do spinner agendado (as abas só PEDEM quadros; a raiz os deduplica) + ticking bool } // UpdateInfo é uma versão nova (tag, notas já limpas, página da release). @@ -117,13 +124,24 @@ func New(o Options, tabs ...Tab) *Model { return &Model{opts: o, theme: Theme{Mono: o.Mono, Dark: true, NoMotion: o.NoMotion}, tabs: tabs, areas: legacyAreas(tabs), lastSec: make([]int, len(tabs)), w: 80, h: 24, results: map[int]*Result{}} } -// Init pede a cor de fundo do terminal (claro ou escuro). +// Init pede a cor de fundo do terminal (claro ou escuro) e carrega SÓ a seção ativa: as outras carregam na primeira +// visita (wake), nunca todas juntas na abertura (antes: catálogo e estado de cada app, receitas, apps do Windows, +// privacidade... disputando CPU e processos com a primeira tela). func (m *Model) Init() tea.Cmd { - cmds := []tea.Cmd{tea.RequestBackgroundColor} - for _, t := range m.tabs { - cmds = append(cmds, t.Init()) + m.started = true + return tea.Batch(tea.RequestBackgroundColor, m.wake()) +} + +// wake pede o Init da seção ativa se ainda não foi pedido. +func (m *Model) wake() tea.Cmd { + if len(m.tabs) == 0 || m.inited[m.active] { + return nil + } + if m.inited == nil { + m.inited = map[int]bool{} } - return tea.Batch(cmds...) + m.inited[m.active] = true + return m.tabs[m.active].Init() } // Active devolve o índice da aba ativa (para os testes). @@ -132,8 +150,19 @@ func (m *Model) Active() int { return m.active } // Quitting diz se a TUI foi encerrada. func (m *Model) Quitting() bool { return m.quit } -// Update trata tamanho, teclas globais e repassa o resto à aba ativa. +// Update trata tamanho, teclas globais e repassa o resto à aba ativa; se a tecla levou a uma seção nova, carrega-a. func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + next, cmd := m.update(msg) + if !m.started { + return next, cmd + } + if w := m.wake(); w != nil { + cmd = tea.Batch(cmd, w) + } + return next, cmd +} + +func (m *Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.WindowSizeMsg: m.w, m.h = msg.Width, msg.Height @@ -163,15 +192,29 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.finishRun() // depois da execução as abas que mostram o estado do sistema o releem (Apps, Receitas) var cmds []tea.Cmd - for _, t := range m.tabs { - if r, ok := t.(Reloader); ok { + for i, t := range m.tabs { + if r, ok := t.(Reloader); ok && (!m.started || m.inited[i]) { // seção nunca aberta carrega do zero na primeira visita cmds = append(cmds, r.Reload()) } } return m, tea.Batch(cmds...) + case tickWantMsg: + if m.ticking { + return m, nil + } + m.ticking = true + return m, tick() case tickMsg: + m.ticking = false // as abas que ainda animam pedem o próximo; o primeiro pedido rearma o relógio if m.review != nil && m.review.loading { m.review.frame++ + cmds := []tea.Cmd{m.theme.Tick()} + for i, t := range m.tabs { + tab, cmd := t.Update(msg) + m.tabs[i] = tab + cmds = append(cmds, cmd) + } + return m, tea.Batch(cmds...) } case tea.KeyPressMsg: if m.w < MinWidth || m.h < MinHeight { @@ -281,15 +324,15 @@ func (m *Model) global(k string) (tea.Model, tea.Cmd, bool) { } switch k { case "tab": - m.active = (m.active + 1) % len(m.tabs) + m.setActive((m.active + 1) % len(m.tabs)) return m, nil, true case "shift+tab": - m.active = (m.active + len(m.tabs) - 1) % len(m.tabs) + m.setActive((m.active + len(m.tabs) - 1) % len(m.tabs)) return m, nil, true } if len(k) == 1 && k[0] >= '1' && k[0] <= '9' { if i := int(k[0] - '1'); i < len(m.tabs) { - m.active = i + m.setActive(i) return m, nil, true } } diff --git a/internal/tui/partida_perf_test.go b/internal/tui/partida_perf_test.go new file mode 100644 index 0000000..486a911 --- /dev/null +++ b/internal/tui/partida_perf_test.go @@ -0,0 +1,286 @@ +package tui + +import ( + "context" + "testing" + "time" + + tea "charm.land/bubbletea/v2" +) + +// Backends que demoram, para simular a partida real (detecção, registro, PowerShell, winget). +type slowApps struct { + fakeBackend + d time.Duration +} + +func (s *slowApps) Load(ctx context.Context) ([]AppInfo, error) { + time.Sleep(s.d) + return s.fakeBackend.Load(ctx) +} + +type slowPriv struct { + *fakePriv + d time.Duration +} + +func (s *slowPriv) Load(ctx context.Context) (PrivInfo, error) { + time.Sleep(s.d) + return s.fakePriv.Load(ctx) +} + +type slowNat struct { + *fakeNat + d time.Duration +} + +func (s *slowNat) Load(ctx context.Context) (NatInfo, error) { + time.Sleep(s.d) + return s.fakeNat.Load(ctx) +} + +type slowRecipes struct { + fakeRecipes + d time.Duration +} + +func (s *slowRecipes) Load(ctx context.Context) (RecipesData, error) { + time.Sleep(s.d) + return s.fakeRecipes.Load(ctx) +} + +// loop é um laço mínimo do Bubble Tea sem terminal: executa os comandos em goroutines e entrega as mensagens ao +// Model numa única goroutine, como o Program faz. Mede quantas mensagens de quadro (tickMsg) chegam e quanto cada +// Update demora. +type loop struct { + m *Model + msgs chan tea.Msg + ticks int + total int + maxUpd time.Duration +} + +func newLoop(m *Model) *loop { return &loop{m: m, msgs: make(chan tea.Msg, 1<<16)} } + +func (l *loop) run(cmd tea.Cmd) { + if cmd == nil { + return + } + go func() { + msg := cmd() + switch v := msg.(type) { + case nil: + case tea.BatchMsg: + for _, c := range v { + l.run(c) + } + default: + select { + case l.msgs <- msg: + default: + } + } + }() +} + +func (l *loop) pump(d time.Duration) { + end := time.After(d) + for { + select { + case <-end: + return + case msg := <-l.msgs: + if _, ok := msg.(tickMsg); ok { + l.ticks++ + } + l.total++ + t0 := time.Now() + _, cmd := l.m.Update(msg) + if el := time.Since(t0); el > l.maxUpd { + l.maxUpd = el + } + l.run(cmd) + } + } +} + +func startupModel(delay time.Duration) *Model { + th := Theme{Mono: true, Dark: true} + ctx := context.Background() + apps := &slowApps{fakeBackend: fakeBackend{apps: sampleApps()}, d: delay} + rec := &slowRecipes{fakeRecipes: fakeRecipes{data: recipeSample()}, d: delay} + tabs := []Tab{ + NewAppsTab(ctx, apps, th, "linux"), + NewRecipesTab(ctx, rec, th, false), + NewNativeAppsTab(ctx, &slowNat{fakeNat: &fakeNat{}, d: delay}, th), + NewPrivacyTab(ctx, &slowPriv{fakePriv: &fakePriv{}, d: delay}, th), + } + return New(Options{}, tabs...) +} + +// Regressão do travamento da partida: cada aba que carrega agenda um quadro do spinner e todo quadro era entregue +// a TODAS as abas, que agendavam outro cada uma: com K abas carregando os quadros multiplicavam por K a cada 100 ms +// (4, 80, 1.280, 20.480 por janela de 200 ms com 4 abas). A raiz agora mantém UM relógio de quadros. +func TestPartidaTicksNaoMultiplicam(t *testing.T) { + m := startupModel(1500 * time.Millisecond) + l := newLoop(m) + l.run(m.Init()) + l.pump(1200 * time.Millisecond) + // um quadro a cada 100 ms: ~12 em 1,2 s (folga para o agendador); a explosão passava de 100 mil + if l.ticks > 30 { + t.Fatalf("%d quadros em 1,2 s (esperado ~12): os quadros estão se multiplicando", l.ticks) + } + if l.ticks < 3 { + t.Fatalf("só %d quadros: o spinner não pode parar enquanto as abas carregam", l.ticks) + } +} + +// initTab conta quantas vezes o Init da aba foi pedido. +type initTab struct { + fakeTab + inits int +} + +func (f *initTab) Init() tea.Cmd { f.inits++; return nil } + +// A partida só carrega a seção que aparece: as outras (catálogo + estado de cada app, receitas, apps do Windows, +// privacidade) carregam na PRIMEIRA visita e nunca de novo. Antes todas carregavam juntas na abertura. +func TestInitSoCarregaASecaoAtivaENaPrimeiraVisita(t *testing.T) { + a, b, c := &initTab{fakeTab: fakeTab{title: "A", short: "A"}}, &initTab{fakeTab: fakeTab{title: "B", short: "B"}}, &initTab{fakeTab: fakeTab{title: "C", short: "C"}} + m := New(Options{}, a, b, c) + m.Init() + if a.inits != 1 || b.inits != 0 || c.inits != 0 { + t.Fatalf("na abertura só a ativa carrega: a=%d b=%d c=%d", a.inits, b.inits, c.inits) + } + m.Update(key('2', "2")) + if b.inits != 1 || c.inits != 0 { + t.Fatalf("a primeira visita carrega a seção: b=%d c=%d", b.inits, c.inits) + } + m.Update(key('1', "1")) + m.Update(key('2', "2")) + if a.inits != 1 || b.inits != 1 { + t.Fatalf("revisitar não recarrega: a=%d b=%d", a.inits, b.inits) + } +} + +// bigApps devolve n apps sintéticos em categorias variadas, com o estado de cada um já lido. +func bigApps(n int) (*fakeBackend, []AppInfo) { + cats := []string{"dev", "browser", "media", "util", "office"} + be := &fakeBackend{status: map[string]AppStatus{}} + for i := 0; i < n; i++ { + id := "app-" + itoa(i) + be.apps = append(be.apps, AppInfo{ID: id, Name: "Aplicativo de teste número " + itoa(i), Category: cats[i%len(cats)], Managers: []string{"winget", "brew"}, Versions: i%7 == 0}) + switch i % 4 { + case 0: + be.status[id] = AppStatus{Installed: true, Version: "1.2." + itoa(i)} + case 1: + be.status[id] = AppStatus{Installed: true, External: true, ExternalManager: "winget", ExternalWhere: "Programas e recursos do Windows [HKLM]"} + } + } + return be, be.apps +} + +func bigModel(t testing.TB, n int) *Model { + be, _ := bigApps(n) + tab := newApps(be) + tab.lastH = 40 + tab.Update(tab.loadCmd()()) + for len(tab.pending) > 0 || len(tab.queue) > 0 { + var ids []string + for id := range tab.pending { + ids = append(ids, id) + } + if len(ids) == 0 { + t.Fatal("fila parada") + } + for _, id := range ids { + tab.Update(appStateMsg{id: id, st: be.status[id]}) + } + } + m := New(Options{Version: "v0.4.0"}, tab) + m.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) + return m +} + +func BenchmarkViewApps300(b *testing.B) { + m := bigModel(b, 300) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = m.View() + } +} + +func BenchmarkTeclaSetaApps300(b *testing.B) { // Update + View por tecla, como o Program faz + m := bigModel(b, 300) + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.Update(tea.KeyPressMsg{Code: tea.KeyDown}) + _ = m.View() + } +} + +// firstFrame e keyLatency medem o que o Paulo sentiu: a primeira tela e a seta durante a carga. +func TestPartidaPrimeiraTelaENaoBloqueiaTecla(t *testing.T) { + m := startupModel(4 * time.Second) + t0 := time.Now() + cmd := m.Init() + m.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) + first := m.View().Content + if el := time.Since(t0); el > 100*time.Millisecond { + t.Fatalf("a primeira tela levou %v (teto 100 ms): Init/Update não podem esperar I/O", el) + } + if first == "" { + t.Fatal("primeira tela vazia") + } + l := newLoop(m) + l.run(cmd) + l.pump(1500 * time.Millisecond) // carga em andamento (spinner animando) + // a seta entra na fila junto com o resto: tem de ser tratada e desenhada rápido, sem fila atrás de quadros + sent := time.Now() + l.msgs <- tea.KeyPressMsg{Code: tea.KeyDown} + var handled time.Duration + end := time.After(2 * time.Second) + for handled == 0 { + select { + case <-end: + t.Fatal("a seta não foi tratada em 2 s: fila entupida") + case msg := <-l.msgs: + _, cmd := l.m.Update(msg) + _ = l.m.View() + l.run(cmd) + if _, ok := msg.(tea.KeyPressMsg); ok { + handled = time.Since(sent) + } + } + } + t.Logf("seta tratada e desenhada em %v; %d quadros na partida", handled, l.ticks) + if handled > 30*time.Millisecond { + t.Fatalf("seta tratada e desenhada em %v (teto 30 ms)", handled) + } +} + +// Teto do View com volume realista (300 apps): o desenho de uma tecla não pode crescer sem aviso. +func TestViewCom300AppsTemTeto(t *testing.T) { + m := bigModel(t, 300) + const n = 200 + t0 := time.Now() + for i := 0; i < n; i++ { + m.Update(tea.KeyPressMsg{Code: tea.KeyDown}) + _ = m.View() + } + if avg := time.Since(t0) / n; avg > 8*time.Millisecond { + t.Fatalf("tecla + View com 300 apps: %v em média (teto 8 ms)", avg) + } +} + +// Depois de uma execução só as seções que já foram abertas são relidas; a nunca aberta carrega do zero na visita. +func TestRunClosedReleSoSecoesJaAbertas(t *testing.T) { + a := &reloadSpy{fakeTab: fakeTab{title: "A", short: "A"}} + b := &reloadSpy{fakeTab: fakeTab{title: "B", short: "B"}} + m := New(Options{}, a, b) + m.Init() // abre só A + m.Update(runClosedMsg{}) + if a.reloads != 1 || b.reloads != 0 { + t.Fatalf("releituras: a=%d b=%d (esperado 1 e 0)", a.reloads, b.reloads) + } +} diff --git a/internal/tui/run_test.go b/internal/tui/run_test.go index 038792d..bb193ff 100644 --- a/internal/tui/run_test.go +++ b/internal/tui/run_test.go @@ -148,7 +148,8 @@ func TestRunAreasCancelsAndStopsEveryArea(t *testing.T) { be := &blockingBackend{apps: []AppInfo{{ID: "a", Name: "A", Category: "dev"}}} apps := NewAppsTab(context.Background(), be, Theme{Mono: true}, "linux") ctx, cancel := context.WithCancel(context.Background()) - in, _ := io.Pipe() + in, w := io.Pipe() + go func() { _, _ = w.Write([]byte("1")) }() // visita a seção Instalar: as seções só carregam na primeira visita done := make(chan error, 1) go func() { done <- runAreas(ctx, Options{Mono: true}, []tea.ProgramOption{tea.WithInput(in), tea.WithOutput(io.Discard), tea.WithWindowSize(80, 24)}, diff --git a/internal/tui/theme.go b/internal/tui/theme.go index c8e7e7d..7f51925 100644 --- a/internal/tui/theme.go +++ b/internal/tui/theme.go @@ -51,12 +51,17 @@ func (t Theme) Spin(frame int) string { return spinnerFrames[frame%len(spinnerFrames)] } -// Tick agenda o próximo quadro do spinner; com o movimento reduzido não agenda nada. +// tickWantMsg é o PEDIDO de um quadro do spinner: quem anima devolve Tick() e a raiz (Model) mantém UM só relógio de +// quadros para todas as abas. Antes cada aba agendava o seu e todo quadro ia a todas as abas, que agendavam outro +// cada uma: com K abas carregando os quadros multiplicavam por K a cada 100 ms (partida travada). +type tickWantMsg struct{} + +// Tick pede o próximo quadro do spinner; com o movimento reduzido não pede nada. func (t Theme) Tick() tea.Cmd { if t.NoMotion { return nil } - return tick() + return func() tea.Msg { return tickWantMsg{} } } // Paint pinta um trecho com cor SÓ no símbolo inicial (✓ ✗ ! ○ [x], o spinner), nunca na palavra ao lado: as cores From e6b4f74339db3389771db9a280cc80089a57d93e Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Mon, 16 Nov 2026 01:48:25 -0300 Subject: [PATCH 2/3] test(tui): tetos de tempo da partida folgados para o runner compartilhado (o problema real passava de segundos) --- internal/tui/partida_perf_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/tui/partida_perf_test.go b/internal/tui/partida_perf_test.go index 486a911..fb03a29 100644 --- a/internal/tui/partida_perf_test.go +++ b/internal/tui/partida_perf_test.go @@ -226,8 +226,8 @@ func TestPartidaPrimeiraTelaENaoBloqueiaTecla(t *testing.T) { cmd := m.Init() m.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) first := m.View().Content - if el := time.Since(t0); el > 100*time.Millisecond { - t.Fatalf("a primeira tela levou %v (teto 100 ms): Init/Update não podem esperar I/O", el) + if el := time.Since(t0); el > 250*time.Millisecond { + t.Fatalf("a primeira tela levou %v (teto 250 ms): Init/Update não podem esperar I/O", el) } if first == "" { t.Fatal("primeira tela vazia") @@ -254,8 +254,8 @@ func TestPartidaPrimeiraTelaENaoBloqueiaTecla(t *testing.T) { } } t.Logf("seta tratada e desenhada em %v; %d quadros na partida", handled, l.ticks) - if handled > 30*time.Millisecond { - t.Fatalf("seta tratada e desenhada em %v (teto 30 ms)", handled) + if handled > 100*time.Millisecond { + t.Fatalf("seta tratada e desenhada em %v (teto 100 ms)", handled) } } @@ -268,8 +268,8 @@ func TestViewCom300AppsTemTeto(t *testing.T) { m.Update(tea.KeyPressMsg{Code: tea.KeyDown}) _ = m.View() } - if avg := time.Since(t0) / n; avg > 8*time.Millisecond { - t.Fatalf("tecla + View com 300 apps: %v em média (teto 8 ms)", avg) + if avg := time.Since(t0) / n; avg > 50*time.Millisecond { + t.Fatalf("tecla + View com 300 apps: %v em média (teto 50 ms; local ~0,2 ms, runner compartilhado ~9 ms)", avg) } } From 4742435f97c3ce0a74b04674e54c42be2d58bb10 Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Mon, 16 Nov 2026 01:55:40 -0300 Subject: [PATCH 3/3] =?UTF-8?q?test(tui):=20a=20seta=20da=20partida=20usa?= =?UTF-8?q?=20flag=20em=20vez=20de=20dura=C3=A7=C3=A3o=200=20(no=20Windows?= =?UTF-8?q?=20time.Since=20pode=20dar=200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/tui/partida_perf_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/tui/partida_perf_test.go b/internal/tui/partida_perf_test.go index fb03a29..0114a34 100644 --- a/internal/tui/partida_perf_test.go +++ b/internal/tui/partida_perf_test.go @@ -239,8 +239,9 @@ func TestPartidaPrimeiraTelaENaoBloqueiaTecla(t *testing.T) { sent := time.Now() l.msgs <- tea.KeyPressMsg{Code: tea.KeyDown} var handled time.Duration + done := false // não usar handled == 0: no Windows time.Since pode dar 0 para intervalos curtos end := time.After(2 * time.Second) - for handled == 0 { + for !done { select { case <-end: t.Fatal("a seta não foi tratada em 2 s: fila entupida") @@ -249,7 +250,7 @@ func TestPartidaPrimeiraTelaENaoBloqueiaTecla(t *testing.T) { _ = l.m.View() l.run(cmd) if _, ok := msg.(tea.KeyPressMsg); ok { - handled = time.Since(sent) + handled, done = time.Since(sent), true } } }