fix(ci): destrava gates de lint/testes após refactor de pastas de hooks#23
fix(ci): destrava gates de lint/testes após refactor de pastas de hooks#23adm01-debug wants to merge 65 commits into
Conversation
- seller-scope: anota rls-allow nas queries de quoteService (filtro por id + RLS) - README: troca 'db push' por 'migration up' (gate check-no-db-push) - hooks: corrige ~150 imports quebrados após mover hooks para subpastas - CloudStatusBanner: corrige paths de mock + gating por estado (down/degraded visível a todos; warming dev-only) - SkeletonMonitor: lê AuthContext defensivamente (não derruba árvore sem provider) - skeleton-snapshots: normaliza altura aleatória do ChartSkeleton + regenera - quoteService: tipa logHistory/personalizations (remove any) https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
O gate (check-eslint-baseline) compara erros E warnings contra o baseline, mas o gerador só congelava erros — então qualquer warning legado virava "regressão" e o gate nunca passava (523 warnings preexistentes). Gerador agora congela ambas severidades. Baseline regenerado: 437 erros + 523 warnings. Inclui limpeza dos imports/vars órfãos em AuthContext e merge de imports duplicados nos testes de conexões. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAtualiza gates/ESLint e coverage, regrava .tsc-baseline.json, refatora AuthContext (prewarm, log de login, signOut), ajusta BridgeStatusBanner para renderizar sempre com conteúdo controlado por isAllowed, adiciona logHistory em quoteService e migra muitos imports/mocks de hooks e rotas de testes. ChangesGates de qualidade + refactors e migração de testes
Estimated code review effort Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
…a snapshots - check-cloud-status-coverage + package.json apontavam para src/hooks/useDevGate.ts (path antigo); o hook foi movido p/ src/hooks/admin/useDevGate.ts no refactor - skeleton snapshots regenerados: o prettier-tailwind reordenou a className do wrapper em SkeletonMonitor após a geração anterior, deixando o .snap defasado https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
Traz os 37 commits da main (que já corrigiram imports de hooks movidos, README db-push e jobs de CI). Conflitos resolvidos preferindo a versão da main em CloudStatusBanner (+ testes/snapshot) e README — convergência com meus fixes. Mantém net-new: gerador do baseline ESLint congelando warnings e correção do path useDevGate no gate de cloud-status. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
Pull request overview
Esta PR destrava os gates de CI (lint baseline, coverage específica e suíte de testes) após o refactor que moveu hooks para subpastas (@/hooks/*/*), alinhando paths de imports/mocks e atualizando o baseline do ESLint para refletir a política real do checker.
Changes:
- Atualiza o gerador do baseline do ESLint para congelar warnings e erros e regenera
.eslint-baseline.json. - Ajusta paths de imports e
vi.mockem uma grande quantidade de testes para refletir a nova estrutura de hooks. - Atualiza gates/documentação auxiliares (coverage do CloudStatus/useDevGate, README e scripts) e pequenos ajustes em componentes/serviços (ex.:
CloudStatusBanner,AuthContext,quoteService).
Reviewed changes
Copilot reviewed 136 out of 137 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/unit/system/BridgeStatusBanner.test.tsx | Atualiza paths de hooks mockados |
| tests/unit/system/BridgeMetricsPerformance.test.tsx | Ajusta import do useDevGate |
| tests/unit/system/BridgeMetricsOverlay.test.tsx | Ajusta import/mock do useDevGate |
| tests/ssr/useDevGate.ssr.test.tsx | Atualiza path do useDevGate |
| tests/pages/kit-builder/useKitBuilderQuote.test.ts | Atualiza tipo KitState path |
| tests/pages/AdminVideoVariantsPage.test.tsx | Atualiza mock useVideoVariantLinks |
| tests/pages/AdminLoginAttemptsPage.test.tsx | Atualiza mock useLoginAttempts |
| tests/lib/theme-presets.test.ts | Atualiza valores GX e comentário |
| tests/lib/colorSystem-utils.test.ts | Atualiza import useColorSystem |
| tests/integration/tecnicas-pricing-flow.test.tsx | Atualiza path useCustomizationPrice |
| tests/integration/simulator-wizard-pricing-parity.test.ts | Atualiza mocks/imports useGravacaoPriceV2 |
| tests/hooks/useWorkspaceNotifications.test.ts | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-unread-count.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-prefetch.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-fetch-error.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-cache-persistence.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-cache-invalidation.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-cache-freshness.test.tsx | Atualiza path do hook |
| tests/hooks/useWorkspaceNotifications-badge-render-log.test.tsx | Atualiza path do hook |
| tests/hooks/useVoiceAgent.test.ts | Atualiza path do hook |
| tests/hooks/useVideoVariantLinks.test.ts | Atualiza path do hook |
| tests/hooks/useUrlState.test.tsx | Atualiza path do hook |
| tests/hooks/useTechniquePricing.test.ts | Atualiza tipos (simulation) |
| tests/hooks/useSupplierComparison.test.ts | Atualiza paths + expectativa retorno |
| tests/hooks/useSpeechRecognition.test.ts | Atualiza path do hook |
| tests/hooks/useSellerCarts.test.tsx | Atualiza path do hook |
| tests/hooks/useSearch.test.ts | Atualiza path do useSearch |
| tests/hooks/useScroll.test.ts | Atualiza path do hook |
| tests/hooks/useSalesGoals.test.tsx | Atualiza path do hook |
| tests/hooks/useReplenishmentsSelectionMode.test.ts | Atualiza paths (products) |
| tests/hooks/useRBAC.test.tsx | Atualiza path (auth) |
| tests/hooks/useQuoteHistory.test.ts | Atualiza path (quotes) |
| tests/hooks/useProducts.test.ts | Atualiza path useProducts |
| tests/hooks/useProductMatch-gaps.test.ts | Atualiza paths + expectativa retorno |
| tests/hooks/useProductCustomizationOptions.smoke.test.ts | Atualiza path do hook |
| tests/hooks/useProductAnalytics.test.tsx | Atualiza path do hook |
| tests/hooks/usePrintAreas.smoke.test.ts | Atualiza path (simulation) |
| tests/hooks/usePasswordBreachCheck.test.tsx | Atualiza path (auth) |
| tests/hooks/useOnboarding.test.tsx | Atualiza path (ui) |
| tests/hooks/useMockupTechniques.test.ts | Atualiza path (mockup) |
| tests/hooks/useMockupGenerator.test.tsx | Atualiza mocks/import do hook |
| tests/hooks/useMagicUpGeneration-onda5.test.tsx | Atualiza path (intelligence) |
| tests/hooks/useLoginRateLimit.test.ts | Move import para lib rate-limit |
| tests/hooks/useLoginAttempts.test.ts | Atualiza path (auth) |
| tests/hooks/useKitBuilder-extended.test.ts | Atualiza paths (kit-builder) |
| tests/hooks/useIPValidation.test.ts | Atualiza path (admin) |
| tests/hooks/useGravacaoPriceV2.test.ts | Atualiza path (simulation) |
| tests/hooks/useGlobalSearch-voice.test.ts | Atualiza tipo (intelligence) |
| tests/hooks/useFavorites.test.ts | Atualiza path (favorites) |
| tests/hooks/useExpertConversations.test.tsx | Atualiza path (intelligence) |
| tests/hooks/useErrorHandler.test.ts | Atualiza path (ui) |
| tests/hooks/useDevGate.test.ts | Atualiza path (admin) |
| tests/hooks/useDebouncedFilters.test.ts | Atualiza path (common) |
| tests/hooks/useDebounce.test.ts | Atualiza path (common) |
| tests/hooks/useDebounce-extended.test.ts | Atualiza path (common) |
| tests/hooks/useCustomizationPriceReactive.functional.test.ts | Atualiza path (simulation) |
| tests/hooks/useCustomizationPrice.functional.test.ts | Atualiza path (simulation) |
| tests/hooks/useCurrentOrgId.test.ts | Atualiza path (common) |
| tests/hooks/useContextualSuggestions.test.tsx | Atualiza path (intelligence) |
| tests/hooks/useConnectionTester.test.tsx | Atualiza path (intelligence) |
| tests/hooks/useComparisonWeights.test.ts | Atualiza path (comparison) |
| tests/hooks/useComparisonScore.test.ts | Atualiza path (comparison) |
| tests/hooks/useComparison.test.tsx | Atualiza path (comparison) |
| tests/hooks/useCollections.test.tsx | Atualiza path (collections) |
| tests/hooks/useCollections.test.ts | Atualiza path (collections) |
| tests/hooks/useCategories.test.tsx | Atualiza path (products) |
| tests/hooks/useBulkSelection.test.ts | Atualiza path (common) |
| tests/hooks/useBulkSelection-extended.test.ts | Atualiza path (common) |
| tests/hooks/useBridgeStatusBanner.test.ts | Atualiza path (intelligence) |
| tests/hooks/useAllowedIPs.test.ts | Atualiza path (admin) |
| tests/hooks/useAIRecommendations.test.ts | Atualiza path (intelligence) |
| tests/hooks/useAccessSecurity.test.ts | Atualiza path (auth) |
| tests/hooks/use2FA.test.ts | Atualiza path (auth) |
| tests/hooks/simulation/simulationPriceFetcher.test.ts | Atualiza mocks de paths |
| tests/hooks/catalog-comparison-smoke.test.ts | Atualiza path (comparison) |
| tests/e2e/infra-banners-prod.test.tsx | Ajusta mock useCloudStatus path |
| tests/e2e/favorites-ui.test.tsx | Ajusta mock useOnboarding path |
| tests/e2e/auth-flow.test.tsx | Ajusta mock useIPValidation path |
| tests/components/simulator/TechniqueCard.test.tsx | Ajusta mock useSimulation path |
| tests/components/security/SecurityDashboard.test.tsx | Ajusta mocks (auth/admin) |
| tests/components/search/GlobalSearchPalette.test.tsx | Ajusta mocks (common/intelligence) |
| tests/components/quotes/AIRecommendationsPanel.test.tsx | Ajusta imports/mocks hook |
| tests/components/ProtectedRoute.test.tsx | Atualiza rota de auth (/auth) |
| tests/components/products/ProductSparkline.labels.test.tsx | Atualiza path hook sparkline |
| tests/components/pricing/QuantityPriceCalculator.test.tsx | Ajusta mocks (simulation) |
| tests/components/pages/MagicUp.test.tsx | Ajusta mocks (simulation/mockup) |
| tests/components/pages/Index.test.tsx | Ajusta mocks de hooks paths |
| tests/components/pages/FiltersPage.test.tsx | Ajusta mock useVoiceAgent path |
| tests/components/pages/Auth.test.tsx | Atualiza path página Auth |
| tests/components/pages/AdvancedPriceSearchPage.test.tsx | Ajusta mock useTecnicasUnificadas |
| tests/components/NotificationDrawer-unmount-cleanup.test.tsx | Ajusta mock useNotifications |
| tests/components/NotificationDrawer-trigger-to-fetch-timing.test.tsx | Ajusta mock useNotifications |
| tests/components/NotificationDrawer-trigger-fetch-counters.test.tsx | Ajusta mock useNotifications |
| tests/components/NotificationDrawer-debounce.test.tsx | Ajusta mock useNotifications |
| tests/components/NotificationDrawer-debounce-config.test.tsx | Ajusta mock useNotifications |
| tests/components/NotificationDrawer-a11y.test.tsx | Ajusta mock useNotifications |
| tests/components/magic-up-onda5.test.tsx | Ajusta tipo VariationItem |
| tests/components/layout/MainLayout.breadcrumbs.test.tsx | Ajusta mocks hooks UI |
| tests/components/kit-builder/KitBuilderComponents.test.tsx | Ajusta mock hook kit-builder |
| tests/components/filters/FilterPanel.test.tsx | Ajusta mocks hooks (products/crm) |
| tests/components/expert/ExpertChatDialog.test.tsx | Ajusta mock (intelligence) |
| tests/components/DevRoute.test.tsx | Atualiza rota de auth (/auth) |
| tests/components/DevOnlyBridgeOverlay.test.tsx | Ajusta path useDevGate |
| tests/components/DevInfraGateStability.test.tsx | Ajusta path useDevGate |
| tests/components/DevInfraGateSSR.test.tsx | Ajusta path useDevGate |
| tests/components/DevInfraGateHydration.test.tsx | Ajusta path useDevGate |
| tests/components/DevInfraGateErrorResilience.test.tsx | Ajusta path useDevGate |
| tests/components/DevInfraGateMatrix.test.tsx | Ajusta expectations (strict dev) |
| tests/components/CloudStatusBanner.test.tsx | Ajusta mocks (ui/admin) |
| tests/components/BridgeStatusBanner.test.tsx | Ajusta mock useDevGate path |
| tests/components/BridgeMetricsOverlay-ProdGate.test.tsx | Ajusta mock useDevGate path |
| tests/components/AdminRoute.test.tsx | Atualiza rota de auth (/auth) |
| tests/components/AdminConexoesAccess.test.tsx | Atualiza rota de auth (/auth) |
| tests/components/admin/SecretField.test.tsx | Ajusta mocks (admin/intelligence) |
| tests/components/admin/SecretField.a11y.test.tsx | Ajusta mocks (admin/intelligence) |
| tests/components/admin/pluralization.test.tsx | Ajusta mocks (admin/intelligence) |
| tests/admin/skeleton-snapshots.test.tsx | Normaliza altura randômica em snapshot |
| tests/a11y/onda5-a11y.test.tsx | Ajusta tipo VariationItem |
| tests/_helpers/connection-fixtures.ts | Ajusta tipo importado |
| src/tests/AdminStandardRules.test.tsx | Ajusta busca do container max-w |
| src/services/quoteService.ts | Tipos + anotações rls-allow |
| src/pages/Auth.test.tsx | Mocka hooks admin adicionais |
| src/hooks/tests/useQuoteBuilderState.unit.test.tsx | Consolida vi.mock e ajusta mensagens |
| src/hooks/tests/useQuoteBuilderState.shipping.test.tsx | Consolida vi.mock e adiciona exports |
| src/hooks/tests/useCatalogState.unit.test.tsx | Mock com importOriginal para preservar hook real |
| src/contexts/AuthContext.tsx | Ajustes de typing/flow + signOut resiliente |
| src/contexts/AuthContext.test.tsx | Preserva signOut real no mock de service |
| src/components/system/CloudStatusBanner.tsx | Gating por status + warming dev-only |
| src/components/loading/SkeletonMonitor.tsx | Leitura defensiva do AuthContext |
| src/components/admin/connections/tests/ConnectionUI.test.tsx | Consolida mocks de @/hooks/intelligence |
| src/components/admin/connections/tests/ConnectionsOverviewTable.test.tsx | Consolida mocks e reorganiza dependências |
| scripts/eslint-baseline-generate.mjs | Congela warnings+erros no baseline |
| scripts/check-cloud-status-coverage.mjs | Atualiza path alvo do useDevGate |
| README.md | Troca db push por migration up |
| package.json | Atualiza include de coverage do hook |
| .eslint-baseline.json | Baseline regenerado (erros+warnings) |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const userRole = auth?.userRole; | ||
| const isDev = userRole === 'admin' || userRole === 'dev'; |
| import { renderHook, act } from '@testing-library/react'; | ||
| import { useSearch } from '@/hooks/useSearch'; | ||
| import { useSearch } from '@/hooks/common/useSearch'; | ||
| import type { Product } from '@/hooks/productss'; | ||
|
|
…nitor/typo - .eslint-baseline.json regenerado contra a árvore mergeada (460 erros + 525 warnings, cobrindo a dívida trazida pela main) - SkeletonMonitor: usa isDev/isAdmin do AuthContext (userRole não existe em AuthContextType — quebrava typecheck e o timer dev nunca aparecia) [Copilot] - useSearch.test: corrige import type de @/hooks/productss → @/hooks/products [Copilot] - skeleton snapshots realinhados com a fonte mergeada https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
No issues found across 137 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.
Re-trigger cubic
There was a problem hiding this comment.
1 issue found across 3 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 060ff19c17
ℹ️ 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".
| } catch { | ||
| // intencional: estado local é limpo no finally independente do remoto |
There was a problem hiding this comment.
Preserve signOut failure signal after local cleanup
Swallowing every exception from authService.signOut() makes signOut() always resolve, so callers that intentionally branch on failure can no longer detect remote logout problems (for example, Header's catch path that shows a server-sync warning). In offline/5xx cases this now shows a success flow even though global revocation failed, which is a behavior regression introduced by this catch-and-ignore block.
Useful? React with 👍 / 👎.
| const { userRole } = useAuth(); | ||
| const isDev = userRole === 'admin' || userRole === 'dev'; | ||
| const { isDev, isAdmin } = useAuth(); | ||
| const showDevTimer = isDev || isAdmin; |
There was a problem hiding this comment.
Keep SkeletonMonitor overlay restricted to dev/admin only
showDevTimer now uses isDev || isAdmin, but in this codebase isAdmin is derived from isSupervisorOrAbove and includes roles like supervisor and manager. That broadens a "Dev-only overlay timer" to non-dev roles, exposing internal diagnostic UI in production to users who previously would not see it.
Useful? React with 👍 / 👎.
| const rule = m.ruleId ?? "<no-rule>"; | ||
| counts[rel] ??= {}; | ||
| counts[rel][rule] = (counts[rel][rule] ?? 0) + 1; |
There was a problem hiding this comment.
Track ESLint severity in baseline keys
The generator now freezes warnings and errors together, but it still aggregates only by file + rule. That means a warning can turn into an error (same rule/count in the same file) without being flagged as regression, because the gate sees unchanged counts. This weakens the CI signal after this commit’s warning-baseline change and can let stricter lint violations slip through.
Useful? React with 👍 / 👎.
…typecheck
- remove QuoteBuilderDiscount.test.ts duplicado (continha JSX em .ts → TS1005/1109);
mantém o .test.tsx válido (resolve regressão de typecheck do merge)
- SkeletonMonitor: useContext(AuthContext) defensivo (não crasha fora do provider)
+ overlay restrito a isDev real (não isAdmin/supervisor) [cubic P1, Codex P2]
- AuthContext.signOut: volta a propagar erro remoto (Header avisa falha de
revogação); estado local segue limpo no finally [Codex P2]
- AuthContext.test: espera rejeição em falha remota + isola mock no 2º teste
- baseline ESLint: rastreia severidade {e,w} por file:rule — flagra
warning→error de mesma contagem [Codex P2]; baseline regenerado
- skeleton-snapshots mock: exporta AuthContext (createContext) p/ useContext
https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
… ref-warning A leitura via useContext(AuthContext) quebrava ~dezenas de testes que mockam apenas useAuth (não AuthContext). SkeletonMonitor sempre renderiza dentro do AuthProvider em produção (App.tsx: AppRoutes aninhado em <AuthProvider>), então useAuth() é seguro — o P1 do cubic é falso-positivo aqui. Mantém o overlay restrito a isDev real (fix do Codex). Mock do snapshot volta a só useAuth. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
1 issue found across 8 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Fix all with cubic | Re-trigger cubic
Soma o valor de melhoria já computado per-severidade (improved) em vez de recompor por totais baseline-current, que podia cancelar/inverter ganhos quando erros e warnings variam em direções opostas no mesmo file:rule. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
O baseline anterior (da main, pré-refactor de pastas) tinha paths defasados; o merge + o refactor que moveu hooks para subpastas deslocaram os erros, gerando 242 "regressões" falsas no gate de typecheck. Baseline regenerado: 1394 erros congelados em 332 arquivos (dívida de TS conhecida, igual à política do eslint). https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tests/unit/system/BridgeStatusBanner.test.tsx (1)
58-71:⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy liftComponente não implementou lógica condicional para mensagens diferentes por papel.
Teste falha na linha 69 porque espera "Catálogo temporariamente indisponível" quando
isAllowed=false, mas o componente renderiza "Catálogo externo indisponível" em ambos os casos (sem variação).O componente obtém
isAllowedna linha 16 e passa para o hook (linha 17), porém não usa esse valor para condicionar a mensagem exibida (linha 32 é fixa). Falta uma renderização condicional:
- Quando
isAllowed=false→ "Catálogo temporariamente indisponível"- Quando
isAllowed=true→ "Catálogo externo indisponível"🤖 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/BridgeStatusBanner.test.tsx` around lines 58 - 71, BridgeStatusBanner currently ignores the isAllowed value from useDevGate and always renders the same message; update the component (BridgeStatusBanner) to read isAllowed (from useDevGate) and pass it or use it to conditionally render the banner message: if isAllowed === false show "Catálogo temporariamente indisponível", otherwise show "Catálogo externo indisponível" (keep the existing unavailable/reason/closeUnavailable/reload behavior from useBridgeStatusBanner intact); locate the render logic in BridgeStatusBanner where the fixed message is returned and replace it with a conditional branch based on the isAllowed value.tests/unit/system/BridgeMetricsOverlay.test.tsx (1)
115-136:⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy liftAtualizar mocks dos testes —
useDevGateretorna estrutura errada.O componente desestrutura
const { isDev } = useDevGate()(linha 27), mas os testes mockam{ isAllowed: true }. Isso deixaisDevcomoundefined, causandouseBridgeMetrics(undefined)e impedindo a renderização correta do Header com os botões 'live', 'paused', 'clear' e '✕'.Alterar todos os mocks de
useDevGatede:(useDevGate as any).mockReturnValue({ isAllowed: true });para:
(useDevGate as any).mockReturnValue({ isDev: true });Essa mudança garante que
isDevseja passado corretamente parauseBridgeMetricse os testes das linhas 115–136 funcionem como esperado.🤖 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 115 - 136, The tests mock useDevGate with the wrong shape causing isDev to be undefined; update all mocks of useDevGate in the test file to return the correct property name (isDev: true) instead of isAllowed so the component's const { isDev } = useDevGate() passes a boolean into useBridgeMetrics and the Header renders the 'live', 'paused', 'clear' and '✕' buttons; search for (useDevGate as any).mockReturnValue(...) and replace the returned object to include isDev: true so useBridgeMetrics and the overlay tests (lines testing live/paused/clear/✕) run correctly.src/services/quoteService.ts (1)
186-207:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
logHistorysilencia erros e perde valores válidos (0,false,'').A função não valida retorno do
insert(linhas 203-206), deixando falhas de escrita invisíveis. Além disso, o||converte falsys legítimos em padrão:
oldValue || null→ perde0,false,''newValue || null→ perde0,false,''fieldChanged || null→ perde0,false,''Em auditoria/histórico, perda silenciosa de dados é regressão crítica. Use
??e lance erros de insert, alinhado ao padrão do arquivo: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 || {}, + 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 - 207, In logHistory, stop swallowing DB errors and preserve falsy-but-valid values: change uses of || for field_changed, old_value, new_value to the nullish coalescing operator (??) so 0/false/'' are kept, and capture/validate the result of supabase.from('quote_history').insert(...) — if the insert returns an error or indicates failure, throw or propagate that error (matching the file's existing error-handling pattern) instead of ignoring it; ensure you reference supabase.from('quote_history').insert and the logHistory function when making the fix.
🧹 Nitpick comments (3)
src/hooks/__tests__/useCatalogState.unit.test.tsx (1)
14-49: 💤 Low valueMock duplicado de
useCatalogFilteringpode ser simplificado.O mesmo hook está mockado duas vezes: dentro do mock de
@/hooks/products(linha 42) e como mock separado para@/hooks/products/useCatalogFiltering(linhas 47-49).Se o código importa sempre pelo path específico, o mock na linha 42 pode ser desnecessário. Se importa por ambos os caminhos, está correto, mas seria bom um comentário explicando por quê.
💡 Sugestão para clarificar
Adicionar comentário explicando a necessidade dos dois mocks:
}; }); +// useCatalogState também importa useCatalogFiltering pelo path direto, então mockamos +// novamente para garantir cobertura em ambas as formas de import. vi.mock('`@/hooks/products/useCatalogFiltering`', () => ({🤖 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/hooks/__tests__/useCatalogState.unit.test.tsx` around lines 14 - 49, There are two mocks for the same hook (useCatalogFiltering) defined inside the mock of the module that exports many hooks (the vi.mock block returning useCatalogFiltering) and separately in the vi.mock for '`@/hooks/products/useCatalogFiltering`'; either remove the redundant useCatalogFiltering entry from the larger '`@/hooks/products`' mock if your code always imports the hook by its direct path, or keep both but add a brief comment above the two mocks explaining that both import paths are used and therefore both mocks are required; locate the duplicated symbol useCatalogFiltering in the vi.mock(...) returning many hooks and the separate vi.mock('`@/hooks/products/useCatalogFiltering`', ...) and edit accordingly.tests/components/DevRoute.test.tsx (1)
8-8: ⚡ Quick winComentário desatualizado após mudança de rota.
O comentário ainda menciona redirecionamento para
/login, mas a rota foi alterada para/auth(linha 71). Atualizar para manter consistência.📝 Correção sugerida
- * - anon: é redirecionado para /login. + * - anon: é redirecionado para /auth.🤖 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/components/DevRoute.test.tsx` at line 8, Update the outdated test comment that references the old route "/login" to the new "/auth": locate the string "/login" in tests/components/DevRoute.test.tsx (the test description/comment near the DevRoute tests and any assertions referencing that path) and replace it with "/auth" so the comment and expectations match the changed route.src/components/admin/connections/__tests__/ConnectionUI.test.tsx (1)
13-29: 💤 Low valueConsidere extrair mock duplicado para helper compartilhado.
Este bloco de mock de
@/hooks/intelligenceestá duplicado entreConnectionUI.test.tsxeConnectionsOverviewTable.test.tsx. Extrair para um helper emtests/_helpers/reduziria duplicação e facilitaria manutenção.♻️ Sugestão: criar helper compartilhado
Criar arquivo
tests/_helpers/intelligence-mocks.ts:import { vi } from 'vitest'; export const mockIntelligenceHooks = () => ({ useConnectionsOverview: vi.fn(), useConnectionTester: vi.fn(), useConnectionsOverviewFilters: vi.fn(() => ({ filters: { types: [], status: [], window: 'all', onlyConsecutiveFailures: false }, activeCount: 0, reset: vi.fn(), toggleType: vi.fn(), setStatus: vi.fn(), setWindow: vi.fn(), removeType: vi.fn(), setOnlyConsecutiveFailures: vi.fn(), })), applyFilters: vi.fn((rows) => rows), });E usar nos testes:
+import { mockIntelligenceHooks } from 'tests/_helpers/intelligence-mocks'; + -vi.mock('`@/hooks/intelligence`', () => ({ - useConnectionsOverview: vi.fn(), - // ... resto do mock -})); +vi.mock('`@/hooks/intelligence`', mockIntelligenceHooks);🤖 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/admin/connections/__tests__/ConnectionUI.test.tsx` around lines 13 - 29, Extract the duplicated mock for '`@/hooks/intelligence`' into a shared helper (e.g., export a mockIntelligenceHooks function from tests/_helpers/intelligence-mocks.ts) that returns the same fakes (useConnectionsOverview, useConnectionTester, useConnectionsOverviewFilters, applyFilters), then replace the inline vi.mock(...) blocks in ConnectionUI.test.tsx and ConnectionsOverviewTable.test.tsx with a single import of that helper and call it to supply the mock implementation to vi.mock; ensure the helper exports are used to create the same shape and that the test files call vi.mock('`@/hooks/intelligence`', () => mockIntelligenceHooks()) so tests keep identical behavior.
🤖 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/admin/connections/__tests__/ConnectionUI.test.tsx`:
- Line 28: The mock for applyFilters in ConnectionUI.test.tsx doesn't match the
real signature from useConnectionsOverviewFilters.ts (rows, filters,
consecutiveFailuresMap, now); update the vi.fn mock to accept all four
parameters (e.g., vi.fn((rows, filters, consecutiveFailuresMap, now) => rows))
so it remains a pass-through but matches the real API, or alternatively add an
explicit inline comment next to applyFilters explaining it's an intentional
pass-through for UI/render tests to avoid masking filtering bugs; ensure the
symbol referenced is applyFilters and mention useConnectionsOverviewFilters.ts
in the comment if you choose the comment route.
In `@src/contexts/AuthContext.tsx`:
- Around line 125-127: The dynamic import calls that invoke m.prewarmExternalDb
(the import('`@/lib/external-db-prewarm`').then(m => m.prewarmExternalDb({
oncePerSession: true })) usage) must handle promise rejections to avoid
unhandled promise rejections; update both occurrences to chain a .catch(err => {
/* log or noop */ }) (or use try/catch with async IIFE) and follow the same
pattern used at the other location around prewarmExternalDb to either log the
error via your logger or explicitly swallow it, ensuring the dynamic import
promise is always settled.
In `@src/services/quoteService.ts`:
- Line 56: Replace the untyped accumulator declaration with the proper
QuoteItemPersonalization type: locate the variable allPersonalizations in
quoteService.ts (currently declared as Array<{ quote_item_id: string; [key:
string]: unknown }>), import the QuoteItemPersonalization type and change the
declaration to use QuoteItemPersonalization[] so the accumulator is strongly
typed across the file.
- Around line 113-125: The select and delete calls around oldItems (the supabase
.from('quote_items').select(...) and subsequent .delete() calls on
'quote_item_personalizations' and 'quote_items') don't check for returned
errors, allowing silent failures; update the logic in the updateQuote flow to
inspect the response tuples (data, error) for the select and each delete,
handle/propagate errors the same way updErr is handled (e.g., throw or return a
failed result) so failures abort the update instead of continuing, and ensure
oldItems is validated before mapping (use the returned data only when no error),
referencing the variables oldItems, updErr, and the supabase calls to
'quote_item_personalizations' and 'quote_items'.
- Around line 37-45: The fetchQuote implementation currently uses
supabase.from('quotes').select('*').eq('id', quoteId).single() which causes an
error when no row is found; change the query to use .maybeSingle() so a missing
quote returns null instead of throwing, keep existing qErr check and the
subsequent if (!quoteData) return null behavior; update the call site references
if necessary but primarily replace .single() with .maybeSingle() in the
fetchQuote function that uses the supabase client.
---
Outside diff comments:
In `@src/services/quoteService.ts`:
- Around line 186-207: In logHistory, stop swallowing DB errors and preserve
falsy-but-valid values: change uses of || for field_changed, old_value,
new_value to the nullish coalescing operator (??) so 0/false/'' are kept, and
capture/validate the result of supabase.from('quote_history').insert(...) — if
the insert returns an error or indicates failure, throw or propagate that error
(matching the file's existing error-handling pattern) instead of ignoring it;
ensure you reference supabase.from('quote_history').insert and the logHistory
function when making the fix.
In `@tests/unit/system/BridgeMetricsOverlay.test.tsx`:
- Around line 115-136: The tests mock useDevGate with the wrong shape causing
isDev to be undefined; update all mocks of useDevGate in the test file to return
the correct property name (isDev: true) instead of isAllowed so the component's
const { isDev } = useDevGate() passes a boolean into useBridgeMetrics and the
Header renders the 'live', 'paused', 'clear' and '✕' buttons; search for
(useDevGate as any).mockReturnValue(...) and replace the returned object to
include isDev: true so useBridgeMetrics and the overlay tests (lines testing
live/paused/clear/✕) run correctly.
In `@tests/unit/system/BridgeStatusBanner.test.tsx`:
- Around line 58-71: BridgeStatusBanner currently ignores the isAllowed value
from useDevGate and always renders the same message; update the component
(BridgeStatusBanner) to read isAllowed (from useDevGate) and pass it or use it
to conditionally render the banner message: if isAllowed === false show
"Catálogo temporariamente indisponível", otherwise show "Catálogo externo
indisponível" (keep the existing unavailable/reason/closeUnavailable/reload
behavior from useBridgeStatusBanner intact); locate the render logic in
BridgeStatusBanner where the fixed message is returned and replace it with a
conditional branch based on the isAllowed value.
---
Nitpick comments:
In `@src/components/admin/connections/__tests__/ConnectionUI.test.tsx`:
- Around line 13-29: Extract the duplicated mock for '`@/hooks/intelligence`' into
a shared helper (e.g., export a mockIntelligenceHooks function from
tests/_helpers/intelligence-mocks.ts) that returns the same fakes
(useConnectionsOverview, useConnectionTester, useConnectionsOverviewFilters,
applyFilters), then replace the inline vi.mock(...) blocks in
ConnectionUI.test.tsx and ConnectionsOverviewTable.test.tsx with a single import
of that helper and call it to supply the mock implementation to vi.mock; ensure
the helper exports are used to create the same shape and that the test files
call vi.mock('`@/hooks/intelligence`', () => mockIntelligenceHooks()) so tests
keep identical behavior.
In `@src/hooks/__tests__/useCatalogState.unit.test.tsx`:
- Around line 14-49: There are two mocks for the same hook (useCatalogFiltering)
defined inside the mock of the module that exports many hooks (the vi.mock block
returning useCatalogFiltering) and separately in the vi.mock for
'`@/hooks/products/useCatalogFiltering`'; either remove the redundant
useCatalogFiltering entry from the larger '`@/hooks/products`' mock if your code
always imports the hook by its direct path, or keep both but add a brief comment
above the two mocks explaining that both import paths are used and therefore
both mocks are required; locate the duplicated symbol useCatalogFiltering in the
vi.mock(...) returning many hooks and the separate
vi.mock('`@/hooks/products/useCatalogFiltering`', ...) and edit accordingly.
In `@tests/components/DevRoute.test.tsx`:
- Line 8: Update the outdated test comment that references the old route
"/login" to the new "/auth": locate the string "/login" in
tests/components/DevRoute.test.tsx (the test description/comment near the
DevRoute tests and any assertions referencing that path) and replace it with
"/auth" so the comment and expectations match the changed route.
🪄 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: fd63c18e-ef9f-41ee-ae36-6504fe333bd6
📒 Files selected for processing (132)
.eslint-baseline.json.tsc-baseline.jsonpackage.jsonscripts/check-cloud-status-coverage.mjsscripts/check-eslint-baseline.mjsscripts/eslint-baseline-generate.mjssrc/components/admin/connections/__tests__/ConnectionUI.test.tsxsrc/components/admin/connections/__tests__/ConnectionsOverviewTable.test.tsxsrc/components/loading/SkeletonMonitor.tsxsrc/components/quotes/__tests__/QuoteBuilderDiscount.test.tssrc/contexts/AuthContext.test.tsxsrc/contexts/AuthContext.tsxsrc/hooks/__tests__/useCatalogState.unit.test.tsxsrc/hooks/__tests__/useQuoteBuilderState.shipping.test.tsxsrc/hooks/__tests__/useQuoteBuilderState.unit.test.tsxsrc/pages/Auth.test.tsxsrc/services/quoteService.tssrc/tests/AdminStandardRules.test.tsxtests/_helpers/connection-fixtures.tstests/a11y/onda5-a11y.test.tsxtests/admin/skeleton-snapshots.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/admin/SecretField.a11y.test.tsxtests/components/admin/SecretField.test.tsxtests/components/admin/pluralization.test.tsxtests/components/expert/ExpertChatDialog.test.tsxtests/components/filters/FilterPanel.test.tsxtests/components/kit-builder/KitBuilderComponents.test.tsxtests/components/layout/MainLayout.breadcrumbs.test.tsxtests/components/magic-up-onda5.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/pricing/QuantityPriceCalculator.test.tsxtests/components/products/ProductSparkline.labels.test.tsxtests/components/quotes/AIRecommendationsPanel.test.tsxtests/components/search/GlobalSearchPalette.test.tsxtests/components/security/SecurityDashboard.test.tsxtests/components/simulator/TechniqueCard.test.tsxtests/e2e/auth-flow.test.tsxtests/e2e/favorites-ui.test.tsxtests/e2e/infra-banners-prod.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/useTechniquePricing.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/simulator-wizard-pricing-parity.test.tstests/integration/tecnicas-pricing-flow.test.tsxtests/lib/colorSystem-utils.test.tstests/lib/theme-presets.test.tstests/pages/AdminLoginAttemptsPage.test.tsxtests/pages/AdminVideoVariantsPage.test.tsxtests/pages/kit-builder/useKitBuilderQuote.test.tstests/ssr/useDevGate.ssr.test.tsxtests/unit/system/BridgeMetricsOverlay.test.tsxtests/unit/system/BridgeMetricsPerformance.test.tsxtests/unit/system/BridgeStatusBanner.test.tsx
💤 Files with no reviewable changes (1)
- src/components/quotes/tests/QuoteBuilderDiscount.test.ts
| removeType: vi.fn(), | ||
| setOnlyConsecutiveFailures: vi.fn(), | ||
| })), | ||
| applyFilters: vi.fn((rows) => rows), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verificar se applyFilters é usado nos componentes testados e se há expectativas de filtragem
rg -nP --type=tsx -C3 'applyFilters' src/components/admin/connections/Repository: adm01-debug/we-dream-big
Length of output: 96
🏁 Script executed:
#!/bin/bash
# First, let's locate the test file and understand its structure
find src/components/admin/connections -type f -name "*.test.tsx" -o -name "*.test.ts" | head -20Repository: adm01-debug/we-dream-big
Length of output: 358
🏁 Script executed:
#!/bin/bash
# Search for applyFilters usage (corrected - use ts type instead of tsx)
rg -n 'applyFilters' src/components/admin/connections/ -A 2 -B 2Repository: adm01-debug/we-dream-big
Length of output: 2210
🏁 Script executed:
#!/bin/bash
# Let's read the ConnectionUI.test.tsx file to understand the mock context
wc -l src/components/admin/connections/__tests__/ConnectionUI.test.tsxRepository: adm01-debug/we-dream-big
Length of output: 137
🏁 Script executed:
#!/bin/bash
# Read the ConnectionUI.test.tsx file to understand the test context
cat -n src/components/admin/connections/__tests__/ConnectionUI.test.tsxRepository: adm01-debug/we-dream-big
Length of output: 3943
🏁 Script executed:
#!/bin/bash
# Find the applyFilters function definition
rg -n 'export.*applyFilters|function applyFilters|const applyFilters' --type ts -A 5Repository: adm01-debug/we-dream-big
Length of output: 2176
🏁 Script executed:
#!/bin/bash
# Read the actual applyFilters implementation
cat -n src/hooks/intelligence/useConnectionsOverviewFilters.ts | head -70Repository: adm01-debug/we-dream-big
Length of output: 2885
🏁 Script executed:
#!/bin/bash
# Check if there are any tests specifically for applyFilters filtering logic
rg -l 'applyFilters' src/ --type ts --type tsx | grep -i testRepository: adm01-debug/we-dream-big
Length of output: 96
🏁 Script executed:
#!/bin/bash
# Check if there are dedicated tests for the filtering logic (corrected command)
rg -l 'applyFilters' src/ --type ts | grep -i testRepository: adm01-debug/we-dream-big
Length of output: 268
🏁 Script executed:
#!/bin/bash
# Look for any test files that specifically test filtering behavior
find src -name "*.test.ts" -o -name "*.test.tsx" | xargs grep -l 'applyFilters|filter' 2>/dev/null | head -10Repository: adm01-debug/we-dream-big
Length of output: 50
🏁 Script executed:
#!/bin/bash
# Read the dedicated filtering test file
cat -n src/hooks/__tests__/useConnectionsOverviewFilters.test.tsRepository: adm01-debug/we-dream-big
Length of output: 3315
A mock de applyFilters não corresponde à assinatura real da função.
O mock vi.fn((rows) => rows) aceita apenas 1 parâmetro, enquanto a função real em useConnectionsOverviewFilters.ts recebe 4 parâmetros (rows, filters, consecutiveFailuresMap, now). Embora o mock funcione na prática (ignora parâmetros extras), isso cria inconsistência.
Contudo, a preocupação sobre "esconder bugs de filtragem" é mitigada: a lógica de filtragem é testada adequadamente em src/hooks/__tests__/useConnectionsOverviewFilters.test.ts, que cobre todos os cenários (filtro por tipo, status, janela temporal). Os testes de componente (ConnectionUI.test.tsx, ConnectionsOverviewTable.test.tsx) são voltados para UI/acessibilidade, não para filtragem.
Recomendação: Atualize o mock para aceitar todos os 4 parâmetros, ou adicione um comentário explícito explicando que é um pass-through intencional para testes de renderização.
🤖 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/admin/connections/__tests__/ConnectionUI.test.tsx` at line 28,
The mock for applyFilters in ConnectionUI.test.tsx doesn't match the real
signature from useConnectionsOverviewFilters.ts (rows, filters,
consecutiveFailuresMap, now); update the vi.fn mock to accept all four
parameters (e.g., vi.fn((rows, filters, consecutiveFailuresMap, now) => rows))
so it remains a pass-through but matches the real API, or alternatively add an
explicit inline comment next to applyFilters explaining it's an intentional
pass-through for UI/render tests to avoid masking filtering bugs; ensure the
symbol referenced is applyFilters and mention useConnectionsOverviewFilters.ts
in the comment if you choose the comment route.
- quoteService: tipa allPersonalizations (QuoteItemPersonalization[]), troca || por ?? em logHistory (preserva 0/false/''), valida erro do insert, .maybeSingle() em fetchQuote (não-encontrado → null), e checa erros nos deletes do updateQuote (evita estado inconsistente) - AuthContext: imports dinâmicos (prewarm/safeToast) agora tratam rejeição - check-eslint-baseline: métrica de drift positivo soma o improved por severidade (não recompõe por totais) — corrige miscompute apontado pelo cubic - DevRoute.test: comentário /login → /auth https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
…sOverlay
BridgeMetricsOverlay usa const { isDev } = useDevGate() + early-return em !isDev.
Os testes mockavam { isAllowed }, deixando isDev undefined → overlay nunca
renderizava (botões live/paused/clear/✕ ausentes). Alinhado ao refactor do gate.
https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
O click do botao Google no SETUP do teste 41 (so para o app gravar o verifier) falhava intermitentemente no actionability 'stable' check da pagina animada (o teste 40 com o mesmo botao passou na mesma run -> flaky). Como o click 'de verdade' ja e validado no teste 40, usamos force:true aqui para pular o heuristico de estabilidade. O botao e comprovadamente clicavel.
…uth) - smoke 93: click force no submit (animações JS framer-motion mantêm o botão "não-estável" para o actionability check; addStyleTag só pausa CSS). - smoke callback ?error=: Auth.tsx consome e remove o param `error` da URL; passa a asserir o hint renderizado (social-login-error-hint) em vez do param volátil. - protected-routes: guards redirecionam para /auth; asserção final aceita /(auth|login) em vez de exigir /login. - helpers/auth LOGIN_URL_RE: exclui /auth/callback (rota PKCE, não login) via negative lookahead, evitando misclassificação nos helpers de auth. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
- 40: click no botão Google com force:true (animações JS mantêm o botão "não-estável" para o actionability check → o click antes travava ~22s). - 41: o app não grava code_verifier em window.localStorage neste ambiente (storage próprio / URL placeholder), então ler o verifier "real" nunca resolvia. Volta a injetar o verifier na chave canônica sb-<ref>-auth-token-code-verifier antes do callback, alcançando o /token mockado de forma determinística. Smoke gate local: 13 passed / 0 failed (40,41,42,43,44,45,46). https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d4bdfc381
ℹ️ 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 log = createStructuredLogger({ req, fn: "simulation-orchestrator", requestId }); | ||
|
|
||
| // Ferramenta dev-only: exige role dev (SSOT _shared/authorize.ts). | ||
| const auth = await authorize(req, { requireRole: "dev" }); |
There was a problem hiding this comment.
Enforce dev role with a strict role check
authorize(req, { requireRole: "dev" }) is not sufficient as written: _shared/authorize.ts only ranks agente/supervisor/dev, so roles used elsewhere in this repo like manager/vendedor resolve to an undefined rank; in JavaScript, undefined < requiredRank is false, so those users are treated as authorized. That means non-dev authenticated users with unranked roles can still call this endpoint (the same pattern is also used in sync-external-db). Add a server-side role validation path here (e.g., enforce RPC has_role checking) so "dev-only" is actually enforced.
Useful? React with 👍 / 👎.
| const log = createStructuredLogger({ req, fn: "sync-external-db", requestId }); | ||
|
|
||
| // Sync dev-only: exige role dev (SSOT _shared/authorize.ts). | ||
| const auth = await authorize(req, { requireRole: "dev" }); |
There was a problem hiding this comment.
Enforce strict dev-only auth in sync-external-db
This endpoint uses the same authorize(req, { requireRole: "dev" }) path that currently trusts a rank map containing only agente/supervisor/dev; roles like manager or vendedor become an undefined rank, and undefined < requiredRank evaluates false, so those users are incorrectly allowed through. Because this function performs cross-database sync operations, relying on the rank shortcut here creates a real authorization bypass unless server-side has_role verification is enforced.
Useful? React with 👍 / 👎.
…ualiza baseline CatalogContent acumulou 16 símbolos não usados após o refactor de hooks/views (useRef/useCallback/useEffect/useState/useMemo, useVirtualizer, ícones lucide, useProductsContextSafe, Button, SelectionCheckbox e 4 props na desestruturação). Remove o código morto e regenera o .eslint-baseline.json (458→442 erros), que deixa de congelar essas 16 entradas — futuras regressões nesse arquivo voltam a ser detectadas. Diff do baseline: só 2 reduções (CatalogContent, e a entrada stale de AuthBranding.visual.test.tsx), nenhuma entrada nova/deslocada. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
…edValue) Adiciona prop opcional `isTransitioning` (default false). Durante transições de view/filtro a toolbar fica `aria-busy` e esmaece levemente; `useDeferredValue` evita flicker (o efeito só "pega" quando o React conclui o trabalho pesado, em vez de piscar a cada render intermediário). Prop opcional → caller atual (Index) não quebra; basta passar `isTransitioning` para ativar. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
…sort/filtros) useCatalogState agora envolve setViewMode/setGridColumns/setSortBy/setFilters em startTransition e expõe isTransitioning (isPending). Index passa isTransitioning ao CatalogToolbar, que esmaece + aria-busy durante o re-render pesado de milhares de produtos — mantendo a UI responsiva (escritas em localStorage seguem síncronas; deps de resetFilters ajustadas para os setters agora memoizados). https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
O guard de scripts/fuzz-testing.mjs fazia exit(0) silencioso quando faltavam SUPABASE_URL/SERVICE_ROLE_KEY — no job integration-tests (sem essas env vars) o "Run Fuzz Testing (Massive)" passava sem executar nenhum payload, escondendo crashers de edges. Agora: - injeta SUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY (de secrets) no job de fuzz; - o script aborta (exit 1) quando ausentes E process.env.CI está setado; segue pulando só localmente (sem CI), para não exigir credenciais no dev. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
…-op (DEFINITIVO) Supersede o fix por injecao de chave (do agente paralelo, 5d4bdfc) que FALHA: run 26183406138 deu 12 passed / 1 failed no teste 41, com 'code verifier should be non-empty' — o gotrue le vazio pois a chave adivinhada nao e a chave/storage real do supabase-js. Evidencia (trace run 61cbd02): o signInWithOAuth real GERA e grava o verifier (code-verifier aparece 22x, subtle 25x, 'redirect dispatched'), mas o redirect top-level (window.location.assign) + route.abort destruiam o contexto de execucao, deixando o localStorage ilegivel para o page.evaluate (poll falhava em 8s com Received:false). Fix: deixar o app gravar o verifier (chave/storage REAIS) e impedir a navegacao via override de window.location.assign (no-op) em addInitScript. Contexto fica intacto -> verifier legivel e preservado na mesma origem ate /auth/callback -> exchangeCodeForSession acha o verifier -> POST /token mockado -> sessao. O click e force:true (setup; o click real ja e validado no teste 40).
…ions-failures-FVfYB # Conflicts: # src/components/catalog/CatalogContent.tsx # src/components/catalog/CatalogToolbar.tsx # src/contexts/AuthContext.tsx # src/hooks/products/useCatalogState.ts # src/pages/Index.tsx
…es-FVfYB' into claude/fix-github-actions-failures-FVfYB
…a main O eslint --fix do pre-commit (regra tailwind classnames-order) reordenou as classes de gap no fonte durante o merge, deixando os 3 snapshots de CatalogSkeleton defasados — quebrando o job Ref-warning e o test:quality (dentro do Lint). Regenerados contra o fonte já em ordem canônica. https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
…ityError) O merge trouxe a versão "DEFINITIVO" (override de window.location.assign + leitura do verifier real do localStorage), que falha com "SecurityError: Access is denied for this document" — signInWithOAuth usa window.location.href (não .assign), então o redirect top-level torna o documento opaco e o localStorage fica ilegível. Volto à injeção do verifier na chave canônica sb-<ref>-auth-token-code-verifier (validada: smoke 13/13). https://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 463fc8287a
ℹ️ 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".
| if (cur.w > base.w) { | ||
| regressions.push({ file, rule, severity: "warning", baseline: base.w, current: cur.w, delta: cur.w - base.w }); |
There was a problem hiding this comment.
Treat error-to-warning shifts as non-regressions
This warning-only regression check can fail CI when a rule improves from error to warning in the same file/rule pair (e.g., baseline {e:1,w:0} to current {e:0,w:1}): cur.w > base.w is true, so the gate reports a regression even though severity decreased. That creates false negatives and blocks legitimate lint improvements after this commit’s split-by-severity model.
Useful? React with 👍 / 👎.
Resumo
Conserta as falhas do GitHub Actions causadas, em sua maioria, pelo refactor que moveu os hooks para subpastas (
@/hooks/quotes,@/hooks/products,@/hooks/intelligence, etc.).Causa raiz do gate de lint
O
lint:baselinenunca passava: o gerador do baseline só congelava erros (severity 2), mas o checker compara erros e warnings. Como os 523 warnings legados nunca entravam no baseline, cada um virava "regressão". Alinhei o gerador para congelar ambas as severidades e regenerei o baseline (437 erros + 523 warnings).Testes corrigidos
vi.mockduplicados para o mesmo path consolidados em chamada única (o hoisting fazia a última sobrescrever as anteriores) —useQuoteBuilderState.{shipping,unit},ConnectionsOverviewTable,ConnectionUI.useCatalogState—importOriginalpara preservar o hook sob teste enquanto mocka as deps.ProtectedRoute/AdminRoute/DevRoute/AdminConexoesAccessagora esperam redirect para/auth.AdminStandardRules— busca o containermax-wno output completo (layout migrou para o nível do router).AuthContext.signOut— não propaga erro remoto (logout local sempre ocorre); + limpeza de imports/vars órfãos.theme-presets— tabela de skins GX alinhada aos valores WCAG reais.DevInfraGateMatrix— expectativas seguemisDev(DevOnly strict).Gates estáticos
check-seller-scope: anotaçõesrls-allowemquoteService.check-no-db-push: README usamigration up.Test plan
npm run lint:baseline(verde localmente)npm run typechecknpm run test:qualityhttps://claude.ai/code/session_01SN7BG6cYaPS1t1fYLkga4Z
Generated by Claude Code
Summary by cubic
Unblocks CI (lint, typecheck, tests, coverage) and Edge gates after the hooks/pages refactor. Stabilizes login/OAuth smoke tests and smooths catalog transitions.
Bug Fixes
test:qualityruns in 4 shards; smoke uses--max-failures=50.dotenv, readSUPABASE_URL/VITE_SUPABASE_URL+SUPABASE_SERVICE_ROLE_KEY, and drop hardcoded keys. Fuzz gate fails in CI without creds (job injects secrets); still skips locally without creds.motion-safe;force: truewhere needed. Authorize is captured via bothpage.on('request')and a route abort. The callback smoke now injects the PKCEcode_verifierinto the canonical storage key before visiting/auth/callback, then asserts only the code→token exchange flag. Redirect checks accept/(auth|login)/; helpers exclude/auth/callback. Visual tests converted to DOM checks; restored a 7‑rocket burst in branding.simulation-orchestratorandsync-external-dbadopt shared CORS, dev‑onlyauthorize, and structured logging; both added to_shared/edge-authz-manifest.ts./simulacaomoved behind<DevRoute />.BridgeStatusBannershows critical outages to everyone (devs get technical copy).SkeletonMonitordev overlay gated by realisDev. Buttons usemotion-safe. Social login shows a PT‑BR message for disabled providers, andresolveOAuthErrortreats it as config.quoteServicevalidates ops and uses.maybeSingle(). Telemetry cards abort fetches on unmount. Header getssidebarOpen. Tests and baselines updated for moved hooks/pages.Refactors
useCatalogStatewraps heavy updates instartTransition, exposesisTransitioning, andIndexpasses it toCatalogToolbar(aria-busy + fade viauseDeferredValue) to reduce flicker during view/column/sort/filter changes.Written for commit 463fc82. Summary will update on new commits. Review in cubic
Summary by CodeRabbit
Novas Funcionalidades
Correções de Bugs
Melhorias de UI
Refatoração