fix(test): destrava 2 timeouts em AIRecommendationsPanel.test.tsx (Bug #3/#4 do plano 10/10)#118
Conversation
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)
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughO PR refatora o arquivo de teste do AlteraçõesRefactor de importação estática
🎯 1 (Trivial) | ⏱️ ~3 minutos 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
There was a problem hiding this comment.
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 insideit()blocks.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
✅ CI rodou — análise dos resultadosRun ID: 26317021529 ( 🟢 Jobs que passaram (6/8 core)
🔴 Jobs que falharam — NÃO são regressão deste PR1.
|
| 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 |
🎯 Próximos passos sugeridos
- Mergear este PR (squash, conforme convenção do Sentinel)
- Decidir próxima prioridade:
- Opção A: Atacar test: NotificationDrawer-a11y.test.tsx — 8 falhas "useAuth must be used within an AuthProvider" #119 (NotificationDrawer-a11y, 8 falhas + hipótese de causa-raiz comum com test: NotificationDrawer-trigger-fetch-counters.test.tsx — 4 falhas (provavelmente mesma causa de #119) #120 e test: NotificationDrawer-debounce-config.test.tsx — 6 falhas (provavelmente mesma causa de #119) #121)
- Opção B: Pular para Bug fix(quotes): alinhar shipping_type=fob vs fob_pre em UI/RPC/dados #5 (ESLint baseline, 3 warnings só)
- Opção C: Atacar test: DevRoute.test.tsx — 5 falhas (rota /auth + Login Page não encontradas) #122 (DevRoute, 5 falhas) — causa-raiz isolada
Aguardo aprovação para merge. 🚀
…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)
…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)
…#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
…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
…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)
…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)
🎯 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:Sob
pool=threads+maxThreads=2(config do vitest), o dynamic import dentro do test compete por CPU com workers paralelos (notavelmentemagic-up-result-panel-keyboard.test.tsx, que tem 276 testes). Os 2 primeiros testes, que sofrem o cold import path, estouravam otestTimeoutdefault de 5000ms.Apenas os 2 primeiros testes falhavam porque:
renders client form fields in default state— 5032msshows product count in the action area— 5002ms✅ Fix
Mover o
import { AIRecommendationsPanel }para o top-level do arquivo.vi.mocké hoisted automaticamente pelo vitest, então o mock deuseAIRecommendationscontinua sendo aplicado antes do import resolver.Diff cirúrgico:
+1 / -16linhas 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
npx vitest run AIRecommendationsPanel.test.tsx)npm run test:quality)Depois do fix
AIRecommendationsPanel.test.tsxnão está mais na lista de failuresEste fix desbloqueia a execução da suíte completa. Antes, o vitest output truncava após
AIRecommendationsPanelconsumir 15.5s do budget, escondendo outras falhas. Agora elas aparecem:tests/components/DevRoute.test.tsxNo routes matched location "/auth"+Unable to find Login Pagetests/components/NotificationDrawer-trigger-fetch-counters.test.tsxtests/components/AdminConexoesAccess.test.tsxtests/components/NotificationDrawer-debounce-config.test.tsxtests/components/NotificationDrawer-a11y.test.tsxError: useAuth must be used within an AuthProvidermainhoje — apenas estavam escondidas pelo bug doAIRecommendationsPanel. 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
test:qualityde 26 → 24 testes🔄 Plano de rollback
Reverter este commit — não há dependências externas. Comportamento volta a ser:
AIRecommendationsPanel✅ Checklist
npm civi.mockhoisting validado (mock continua aplicado)📋 Status do plano "10/10"
5f3ec9d)0c650ca)Refs #3 (Test Coverage), #4 (Run tests)
🤖 Co-authored-by: Claude noreply@anthropic.com
Summary by cubic
Fixes two
vitesttimeouts 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).vitestpool=threads and maxThreads=2, the first two cold imports exceeded the 5s timeout.vi.mockhoisting keeps theuseAIRecommendationsmock applied.Written for commit 86c5219. Summary will update on new commits. Review in cubic
Summary by CodeRabbit