Skip to content

fix(test): destrava 2 timeouts em AIRecommendationsPanel.test.tsx (Bug #3/#4 do plano 10/10)#118

Merged
adm01-debug merged 1 commit into
mainfrom
fix/test-aiRecommendations-top-level-import
May 23, 2026
Merged

fix(test): destrava 2 timeouts em AIRecommendationsPanel.test.tsx (Bug #3/#4 do plano 10/10)#118
adm01-debug merged 1 commit into
mainfrom
fix/test-aiRecommendations-top-level-import

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 22, 2026

🎯 Objetivo

Destravar 2 testes que estavam dando timeout em AIRecommendationsPanel.test.tsx, derrubando os jobs Test Coverage e Lint, Typecheck & Test → Run tests do CI. Bugs #3 e #4 do plano "10/10".

🔬 Causa-raiz

Cada um dos 16 it() blocks do arquivo fazia:

it("...", async () => {
  const { AIRecommendationsPanel } = await import("@/components/ai/AIRecommendationsPanel");
  renderWithProviders(<AIRecommendationsPanel ... />);
  // assertions
});

Sob pool=threads + maxThreads=2 (config do vitest), o dynamic import dentro do test compete por CPU com workers paralelos (notavelmente magic-up-result-panel-keyboard.test.tsx, que tem 276 testes). Os 2 primeiros testes, que sofrem o cold import path, estouravam o testTimeout default de 5000ms.

Apenas os 2 primeiros testes falhavam porque:

  • Test 1: renders client form fields in default state — 5032ms
  • Test 2: shows product count in the action area — 5002ms
  • Test 3: já se beneficia do cache do require → 4222ms (passa)
  • Tests 4-16: < 200ms cada (cache quente)

✅ Fix

Mover o import { AIRecommendationsPanel } para o top-level do arquivo. vi.mock é hoisted automaticamente pelo vitest, então o mock de useAIRecommendations continua sendo aplicado antes do import resolver.

Diff cirúrgico: +1 / -16 linhas em 1 arquivo de teste. Zero mudança de código de produção.

🧪 Validação em laboratório

Clone fresh de main (1cb3b47), npm ci, node v20.18.0 (.nvmrc):

Antes do fix

Cenário Resultado
Arquivo isolado (npx vitest run AIRecommendationsPanel.test.tsx) 16/16 pass, tests=3244ms, teste 1 leva 2888ms
Suíte completa (npm run test:quality) 2/16 timeout em 5032ms + 5002ms

Depois do fix

Cenário Resultado
Arquivo isolado 16/16 pass, tests=666ms (~80% mais rápido)
Suíte completa AIRecommendationsPanel.test.tsx não está mais na lista de failures

⚠️ Descoberta importante: 24 falhas pré-existentes reveladas

Este fix desbloqueia a execução da suíte completa. Antes, o vitest output truncava após AIRecommendationsPanel consumir 15.5s do budget, escondendo outras falhas. Agora elas aparecem:

Arquivo Falhas Causa visível
tests/components/DevRoute.test.tsx 5 No routes matched location "/auth" + Unable to find Login Page
tests/components/NotificationDrawer-trigger-fetch-counters.test.tsx 4 (a investigar — provavelmente useAuth)
tests/components/AdminConexoesAccess.test.tsx 1 (a investigar)
tests/components/NotificationDrawer-debounce-config.test.tsx 6 (a investigar — provavelmente useAuth)
tests/components/NotificationDrawer-a11y.test.tsx 8 Error: useAuth must be used within an AuthProvider
Total 24 Pelo menos 2 causas-raiz diferentes

⚠️ Estas 24 falhas já existem na main hoje — apenas estavam escondidas pelo bug do AIRecommendationsPanel. Este PR é apenas o primeiro passo para destravar Bugs #3 e #4; serão necessários PRs adicionais para zerar.

Issues separadas serão abertas para cada arquivo, seguindo o princípio "1 melhoria por vez" definido pelo PO.

📊 Impacto

  • ✅ Reduz falhas no test:quality de 26 → 24 testes
  • ✅ Permite que CI rode a suite completa até o fim (revelando bugs antes ocultos)
  • ✅ Acelera o arquivo em 80% (3244ms → 666ms)
  • ⚠️ CI ainda continuará vermelho até as outras 5 issues serem resolvidas

🔄 Plano de rollback

Reverter este commit — não há dependências externas. Comportamento volta a ser:

  • 2 timeouts em AIRecommendationsPanel
  • 24 falhas escondidas (não aparecem no output)

✅ Checklist

  • Lab validation em clone fresh com npm ci
  • Arquivo isolado passa 16/16
  • Na suite completa, arquivo sai da lista de failures
  • vi.mock hoisting validado (mock continua aplicado)
  • Zero mudança em código de produção (apenas test file)
  • Pre-flight: nenhum PR aberto ataca o mesmo arquivo

📋 Status do plano "10/10"

# Bug Status
1 Migrations sync guard ✅ MERGED (PR #111, 5f3ec9d)
2 Edge Deno typecheck ✅ MERGED (PR #115, 0c650ca)
3 Test Coverage 🟡 PARCIAL — este PR fecha 2 das 26 falhas
4 quality > Run tests 🟡 PARCIAL — mesma situação
5 ESLint baseline gate ⏳ Pendente

Refs #3 (Test Coverage), #4 (Run tests)

🤖 Co-authored-by: Claude noreply@anthropic.com


Summary by cubic

Fixes two vitest timeouts in AIRecommendationsPanel.test.tsx by moving the component import to the top level. This unblocks CI test runs and speeds this file by ~80% (3244ms → 666ms).

Written for commit 86c5219. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • Testes
    • Refatoração dos testes automatizados do painel de recomendações de IA com otimização da estrutura de importação de componentes. Importações dinâmicas repetidas foram consolidadas no topo do arquivo para aumentar a manutenibilidade, performance e clareza do código de testes. Esta mudança é interna e não afeta a funcionalidade ou experiência do usuário.

Review Change Stack

Resolves 2 vitest timeouts (Test timed out in 5000ms) that broke the
'Test Coverage' job and the 'Lint, Typecheck & Test > Run tests' step
in CI.

Root cause: each of the 16 it() blocks was doing
`const { AIRecommendationsPanel } = await import("@/components/ai/AIRecommendationsPanel")`
inside the test body. Under vitest pool=threads + maxThreads=2, the
dynamic import competes for CPU with parallel workers (notably
magic-up-result-panel-keyboard.test.tsx with 276 tests) and blows past
the 5000ms testTimeout default — specifically on the first 2 tests
that hit the cold import path.

Fix: move the import to top-level of the test file. vi.mock is
hoisted automatically by vitest, so the mock for
useAIRecommendations is still applied before the import resolves.

Lab validation (clone fresh of main 1cb3b47):

Before:
- isolated: 16/16 pass, duration tests=3244ms, test 1 took 2888ms
- in test:quality suite: 2/16 timeout (5032ms + 5002ms)

After:
- isolated: 16/16 pass, duration tests=666ms (~80% faster)
- in test:quality suite: AIRecommendationsPanel no longer in failure
  list

Diff: +1 / -16 lines in a single test file. No production code change.

Note: this fix unmasks 24 pre-existing failures in 5 other test files
that were previously hidden because vitest output truncated after
AIRecommendationsPanel consumed 15.5s of the suite budget. Those will
be tracked in separate issues:
- DevRoute.test.tsx (5 failures, route "/auth" + Login Page)
- NotificationDrawer-trigger-fetch-counters.test.tsx (4, useAuth)
- AdminConexoesAccess.test.tsx (1)
- NotificationDrawer-debounce-config.test.tsx (6, useAuth)
- NotificationDrawer-a11y.test.tsx (8, useAuth)
Copilot AI review requested due to automatic review settings May 22, 2026 23:34
@vercel
Copy link
Copy Markdown

vercel Bot commented May 22, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 22, 2026 11:35pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6f85d1b7-97c4-46ec-bfcd-ca07cbb9d49a

📥 Commits

Reviewing files that changed from the base of the PR and between e96134c and 86c5219.

📒 Files selected for processing (1)
  • tests/components/quotes/AIRecommendationsPanel.test.tsx

Walkthrough

O PR refatora o arquivo de teste do AIRecommendationsPanel consolidando a importação do componente de dinâmica (repetida em múltiplos it()) para uma importação estática única no topo. Os testes mantêm funcionalidade e asserções idênticas.

Alterações

Refactor de importação estática

Layer / File(s) Resumo
Consolidação de importação estática
tests/components/quotes/AIRecommendationsPanel.test.tsx
Importação do AIRecommendationsPanel movida para o topo do arquivo (linha 51). Removidas todas as importações dinâmicas (await import(...)) dos testes de renderização (linhas 67–68), contagem de produtos (linhas 77–82) e desabilitação de botão (linhas 91–102). Lógica e asserções de teste permanecem intactas.

🎯 1 (Trivial) | ⏱️ ~3 minutos

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão a mudança principal: mover o import dinâmico de AIRecommendationsPanel para top-level, resolvendo 2 timeouts no arquivo de teste especificado.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/test-aiRecommendations-top-level-import

Comment @coderabbitai help to get the list of available commands and usage tips.

@supabase
Copy link
Copy Markdown

supabase Bot commented May 22, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Moves the AIRecommendationsPanel import from per-test dynamic await import(...) calls to a single top-level static import, fixing 2 timeouts in AIRecommendationsPanel.test.tsx caused by cold dynamic imports under pool=threads with maxThreads=2. Test-only change; vi.mock hoisting keeps the useAIRecommendations mock applied before the static import resolves.

Changes:

  • Add top-level import { AIRecommendationsPanel } from "@/components/ai/AIRecommendationsPanel".
  • Remove 16 duplicated const { AIRecommendationsPanel } = await import(...) lines inside it() blocks.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Re-trigger cubic

@adm01-debug
Copy link
Copy Markdown
Owner Author

✅ CI rodou — análise dos resultados

Run ID: 26317021529 (86c5219)

🟢 Jobs que passaram (6/8 core)

Job Tempo Status
Edge Functions — Deno typecheck 1m50s ✅ success
Cloud Status — testes + cobertura 23s ✅ success
Price Freshness — testes + cobertura 39s ✅ success
Smoke tests (rotas + health-check) 12s ✅ success
Hook tests (smoke + funcionais) 2m54s ✅ success
Ref-warning suite 30s ✅ success

🔴 Jobs que falharam — NÃO são regressão deste PR

1. Test Coverage — FAIL no step Run tests with coverage

Esperado. Este é o Bug #3 que rodou a suite completa pela primeira vez (porque meu fix destrava o vitest output). As 24 falhas que aparecem aqui são as pré-existentes documentadas nas issues:

2. Lint, Typecheck & Test — FAIL no step ESLint baseline gate

Não relacionado ao meu PR. Validei localmente com npm run lint:baseline:

❌ 3 problema(s) novo(s) de ESLint em 1 par(es) file:rule:
  • src/tests/AdminStandardRules.test.tsx [@typescript-eslint/naming-convention] baseline=0 → atual=3 (+3)
      WARN 107:16 Parameter name `Component` must match one of the following formats: camelCase
      WARN 108:23 Parameter name `Component` must match one of the following formats: camelCase
      WARN 113:60 Parameter name `PageComponent` must match one of the following formats: camelCase

Estes 3 warnings já existem no main — vêm de outro commit anterior. Provavelmente vieram do T-FIX-4 (PascalCase params para components). Este é o Bug #5 do plano "10/10" (ESLint baseline gate). Este PR não toca em AdminStandardRules.test.tsx — diff de 1 arquivo apenas (tests/components/quotes/AIRecommendationsPanel.test.tsx).

Drift positivo: meu fix eliminou 20 erros de ESLint no tests/components/quotes/AIRecommendationsPanel.test.tsx (provavelmente regras como no-await-in-loop ou similares aplicadas ao await import dentro de it()).

📊 Conclusão

Verificação Resultado
Meu fix funciona ✅ Sim (validado em lab + 6 jobs verdes)
Falhas do CI são minhas ❌ Não — 100% pré-existentes
AIRecommendationsPanel resolvido ✅ Sim
CI fica verde após merge ⚠️ Não — precisa fechar #119-#123 e Bug #5

🎯 Próximos passos sugeridos

  1. Mergear este PR (squash, conforme convenção do Sentinel)
  2. Decidir próxima prioridade:

Aguardo aprovação para merge. 🚀

@adm01-debug adm01-debug merged commit b0d19ba into main May 23, 2026
29 of 32 checks passed
@adm01-debug adm01-debug deleted the fix/test-aiRecommendations-top-level-import branch May 23, 2026 10:54
adm01-debug added a commit that referenced this pull request May 23, 2026
…soleto)

Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos.
Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124,
descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124).

Arquivos aplicados:

1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10
2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder)
3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene
4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px])

Arquivos DESCARTADOS do PR #125 original:
- tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117
- tests/components/quotes/AIRecommendationsPanel: reverteria #118
- docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation:
  Tudo já mergeado via #124
- useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor

Sanity checks confirmados:
- SpaceScene existe em src/pages/auth/AuthBranding.tsx
- testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342
- 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
adm01-debug added a commit that referenced this pull request May 23, 2026
…soleto) (#130)

Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos.
Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124,
descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124).

Arquivos aplicados:

1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10
2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder)
3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene
4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px])

Arquivos DESCARTADOS do PR #125 original:
- tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117
- tests/components/quotes/AIRecommendationsPanel: reverteria #118
- docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation:
  Tudo já mergeado via #124
- useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor

Sanity checks confirmados:
- SpaceScene existe em src/pages/auth/AuthBranding.tsx
- testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342
- 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
adm01-debug added a commit that referenced this pull request May 23, 2026
…#127

Documenta análise + decisão para cada um dos 3 PRs em conflito após #124:
- #125: fechado, branch chore/pr125-cherry-pick com 4 testes únicos
- #126: fechado, branch chore/pr126-cherry-pick com 2 CORS + 1 auditoria
- #127: DRAFT mantido (precisa sessão dedicada com npm install + typecheck)

Inclui:
- Análise arquivo-por-arquivo de cada PR
- Identificação de redundâncias vs main e reversões de #117/#118
- Plano de retomada do #127 (3-5h estimadas)
- Lições aprendidas para sessões futuras
- Limitação descoberta: MCP do GitHub não expõe github_create_pull_request
adm01-debug pushed a commit that referenced this pull request May 23, 2026
…main

Em response ao comentário do owner em #127:
> AIRecommendationsPanel.test.tsx: reverte top-level await import (do #118)
> para dynamic. Descartar este arquivo.

O arquivo foi modificado acidentalmente — provavelmente por auto-fix do pre-commit hook (prettier/eslint --fix em arquivos staged via lint-staged) numa das passagens deste PR. Não havia intenção de reverter o fix do #118.

Restaurado para origin/main (top-level import preservado).

https://claude.ai/code/session_01Gq8xgvgBr2e9yQ7tpZrYoG
adm01-debug added a commit that referenced this pull request May 23, 2026
…soleto)

Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos.
Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124,
descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124).

Arquivos aplicados:

1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10
2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder)
3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene
4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px])

Arquivos DESCARTADOS do PR #125 original:
- tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117
- tests/components/quotes/AIRecommendationsPanel: reverteria #118
- docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation:
  Tudo já mergeado via #124
- useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor

Sanity checks confirmados:
- SpaceScene existe em src/pages/auth/AuthBranding.tsx
- testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342
- 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
adm01-debug added a commit that referenced this pull request May 23, 2026
…soleto) (#134)

Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos.
Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124,
descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124).

Arquivos aplicados:

1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10
2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder)
3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene
4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px])

Arquivos DESCARTADOS do PR #125 original:
- tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117
- tests/components/quotes/AIRecommendationsPanel: reverteria #118
- docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation:
  Tudo já mergeado via #124
- useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor

Sanity checks confirmados:
- SpaceScene existe em src/pages/auth/AuthBranding.tsx
- testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342
- 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants