fix(ci): corrige causas-raiz dos jobs falhos do CI#24
Conversation
- telemetryService: fecha método logPerformance (erro de sintaxe que quebrava EnhancedErrorBoundary global → build, E2E e várias suítes) e troca any por unknown - hooks/products: exporta usePrefetchProduct no barrel (build do ProductCard) - cloud-status coverage: atualiza caminho useDevGate.ts → admin/useDevGate.ts - seller-scope: anota queries de quotes protegidas por RLS com // rls-allow - skeleton snapshot: atualiza CatalogSkeleton (gaps responsivos) - quoteService: tipa any pré-existentes para passar no lint https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
O checker compara erros (2) e warnings (1) por (file,rule), mas o gerador congelava apenas erros — então todo warning contava como regressão e o gate nunca passava. Gerador agora congela ambas as severidades; baseline regenerado. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
|
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 (8)
WalkthroughAtualiza baseline do ESLint (agrega warnings), adiciona script/gate de cobertura para CloudStatus, fixa TZ do Vitest; refatora Header/MainLayout/Sidebar; melhora tipagem em quoteService/telemetryService; reorganiza exports de hooks e atualiza muitos testes/mocks/paths. ChangesRepo-wide updates and test realignment
Sequence Diagram(s)sequenceDiagram
participant Dev as Dev scripts
participant ESLintGen as eslint-baseline-generate
participant Baseline as .eslint-baseline.json
participant Vitest as Vitest
participant CoverageGate as check-cloud-status-coverage
Dev->>ESLintGen: run generator
ESLintGen->>Baseline: write errors + warnings snapshot
Dev->>Vitest: run tests (TZ set)
Vitest->>CoverageGate: provide coverage-summary.json
CoverageGate->>Dev: validate thresholds for CloudStatusBanner + useDevGate
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
|
- Reescreve imports de hooks/pages movidos para subpastas (ex.: @/hooks/useDebounce → @/hooks/common/useDebounce; @/pages/Auth → @/pages/auth/Auth) e caminhos corrompidos (@/hooks/productss → @/hooks/products/useProducts) - Mescla vi.mock duplicados do mesmo módulo (só o último vencia): quotes, products, intelligence - NotificationDrawer: mocka @/hooks/ui/useNotifications (caminho real) - Resolve lint (no-duplicate-imports, consistent-type-imports) nos testes tocados https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
Os presets Opera GX tiveram a lightness reduzida para contraste 3:1 com texto branco (ver comentários em theme-presets.ts). Atualiza ZAPP_GX_HSL e literais inline nos testes de tema para os valores acessíveis atuais. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
ContinuousRockets foi absorvido por SpaceScene (animação por setInterval) e as classes do FeatureCard mudaram (rounded-3xl/h-[88px]/px-5). Atualiza os testes unit e visual para a implementação atual. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
…a obsoleta - unit/system/BridgeStatusBanner: não-dev não vê banner (decisão de produto: restrito ao gate de infra dev) - remove tests/components/BridgeStatusBanner.test.tsx (arquitetura monolítica pré-refactor; superado por unit/system + tests/hooks/useBridgeStatusBanner) https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
- DevInfraGate/DevOnlyBridgeOverlay/BridgeMetricsOverlay: gate é por isDev (strict, role dev real), não isAllowed — atualiza matrizes e mocks - DevRoute: anon redireciona para /auth (não /login) https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
AdminRoute, ProtectedRoute e testes de árvore de rotas: anon redireciona para /auth. Atualiza as rotas mock dos testes correspondentes. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
test.env.TZ é tarde demais (ICU cacheia o fuso no startup do worker), fazendo snapshots com "Hora local" divergirem em runners UTC (CI/sandbox). Seta process.env.TZ no topo do vitest.config antes dos workers nascerem. Também completa o mock de authService.signOut em AuthContext.test. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
Header referenciava `sidebarOpen` (fora de escopo) em aria-label/aria-expanded → ReferenceError ao montar. Adiciona prop isMenuOpen (passada pelo MainLayout). Remove código morto (imports/vars não usados) para passar no lint e estabiliza o teste de integridade stubando os filhos assíncronos do Header. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
O guard de design SidebarNoShadow proíbe border-primary no nav (vira glow em dark mode). Badges de contagem mantêm bg-primary/20 + shadow sem desfoque. https://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
…a spy do functions.invoke
…_pre exige frete>0)
…error_description)
…ilitado (era código cru)
…o (forma de pagamento)
…ut movido, não removido)
…e corrige path FiltersPage movida
…re-render infinito/hang)
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a7603e13f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const m = raw.toLowerCase(); | ||
| if (m.includes('unsupported provider') || m.includes('provider is not enabled')) { | ||
| return 'provider_is_not_enabled'; | ||
| return 'O login com Google ainda não está habilitado. Use e-mail e senha por enquanto.'; |
There was a problem hiding this comment.
Preserve provider error code for OAuth config failures
Return a stable error key here (e.g. provider_is_not_enabled) instead of a free-form sentence: Auth routes this callback through resolveOAuthError, which classifies config errors via known keys and sets isConfig. With the new literal message, that classification is missed, so the UI falls back to a generic error and incorrectly shows the “Tentar Google Novamente” retry action for a non-recoverable provider-disabled configuration, leading users into repeated failed retries.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
Este PR foca em destravar o CI no main corrigindo causas-raiz de falhas de build/lint e alinhando testes/imports após refactors (especialmente a reorganização de hooks e ajustes de rotas/gates).
Changes:
- Corrige breakages de build (telemetry service) e de barrel exports (hooks/products), além de ajustar scripts de gates do CI (cloud-status e eslint baseline).
- Padroniza/atualiza imports e mocks de testes para a nova estrutura de pastas (admin/auth/products/common/ui/intelligence/simulation/mockup).
- Ajusta comportamento/expectativas de testes e alguns componentes de layout/nav para refletir regras atuais (DevOnly strict, rotas públicas, snapshots e TZ).
Reviewed changes
Copilot reviewed 146 out of 147 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| vitest.config.ts | Fixa TZ em nível de processo para estabilizar snapshots dependentes de locale/hora. |
| tests/unit/system/BridgeStatusBanner.test.tsx | Atualiza imports/mocks e expectativa para gate dev-only (não renderiza p/ não-dev). |
| tests/unit/system/BridgeMetricsPerformance.test.tsx | Atualiza import/mock do useDevGate para novo caminho. |
| tests/unit/system/BridgeMetricsOverlay.test.tsx | Ajusta mock de useDevGate para incluir isDev e renomeia cenário. |
| tests/unit/syntax-integrity.test.tsx | Stub de filhos assíncronos do Header para evitar hangs em smoke test de render. |
| tests/unit/quote-stepper-ui.test.tsx | Ajusta assertions para novas classes/ordem de conectores no stepper. |
| tests/unit/quote-calculations.test.ts | Alinha teste ao arredondamento monetário (2 casas) em calculateItemTotal. |
| tests/unit/autosave-migration.test.ts | Atualiza import do hook após refactor de paths. |
| tests/ssr/useDevGate.ssr.test.tsx | Atualiza import do useDevGate para hooks/admin. |
| tests/pages/QuoteBuilder.test.ts | Corrige import quebrado (productss → products/useProducts). |
| tests/pages/ProductDetailHero.buttonColors.test.tsx | Atualiza path da página após reorganização de pages/products. |
| tests/pages/ProductDetail.test.ts | Atualiza import de helpers de produtos para novo módulo. |
| tests/pages/MockupHistoryPage.test.tsx | Atualiza import dinâmico da página para novo path (pages/mockups). |
| tests/pages/AdminVideoVariantsPage.test.tsx | Atualiza mock do hook para hooks/products. |
| tests/pages/AdminTelemetriaPage.test.tsx | Ajusta teste para validar conteúdo (layout agora via rota). |
| tests/pages/AdminLoginAttemptsPage.test.tsx | Atualiza mock para hooks/auth/useLoginAttempts. |
| tests/lib/theme-radius-smoke.test.ts | Atualiza expectativa do HSL primário (GX preset). |
| tests/lib/theme-presets.test.ts | Atualiza valores HSL esperados para presets GX (paridade/contraste). |
| tests/lib/colorSystem-utils.test.ts | Atualiza import/types para hooks/products/useColorSystem. |
| tests/integration/tecnicas-pricing-flow.test.tsx | Atualiza import para hooks/simulation/useCustomizationPrice. |
| tests/integration/simulator-wizard-pricing-parity.test.ts | Atualiza tipos/mocks/imports para hooks/simulation/useGravacaoPriceV2. |
| tests/integration/simulation-orchestrator.test.ts | Corrige spy em supabase.functions.invoke estabilizando instância e setup. |
| tests/hooks/useWorkspaceNotifications.test.ts | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-unread-count.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-prefetch.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-fetch-error.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-cache-persistence.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-cache-invalidation.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-cache-freshness.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useWorkspaceNotifications-badge-render-log.test.tsx | Atualiza import do hook para hooks/ui. |
| tests/hooks/useVoiceAgent.test.ts | Atualiza import para hooks/intelligence/useVoiceAgent. |
| tests/hooks/useVideoVariantLinks.test.ts | Atualiza import para hooks/products/useVideoVariantLinks. |
| tests/hooks/useUrlState.test.tsx | Atualiza import para hooks/common/useUrlState. |
| tests/hooks/useSupplierComparison.test.ts | Atualiza imports e ajusta expectativa ao “shape de query” ({data,isLoading}). |
| tests/hooks/useSpeechRecognition.test.ts | Atualiza import para hooks/intelligence/useSpeechRecognition. |
| tests/hooks/useSellerCarts.test.tsx | Atualiza import para hooks/products/useSellerCarts. |
| tests/hooks/useSearch.test.ts | Atualiza import para hooks/common/useSearch e type para products/useProducts. |
| tests/hooks/useScroll.test.ts | Atualiza import para hooks/ui/useScroll. |
| tests/hooks/useSalesGoals.test.tsx | Atualiza import para hooks/intelligence/useSalesGoals. |
| tests/hooks/useReplenishmentsSelectionMode.test.ts | Atualiza import para hooks/products/useReplenishmentsSelectionMode. |
| tests/hooks/useRBAC.test.tsx | Atualiza import para hooks/auth/useRBAC. |
| tests/hooks/useQuoteHistory.test.ts | Atualiza import para hooks/quotes/useQuoteHistory. |
| tests/hooks/useProducts.test.ts | Atualiza import para hooks/products/useProducts. |
| tests/hooks/useProductMatch-gaps.test.ts | Atualiza imports para hooks/products/* e ajusta expectativas de retorno. |
| tests/hooks/useProductAnalytics.test.tsx | Atualiza import para hooks/products/useProductAnalytics. |
| tests/hooks/usePasswordBreachCheck.test.tsx | Atualiza import para hooks/auth/usePasswordBreachCheck. |
| tests/hooks/useOnboarding.test.tsx | Atualiza import para hooks/ui/useOnboarding. |
| tests/hooks/useMockupTechniques.test.ts | Atualiza import para hooks/mockup/useMockupTechniques. |
| tests/hooks/useMockupGenerator.test.ts | Atualiza mocks/imports para hooks/mockup/useMockupGenerator. |
| tests/hooks/useMagicUpGeneration-onda5.test.tsx | Atualiza import para hooks/intelligence/useMagicUpGeneration. |
| tests/hooks/useLoginRateLimit.test.ts | Move testes para usar helpers de rate-limit em lib/auth/rate-limit. |
| tests/hooks/useLoginAttempts.test.ts | Atualiza import para hooks/auth/useLoginAttempts. |
| tests/hooks/useKitBuilder-extended.test.ts | Atualiza import para hooks/kit-builder/useKitUndoRedo. |
| tests/hooks/useIPValidation.test.ts | Atualiza import para hooks/admin/useIPValidation. |
| tests/hooks/useGravacaoPriceV2.test.ts | Atualiza import para hooks/simulation/useGravacaoPriceV2. |
| tests/hooks/useGlobalSearch-voice.test.ts | Atualiza type import para hooks/intelligence/useVoiceAgent. |
| tests/hooks/useFavorites.test.ts | Atualiza import para hooks/favorites/useFavorites. |
| tests/hooks/useExpertConversations.test.tsx | Atualiza import para hooks/intelligence/useExpertConversations. |
| tests/hooks/useErrorHandler.test.ts | Atualiza import para hooks/ui/useErrorHandler. |
| tests/hooks/useDebouncedFilters.test.ts | Atualiza import para hooks/common/useDebouncedFilters. |
| tests/hooks/useDebounce.test.ts | Atualiza import para hooks/common/useDebounce. |
| tests/hooks/useDebounce-extended.test.ts | Atualiza import para hooks/common/useDebounce. |
| tests/hooks/useCustomizationPriceReactive.functional.test.ts | Atualiza import para hooks/simulation/useCustomizationPrice. |
| tests/hooks/useCustomizationPrice.functional.test.ts | Atualiza import para hooks/simulation/useCustomizationPrice. |
| tests/hooks/useCurrentOrgId.test.ts | Atualiza import para hooks/common/useCurrentOrgId. |
| tests/hooks/useContextualSuggestions.test.tsx | Atualiza import para hooks/intelligence/useContextualSuggestions. |
| tests/hooks/useConnectionTester.test.tsx | Atualiza import para hooks/intelligence/useConnectionTester. |
| tests/hooks/useComparisonWeights.test.ts | Atualiza import para hooks/comparison/useComparisonWeights. |
| tests/hooks/useComparisonScore.test.ts | Atualiza import para hooks/comparison/useComparisonScore. |
| tests/hooks/useComparison.test.tsx | Atualiza import para hooks/comparison/useComparison. |
| tests/hooks/useCollections.test.tsx | Atualiza import para hooks/collections/useCollections. |
| tests/hooks/useCollections.test.ts | Atualiza import para hooks/collections/useCollections. |
| tests/hooks/useCategories.test.tsx | Atualiza import para hooks/products/useCategories. |
| tests/hooks/useBulkSelection.test.ts | Atualiza import para hooks/common/useBulkSelection. |
| tests/hooks/useBulkSelection-extended.test.ts | Atualiza import para hooks/common/useBulkSelection. |
| tests/hooks/useBridgeStatusBanner.test.ts | Atualiza import para hooks/intelligence/useBridgeStatusBanner. |
| tests/hooks/useAllowedIPs.test.ts | Atualiza import para hooks/admin/useAllowedIPs. |
| tests/hooks/useAIRecommendations.test.ts | Atualiza import para hooks/intelligence/useAIRecommendations. |
| tests/hooks/useAccessSecurity.test.ts | Atualiza import para hooks/auth/useAccessSecurity. |
| tests/hooks/use2FA.test.ts | Atualiza import para hooks/auth/use2FA. |
| tests/hooks/simulation/simulationPriceFetcher.test.ts | Atualiza mock/import do useGravacaoPriceV2 para hooks/simulation. |
| tests/e2e/favorites-ui.test.tsx | Atualiza mock para hooks/ui/useOnboarding. |
| tests/e2e/auth-flow.test.tsx | Atualiza mock para hooks/admin/useIPValidation. |
| tests/contexts/AuthContext.test.tsx | Ajusta mock de .then para callback opcional (compat c/ uso sem cb). |
| tests/components/security/SecurityDashboard.test.tsx | Atualiza mocks para hooks novos (auth/use2FA, admin/useAllowedIPs). |
| tests/components/search/GlobalSearchPalette.test.tsx | Atualiza mocks para hooks movidos (common, intelligence). |
| tests/components/quotes/AIRecommendationsPanel.test.tsx | Atualiza import/mock para hooks/intelligence/useAIRecommendations. |
| tests/components/ProtectedRoute.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| tests/components/products/ProductSparkline.labels.test.tsx | Atualiza import/mock para hooks/intelligence/useSparklineSales. |
| tests/components/pages/MagicUp.test.tsx | Atualiza path da página e mocks de mockup hooks; assertion por testid de título. |
| tests/components/pages/Index.test.tsx | Atualiza mocks de hooks de produtos e busca após refactor. |
| tests/components/pages/FiltersPage.test.tsx | Atualiza path da página e mocks de hooks após reorganização. |
| tests/components/pages/Auth.test.tsx | Atualiza import de Auth page (novo path). |
| tests/components/pages/AdvancedPriceSearchPage.test.tsx | Atualiza path e assertion por testid do título. |
| tests/components/NotificationDrawer-unmount-cleanup.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/NotificationDrawer-trigger-to-fetch-timing.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/NotificationDrawer-trigger-fetch-counters.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/NotificationDrawer-debounce.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/NotificationDrawer-debounce-config.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/NotificationDrawer-a11y.test.tsx | Atualiza mock para hooks/ui/useNotifications. |
| tests/components/expert/ExpertChatDialog.test.tsx | Atualiza mock para hooks/intelligence/useExpertConversations. |
| tests/components/DevRoute.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| tests/components/DevOnlyBridgeOverlay.test.tsx | Atualiza import/mock de useDevGate e expectativas p/ modo strict (isDev). |
| tests/components/DevInfraGateStability.test.tsx | Atualiza import/mock de useDevGate para hooks/admin. |
| tests/components/DevInfraGateSSR.test.tsx | Atualiza import/mock de useDevGate para hooks/admin. |
| tests/components/DevInfraGateMatrix.test.tsx | Atualiza matriz de permissão para refletir gate strict por isDev. |
| tests/components/DevInfraGateHydration.test.tsx | Atualiza import/mock de useDevGate para hooks/admin. |
| tests/components/DevInfraGateErrorResilience.test.tsx | Atualiza import/mock de useDevGate para hooks/admin. |
| tests/components/BridgeStatusBanner.test.tsx | Remove teste duplicado/obsoleto do banner anterior. |
| tests/components/BridgeMetricsOverlay-ProdGate.test.tsx | Atualiza import/mock de useDevGate e expectativa para gate por isDev. |
| tests/components/AdminRoute.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| tests/components/AdminConexoesAccess.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| tests/admin/route-no-error-element.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| tests/admin/reduced-app-navigation.test.tsx | Atualiza rota pública de login nos testes (/auth). |
| src/tests/ScenarioSimulation.test.ts | Atualiza payloads de schema (inclui paymentMethod e refina shippingType). |
| src/tests/CatalogFilteringLogic.test.tsx | Atualiza import do hook para hooks/products/useCatalogFiltering e formata fixtures. |
| src/tests/AdminStandardRules.test.tsx | Remove check per-page de max-w (layout agora via rota/MainLayout). |
| src/tests/AdminLayout.test.tsx | Ajusta testes para validar conteúdo da página, não sidebar/layout via rota. |
| src/services/telemetryService.ts | Corrige sintaxe e troca any → unknown no payload/erros; fecha logPerformance. |
| src/services/quoteService.ts | Adiciona anotações // rls-allow: e tipa opções/arrays legados (any → unknown). |
| src/pages/auth/AuthBranding.visual.test.tsx | Atualiza assertions de classes após mudança de layout/translate interno. |
| src/pages/auth/AuthBranding.test.tsx | Migra teste de foguetes para SpaceScene (intervalo/removal). |
| src/pages/Auth.test.tsx | Ajusta teste para AnimatePresence (espera render async do Forgot Password). |
| src/pages/tests/SSOCallbackPage.test.tsx | Atualiza import e validação de query params de erro via URL. |
| src/pages/tests/FiltersPage.no-duplicate-sidebar.test.tsx | Atualiza caminho da página Filters após mover para pages/products. |
| src/lib/security/tests/security-integration.test.ts | Ajusta expectations ao allowlist mais estrito do sanitizeHtml (remove /). |
| src/hooks/products/index.ts | Adiciona export de usePrefetchProduct no barrel de products. |
| src/hooks/tests/useQuoteBuilderState.unit.test.tsx | Dedup de mocks e ajusta mensagens/fluxo esperado de validação. |
| src/hooks/tests/useQuoteBuilderState.shipping.test.tsx | Dedup/centraliza mocks de @/hooks/quotes e adiciona stub necessário. |
| src/hooks/tests/useCatalogState.unit.test.tsx | Evita loop de re-render em mocks retornando referências estáveis. |
| src/hooks/tests/useAdvancedFilters.unit.test.tsx | Corrige caminho do mock de useExternalDatabase. |
| src/contexts/AuthContext.test.tsx | Mantém authService.signOut real e ajusta testes para lidar com falha (catch) + RPC. |
| src/components/quotes/tests/QuoteBuilderDiscountAdvanced.test.tsx | Atualiza selectors para data-testid e validações de limite/markup. |
| src/components/quotes/tests/QuoteBuilderDiscount.test.ts | Remove teste duplicado/obsoleto do desconto. |
| src/components/layout/sidebar/SidebarNavGroup.tsx | Ajustes de estilo/active state e hardening de visibilidade por role/SSOT. |
| src/components/layout/sidebar/tests/SidebarNavGroup.suspense.test.tsx | Atualiza classe esperada para item ativo (bg-primary/10). |
| src/components/layout/sidebar/tests/SidebarNavGroup.history.test.tsx | Atualiza classe esperada para item ativo (bg-primary/10). |
| src/components/layout/MainLayout.tsx | Passa isMenuOpen ao Header, reordena/limpa imports e ajusta layout. |
| src/components/layout/Header.tsx | Consome isMenuOpen e ajusta UX/estilos; atualiza navegação e clusters. |
| src/components/auth/SocialLoginButtons.tsx | Melhora mensagens PT-BR do OAuth e pequenos ajustes de classe. |
| src/components/admin/connections/tests/ConnectionUI.test.tsx | Consolida mocks de hooks/intelligence e evita mocks duplicados. |
| src/components/admin/connections/tests/ConnectionsOverviewTable.test.tsx | Consolida mocks e reorganiza ordem para estabilidade. |
| scripts/eslint-baseline-generate.mjs | Passa a congelar warnings+errors (alinhado ao checker) e inclui contagens no payload. |
| scripts/check-cloud-status-coverage.mjs | Atualiza thresholds para novo caminho do useDevGate. |
| package.json | Atualiza comando test:cloud-status-coverage para incluir hooks/admin/useDevGate.ts. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| {!isCollapsed && item.badge !== null && ( | ||
| <span className="ml-auto min-w-[20px] rounded-full bg-primary/20 px-1.5 py-0.5 text-center text-[10px] font-semibold text-white shadow-[0_0_10px_rgba(var(--primary),0.2)]"> | ||
| {item.badge} | ||
| </span> | ||
| )} |
| @@ -170,5 +205,5 @@ export const quoteService = { | |||
| new_value: options?.newValue || null, | |||
| metadata: options?.metadata || {}, | |||
| interface HeaderProps { | ||
| onMenuToggle: () => void; | ||
| isMenuOpen?: boolean; | ||
| searchQuery: string; | ||
| onSearchChange: (query: string) => void; | ||
| } | ||
|
|
||
| export const Header = React.memo(function Header({ onMenuToggle, searchQuery, onSearchChange }: HeaderProps) { | ||
| export const Header = React.memo(function Header({ | ||
| onMenuToggle, | ||
| isMenuOpen = false, | ||
| }: HeaderProps) { |
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/services/quoteService.ts (1)
186-208:⚠️ Potential issue | 🟠 Major | ⚡ Quick winFalha silenciosa em
logHistorypode quebrar trilha de auditoria.O
inserté aguardado, mas oerrornão é checado. Em falha de escrita, o histórico é perdido sem sinalização.💡 Sugestão de ajuste
- await supabase.from('quote_history').insert({ + const { error } = await supabase.from('quote_history').insert({ quote_id: quoteId, user_id: userId, action, description, field_changed: options?.fieldChanged || null, old_value: options?.oldValue || null, new_value: options?.newValue || null, metadata: options?.metadata || {}, }); + if (error) throw error;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/services/quoteService.ts` around lines 186 - 208, The logHistory function awaits supabase.from('quote_history').insert but doesn't check the response for errors, so failed inserts silently drop audit records; update logHistory to inspect the insert result (the object returned by supabase.from('quote_history').insert), handle response.error by logging via your logger (or processLogger) and/or rethrowing an Error so callers know the audit write failed, and return or propagate the inserted data on success; specifically modify the call in logHistory that uses supabase.from('quote_history').insert to capture the result, check result.error, and act accordingly.
🧹 Nitpick comments (4)
src/components/quotes/__tests__/QuoteBuilderDiscountAdvanced.test.tsx (1)
11-19: ⚡ Quick winEvite
as anyno fixture deitems.Em Line 18, esse cast pode esconder quebra de contrato da
QuoteBuilderSummaryColumn. Prefira tipar o item com o tipo real esperado (ousatisfies).As per coding guidelines "any/unknown sem narrowing posterior".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/components/quotes/__tests__/QuoteBuilderDiscountAdvanced.test.tsx` around lines 11 - 19, O fixture em QuoteBuilderDiscountAdvanced.test.tsx usa um cast "as any" no item (items array) que pode mascarar quebras de contrato com a prop esperada por QuoteBuilderSummaryColumn; corrija importando e aplicando o tipo real esperado para cada item (por exemplo LineItem, QuoteItem ou o tipo exportado que a QuoteBuilderSummaryColumn aceita) ou use a cláusula TypeScript "satisfies" no objeto de fixture para garantir compatibilidade estrutural em vez de "as any", ajustando as propriedades do objeto conforme necessário para corresponder ao tipo importado.src/components/layout/MainLayout.tsx (1)
92-93: ⚡ Quick winPrefira atualização funcional para toggle de estado dependente.
Em linha 92 e 100, use
setSidebarOpen((prev) => !prev)em vez desetSidebarOpen(!sidebarOpen). O padrão funcional é mais seguro quando o novo estado depende do estado anterior, evitando possíveis inconsistências com closures em atualizações rápidas.Diff sugerido
- onToggle={() => setSidebarOpen(!sidebarOpen)} + onToggle={() => setSidebarOpen((prev) => !prev)} - onMenuToggle={() => setSidebarOpen(!sidebarOpen)} + onMenuToggle={() => setSidebarOpen((prev) => !prev)}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/components/layout/MainLayout.tsx` around lines 92 - 93, O handler de toggle usa setSidebarOpen(!sidebarOpen) o que pode causar condições de corrida; atualize ambas as ocorrências para a forma funcional setSidebarOpen(prev => !prev) (referências: setSidebarOpen, sidebarOpen, onToggle) para garantir que o novo estado seja calculado a partir do estado anterior.tests/contexts/AuthContext.test.tsx (1)
15-15: ⚡ Quick winRemove
anydo callback e use tipo explícito.As linhas 15, 111 e 167 usam
cb?: anynos mocks, enfraquecendo a tipagem. Declare o tipo da callback explicitamente conforme o contrato que ela usa:Sugestão
- then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve(); }), + then: vi.fn((cb?: (value: { error: null }) => unknown) => { + cb?.({ error: null }); + return Promise.resolve(); + }),Aplique o mesmo em todas as três linhas (15, 111, 167).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/contexts/AuthContext.test.tsx` at line 15, Replace the weak `any` callback types in the test mocks with an explicit callback signature matching the contract (a possibly-undefined callback that accepts an object with an `error` field). For example, change occurrences of `then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve(); })` in tests/contexts/AuthContext.test.tsx (the instances at lines 15, 111 and 167) to use a typed callback such as `cb?: (res: { error: Error | null }) => void` (or `cb?: (res: { error: null }) => void` if the tests always pass null) so the mock accurately reflects the callback shape used by the function under test.tests/unit/system/BridgeMetricsOverlay.test.tsx (1)
43-44: ⚡ Quick winRemova
as anydos mocks para recuperar segurança de tipo.Use
vi.mocked()no lugar dos castsas any. Isso se aplica a todas as ocorrências no arquivo (linhas 43, 44, 48, 54, 63, 95, 120). Vitest fornece tipagem adequada sem perder funcionalidade.Exemplo de fix
- (useDevGate as any).mockReturnValue({ isAllowed: true, isDev: true }); + vi.mocked(useDevGate).mockReturnValue({ isAllowed: true, isDev: true }); - (useBridgeMetrics as any).mockReturnValue(defaultMockValues); + vi.mocked(useBridgeMetrics).mockReturnValue(defaultMockValues);Aplica-se à guideline:
any/unknown sem narrowing posterior🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/unit/system/BridgeMetricsOverlay.test.tsx` around lines 43 - 44, Remova os casts "as any" dos mocks e use vi.mocked() para manter tipagem; por exemplo substitua (useDevGate as any).mockReturnValue(...) por vi.mocked(useDevGate).mockReturnValue(...). Faça a mesma troca para todas as ocorrências mencionadas (useDevGate, useBridgeMetrics e outras mockadas nas linhas indicadas) e, se necessário, garanta que "vi" do Vitest esteja disponível no escopo do teste.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/components/layout/Header.tsx`:
- Around line 262-263: Update the static aria-label attributes in Header.tsx so
they describe the button actions rather than the visual/icon names: replace
aria-label="GitCompare" and aria-label="Tema claro" with semantic, context-aware
labels (e.g., "Open Git compare panel" or "Toggle theme to light") and make them
dynamic where the state changes (e.g., use current theme to set aria-label in
the theme toggle). Locate the buttons by their className or aria-label
attributes in the Header component and ensure both instances (the one currently
labeled "GitCompare" and the theme toggle currently labeled "Tema claro") use
clear action-oriented, localized strings that reflect their function for screen
readers.
- Around line 237-239: The dynamic import() calls used inside the Header
component's mouse event handlers (e.g., import('`@/pages/products/FavoritesPage`')
and the similar import for the Cart page) are fire-and-forget promises; update
those calls to attach a .catch(...) handler so rejections are handled locally
(for example, call .catch(err => processLogger.warn('Preload failed', err)) or
console.error) rather than relying on global handlers; locate the
onMouseEnter/onMouseOver handlers in Header.tsx and add .catch to each dynamic
import invocation.
In `@src/components/layout/sidebar/SidebarNavGroup.tsx`:
- Around line 204-207: The current conditional uses item.badge !== null which
still allows undefined and renders an empty badge; change the checks where the
span is rendered (the condition using isCollapsed and item.badge) to explicitly
guard against both null and undefined by using item.badge != null (nullish
check) or an explicit typeof check (e.g., item.badge !== null && item.badge !==
undefined); update both occurrences that render the badge (the span with class
"ml-auto ... text-[10px] ..." and the similar block around lines 226-229) so the
badge only renders when item.badge is neither null nor undefined.
In `@src/contexts/AuthContext.test.tsx`:
- Around line 109-111: The test for the happy path of signOut is silencing real
failures by appending .catch(() => {}) to result.current.signOut; remove the
.catch handler so the test awaits the promise directly (e.g., await
result.current.signOut()) and thus fails on regressions — update the assertion
block using result.current.signOut (referencing the same call in the test) and
keep the mockResolvedValue({ error: null }) setup for the successful case.
In `@src/services/quoteService.ts`:
- Around line 113-125: The chained deletions for quote items and their
personalizations can leave the quote in a partially-updated state because their
Supabase responses aren't checked; update the block in quoteService.ts to
capture each delete's result (e.g., store the await result for the
quote_item_personalizations delete and the quote_items delete), check for
response.error after each operation and abort/throw (or return an error) if any
delete fails, and include the quoteId and failing table
('quote_item_personalizations' or 'quote_items') in the error handling to ensure
the caller can roll back or surface the failure.
In `@tests/unit/quote-calculations.test.ts`:
- Around line 135-142: The test for calculateItemTotal uses toBeCloseTo(..., 2)
which can hide rounding regressions; update the assertion to require exact
2-decimal monetary rounding (use expect(calculateItemTotal(params)).toBe(3.52))
or adjust calculateItemTotal to explicitly round to two decimals and then assert
equality; reference the calculateItemTotal function and ensure the test verifies
the function returns a value already rounded to cents rather than an approximate
match.
---
Outside diff comments:
In `@src/services/quoteService.ts`:
- Around line 186-208: The logHistory function awaits
supabase.from('quote_history').insert but doesn't check the response for errors,
so failed inserts silently drop audit records; update logHistory to inspect the
insert result (the object returned by supabase.from('quote_history').insert),
handle response.error by logging via your logger (or processLogger) and/or
rethrowing an Error so callers know the audit write failed, and return or
propagate the inserted data on success; specifically modify the call in
logHistory that uses supabase.from('quote_history').insert to capture the
result, check result.error, and act accordingly.
---
Nitpick comments:
In `@src/components/layout/MainLayout.tsx`:
- Around line 92-93: O handler de toggle usa setSidebarOpen(!sidebarOpen) o que
pode causar condições de corrida; atualize ambas as ocorrências para a forma
funcional setSidebarOpen(prev => !prev) (referências: setSidebarOpen,
sidebarOpen, onToggle) para garantir que o novo estado seja calculado a partir
do estado anterior.
In `@src/components/quotes/__tests__/QuoteBuilderDiscountAdvanced.test.tsx`:
- Around line 11-19: O fixture em QuoteBuilderDiscountAdvanced.test.tsx usa um
cast "as any" no item (items array) que pode mascarar quebras de contrato com a
prop esperada por QuoteBuilderSummaryColumn; corrija importando e aplicando o
tipo real esperado para cada item (por exemplo LineItem, QuoteItem ou o tipo
exportado que a QuoteBuilderSummaryColumn aceita) ou use a cláusula TypeScript
"satisfies" no objeto de fixture para garantir compatibilidade estrutural em vez
de "as any", ajustando as propriedades do objeto conforme necessário para
corresponder ao tipo importado.
In `@tests/contexts/AuthContext.test.tsx`:
- Line 15: Replace the weak `any` callback types in the test mocks with an
explicit callback signature matching the contract (a possibly-undefined callback
that accepts an object with an `error` field). For example, change occurrences
of `then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve();
})` in tests/contexts/AuthContext.test.tsx (the instances at lines 15, 111 and
167) to use a typed callback such as `cb?: (res: { error: Error | null }) =>
void` (or `cb?: (res: { error: null }) => void` if the tests always pass null)
so the mock accurately reflects the callback shape used by the function under
test.
In `@tests/unit/system/BridgeMetricsOverlay.test.tsx`:
- Around line 43-44: Remova os casts "as any" dos mocks e use vi.mocked() para
manter tipagem; por exemplo substitua (useDevGate as any).mockReturnValue(...)
por vi.mocked(useDevGate).mockReturnValue(...). Faça a mesma troca para todas as
ocorrências mencionadas (useDevGate, useBridgeMetrics e outras mockadas nas
linhas indicadas) e, se necessário, garanta que "vi" do Vitest esteja disponível
no escopo do teste.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ee71ca26-2ce2-4d3e-a55c-3278d95dc539
⛔ Files ignored due to path filters (1)
tests/admin/__snapshots__/skeleton-snapshots.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (146)
.eslint-baseline.jsonpackage.jsonscripts/check-cloud-status-coverage.mjsscripts/eslint-baseline-generate.mjssrc/components/admin/connections/__tests__/ConnectionUI.test.tsxsrc/components/admin/connections/__tests__/ConnectionsOverviewTable.test.tsxsrc/components/auth/SocialLoginButtons.tsxsrc/components/layout/Header.tsxsrc/components/layout/MainLayout.tsxsrc/components/layout/sidebar/SidebarNavGroup.tsxsrc/components/layout/sidebar/__tests__/SidebarNavGroup.history.test.tsxsrc/components/layout/sidebar/__tests__/SidebarNavGroup.suspense.test.tsxsrc/components/quotes/__tests__/QuoteBuilderDiscount.test.tssrc/components/quotes/__tests__/QuoteBuilderDiscountAdvanced.test.tsxsrc/contexts/AuthContext.test.tsxsrc/hooks/__tests__/useAdvancedFilters.unit.test.tsxsrc/hooks/__tests__/useCatalogState.unit.test.tsxsrc/hooks/__tests__/useQuoteBuilderState.shipping.test.tsxsrc/hooks/__tests__/useQuoteBuilderState.unit.test.tsxsrc/hooks/products/index.tssrc/lib/security/__tests__/security-integration.test.tssrc/pages/Auth.test.tsxsrc/pages/__tests__/FiltersPage.no-duplicate-sidebar.test.tsxsrc/pages/__tests__/SSOCallbackPage.test.tsxsrc/pages/auth/AuthBranding.test.tsxsrc/pages/auth/AuthBranding.visual.test.tsxsrc/services/quoteService.tssrc/services/telemetryService.tssrc/tests/AdminLayout.test.tsxsrc/tests/AdminStandardRules.test.tsxsrc/tests/CatalogFilteringLogic.test.tsxsrc/tests/ScenarioSimulation.test.tstests/admin/reduced-app-navigation.test.tsxtests/admin/route-no-error-element.test.tsxtests/components/AdminConexoesAccess.test.tsxtests/components/AdminRoute.test.tsxtests/components/BridgeMetricsOverlay-ProdGate.test.tsxtests/components/BridgeStatusBanner.test.tsxtests/components/DevInfraGateErrorResilience.test.tsxtests/components/DevInfraGateHydration.test.tsxtests/components/DevInfraGateMatrix.test.tsxtests/components/DevInfraGateSSR.test.tsxtests/components/DevInfraGateStability.test.tsxtests/components/DevOnlyBridgeOverlay.test.tsxtests/components/DevRoute.test.tsxtests/components/NotificationDrawer-a11y.test.tsxtests/components/NotificationDrawer-debounce-config.test.tsxtests/components/NotificationDrawer-debounce.test.tsxtests/components/NotificationDrawer-trigger-fetch-counters.test.tsxtests/components/NotificationDrawer-trigger-to-fetch-timing.test.tsxtests/components/NotificationDrawer-unmount-cleanup.test.tsxtests/components/ProtectedRoute.test.tsxtests/components/expert/ExpertChatDialog.test.tsxtests/components/pages/AdvancedPriceSearchPage.test.tsxtests/components/pages/Auth.test.tsxtests/components/pages/FiltersPage.test.tsxtests/components/pages/Index.test.tsxtests/components/pages/MagicUp.test.tsxtests/components/products/ProductSparkline.labels.test.tsxtests/components/quotes/AIRecommendationsPanel.test.tsxtests/components/search/GlobalSearchPalette.test.tsxtests/components/security/SecurityDashboard.test.tsxtests/contexts/AuthContext.test.tsxtests/e2e/auth-flow.test.tsxtests/e2e/favorites-ui.test.tsxtests/hooks/simulation/simulationPriceFetcher.test.tstests/hooks/use2FA.test.tstests/hooks/useAIRecommendations.test.tstests/hooks/useAccessSecurity.test.tstests/hooks/useAllowedIPs.test.tstests/hooks/useBridgeStatusBanner.test.tstests/hooks/useBulkSelection-extended.test.tstests/hooks/useBulkSelection.test.tstests/hooks/useCategories.test.tsxtests/hooks/useCollections.test.tstests/hooks/useCollections.test.tsxtests/hooks/useComparison.test.tsxtests/hooks/useComparisonScore.test.tstests/hooks/useComparisonWeights.test.tstests/hooks/useConnectionTester.test.tsxtests/hooks/useContextualSuggestions.test.tsxtests/hooks/useCurrentOrgId.test.tstests/hooks/useCustomizationPrice.functional.test.tstests/hooks/useCustomizationPriceReactive.functional.test.tstests/hooks/useDebounce-extended.test.tstests/hooks/useDebounce.test.tstests/hooks/useDebouncedFilters.test.tstests/hooks/useErrorHandler.test.tstests/hooks/useExpertConversations.test.tsxtests/hooks/useFavorites.test.tstests/hooks/useGlobalSearch-voice.test.tstests/hooks/useGravacaoPriceV2.test.tstests/hooks/useIPValidation.test.tstests/hooks/useKitBuilder-extended.test.tstests/hooks/useLoginAttempts.test.tstests/hooks/useLoginRateLimit.test.tstests/hooks/useMagicUpGeneration-onda5.test.tsxtests/hooks/useMockupGenerator.test.tstests/hooks/useMockupTechniques.test.tstests/hooks/useOnboarding.test.tsxtests/hooks/usePasswordBreachCheck.test.tsxtests/hooks/useProductAnalytics.test.tsxtests/hooks/useProductMatch-gaps.test.tstests/hooks/useProducts.test.tstests/hooks/useQuoteHistory.test.tstests/hooks/useRBAC.test.tsxtests/hooks/useReplenishmentsSelectionMode.test.tstests/hooks/useSalesGoals.test.tsxtests/hooks/useScroll.test.tstests/hooks/useSearch.test.tstests/hooks/useSellerCarts.test.tsxtests/hooks/useSpeechRecognition.test.tstests/hooks/useSupplierComparison.test.tstests/hooks/useUrlState.test.tsxtests/hooks/useVideoVariantLinks.test.tstests/hooks/useVoiceAgent.test.tstests/hooks/useWorkspaceNotifications-badge-render-log.test.tsxtests/hooks/useWorkspaceNotifications-cache-freshness.test.tsxtests/hooks/useWorkspaceNotifications-cache-invalidation.test.tsxtests/hooks/useWorkspaceNotifications-cache-persistence.test.tsxtests/hooks/useWorkspaceNotifications-fetch-error.test.tsxtests/hooks/useWorkspaceNotifications-prefetch.test.tsxtests/hooks/useWorkspaceNotifications-unread-count.test.tsxtests/hooks/useWorkspaceNotifications.test.tstests/integration/simulation-orchestrator.test.tstests/integration/simulator-wizard-pricing-parity.test.tstests/integration/tecnicas-pricing-flow.test.tsxtests/lib/colorSystem-utils.test.tstests/lib/theme-presets.test.tstests/lib/theme-radius-smoke.test.tstests/pages/AdminLoginAttemptsPage.test.tsxtests/pages/AdminTelemetriaPage.test.tsxtests/pages/AdminVideoVariantsPage.test.tsxtests/pages/MockupHistoryPage.test.tsxtests/pages/ProductDetail.test.tstests/pages/ProductDetailHero.buttonColors.test.tsxtests/pages/QuoteBuilder.test.tstests/ssr/useDevGate.ssr.test.tsxtests/unit/autosave-migration.test.tstests/unit/quote-calculations.test.tstests/unit/quote-stepper-ui.test.tsxtests/unit/syntax-integrity.test.tsxtests/unit/system/BridgeMetricsOverlay.test.tsxtests/unit/system/BridgeMetricsPerformance.test.tsxtests/unit/system/BridgeStatusBanner.test.tsxvitest.config.ts
💤 Files with no reviewable changes (2)
- src/components/quotes/tests/QuoteBuilderDiscount.test.ts
- tests/components/BridgeStatusBanner.test.tsx
There was a problem hiding this comment.
1 issue found across 147 files
Partial review: This PR has more than 50 files, so cubic reviewed the highest-priority files first. During the trial, paid plans get a higher file limit.
You can try an ultrareview to bypass the file limit, comment @cubic-dev-ai ultrareview. Learn more.
Fix all with cubic | Re-trigger cubic
- SocialLoginButtons: preserva CHAVE estável (provider_is_not_enabled) p/ Auth classificar isConfig (evita botão de retry em erro não-recuperável); toast exibe a cópia humana via resolveOAuthError - quoteService: checa error em logHistory e nas deleções de updateQuote; usa ?? - SidebarNavGroup: badge só renderiza com valor real (exclui undefined) - Header: aria-labels semânticos/dinâmicos; .catch em imports de preload; remove props searchQuery/onSearchChange não usados - MainLayout: setSidebarOpen funcional; remove estado órfão de busca - AuthContext.test: signOut real no happy-path (sem catch) + callbacks tipados - quote-calculations: toBe(3.52) estrito
There was a problem hiding this comment.
1 issue found across 8 files (changes from recent commits).
You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/contexts/AuthContext.test.tsx">
<violation number="1" location="src/contexts/AuthContext.test.tsx:110">
P1: Removing `.catch(() => {})` breaks the test — `signOut()` uses `try/finally` (not `try/catch`), so errors from the mocked `supabase.auth.signOut` rejection still propagate and will cause the test to fail inside `act`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
| @@ -99,6 +110,7 @@ describe('AuthContext', () => { | |||
| await result.current.signOut(); | |||
There was a problem hiding this comment.
P1: Removing .catch(() => {}) breaks the test — signOut() uses try/finally (not try/catch), so errors from the mocked supabase.auth.signOut rejection still propagate and will cause the test to fail inside act.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/contexts/AuthContext.test.tsx, line 110:
<comment>Removing `.catch(() => {})` breaks the test — `signOut()` uses `try/finally` (not `try/catch`), so errors from the mocked `supabase.auth.signOut` rejection still propagate and will cause the test to fail inside `act`.</comment>
<file context>
@@ -107,7 +107,7 @@ describe('AuthContext', () => {
await act(async () => {
- await result.current.signOut().catch(() => {});
+ await result.current.signOut();
});
</file context>
There was a problem hiding this comment.
Falso-positivo neste caso. Este teste (calls log_user_logout RPC before signing out) define explicitamente vi.mocked(supabase.auth.signOut).mockResolvedValue({ error: null }), então authService.signOut() resolve — não há rejeição para o try/finally repropagar. O .catch() aqui era redundante e mascararia regressões (era o ponto do CodeRabbit). O teste de falha (clears state even if remote signOut fails) mantém o .catch() justamente porque lá o signOut rejeita.
Verificado localmente: vitest run src/contexts/AuthContext.test.tsx → 2/2 passam. Sem alteração necessária.
Generated by Claude Code
There was a problem hiding this comment.
Thanks for the feedback! I've saved this as a new learning to improve future reviews.
…&error_description={msg})
Componente redireciona /login com formato estruturado (PR #24); asserts liam o param
errado. Tests 1/2/3b agora parseiam error_description (User cancelled / Boom / invalid_grant).
Resumo
Corrige as causas-raiz que derrubavam vários jobs do GitHub Actions no
main.Correções (verificadas localmente)
src/services/telemetryService.ts— faltava}fechandologPerformance. ComoEnhancedErrorBoundary(global) importa esse módulo, o erro de transform quebrava build de produção, E2E smoke, Test Coverage e a suíte strict-ref. Também trocadosany→unknownpara passar no lint.usePrefetchProductnão era exportado pelo barrelsrc/hooks/products/index.ts(importado porProductCard). Export adicionado.src/hooks/useDevGate.ts→src/hooks/admin/useDevGate.tsempackage.jsonescripts/check-cloud-status-coverage.mjs.// rls-allow:nas queries dequotes(protegidas por RLS) emquoteService.ts;anylegados tipados.CatalogSkeletonatualizado (gaps responsivosgap-x-4 sm:gap-x-6 lg:gap-x-8).Jobs destravados (verificados)
Cloud Status,Seller-scope checker,Ref-warning suite (strict-ref),Hook tests (smoke),Production Build,ESLint baseline gate.Pendências (não cobertas — escopo grande, pré-existente)
refreshSession/getAuthenticatorAssuranceLevelnão são funções nos mocks),vi.mockfaltando exports (useQuotes,useDevGate, etc.), e wrappers semAuthProvider. É dívida de teste espalhada por ~132 arquivos.deno.land/esm.sh/jsr.io). 60/79 funções passam limpas; as 19 restantes só falharam por download bloqueado, sem erros de tipo reais observados.Test plan
node scripts/check-seller-scope.mjsnpm run test:cloud-status-coveragenpx vite build— OK (5733 módulos)node scripts/check-eslint-baseline.mjs— sem regressõeshttps://claude.ai/code/session_01PXGYiBingJZbsFqpuTc3Vr
Generated by Claude Code
Summary by cubic
Fixes CI job failures, restores the production build, and aligns tests and tooling with recent refactors. Also applies review feedback to OAuth error handling, header/layout behavior, and sidebar visuals to stabilize gates and UX.
Bug Fixes
resolveOAuthErrorfor clear PT-BR messages; no retry for disabled providers.ReferenceErrorviaisMenuOpen; add semantic/dynamic aria labels; safe preloads with.catch; functionalsetSidebarOpen; remove unused search props/state.bg-primary/10; remove glow borders on badges; hide badge when count is undefined.??).logPerformance, switchany→unknown, and exportusePrefetchProductto fix build; update Cloud Status coverage path; ESLint baseline generator now freezes errors and warnings (baseline regenerated).Tests
/auth; dev infra overlays gate strictly byisDev; removed obsolete BridgeStatusBanner test.vi.mockcalls; mocked@/hooks/ui/useNotifications; fixed TZ and Supabase.then()mocks; AuthContext uses realauthService.signOut.SpaceScene, updated GX HSL expectations, and parsed structured callback errors; stabilized quote-calculation assertions.Written for commit e880712. Summary will update on new commits. Review in cubic
Summary by CodeRabbit
Style
Bug Fixes
New Features
Tests / Chores