Skip to content

fix: resolve TDZ crash in useAudioRecorder and schema violations in evolution contact queries - #593

Merged
adm01-debug merged 3 commits into
mainfrom
claude/zapp-db-organization-docs-txezga
Jul 27, 2026
Merged

fix: resolve TDZ crash in useAudioRecorder and schema violations in evolution contact queries#593
adm01-debug merged 3 commits into
mainfrom
claude/zapp-db-organization-docs-txezga

Conversation

@adm01-debug

@adm01-debug adm01-debug commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Descrição

Três correções de bugs identificados na auditoria exaustiva de código:

1. TDZ (Temporal Dead Zone) em useAudioRecorder.ts
O useEffect na linha 25 tinha [cleanupRecordingResources] no dep array, mas const cleanupRecordingResources = useCallback(...) só era declarado na linha 43 — DEPOIS do useEffect. Em JavaScript, dep arrays são avaliados no momento do render, antes de const ser inicializado → ReferenceError por TDZ em todo mount do componente. Fix: mover todos os useRef e cleanupRecordingResources para ANTES do useEffect.

2. Schema violation em useRealtimeMessages.ts
Queries de dados em evolution_contacts usavam .schema('evo'), violando a regra CLAUDE.md §2: o cliente canônico já tem db.schema='zapp' e evolution_contacts existe como view auto-updatable em zapp com security_invoker=on. Fix: remover .schema('evo') nas linhas 105 e 136; manter schema: 'evo' nas subscriptions Realtime (correto para CDC físico).

3. Schema violation em useZappContactSearch.ts
zappSupabase.schema('evo').from('evolution_contacts')zappSupabase é o mesmo cliente canônico com db.schema='zapp', então .schema('evo') sobrescrevia desnecessariamente o schema correto. Fix: remover .schema('evo').

Tipo de mudança

  • fix: Correção de bug

Checklist de qualidade

Para todo PR

  • Título segue Conventional Commits (tipo: descrição em minúsculas)
  • PR aborda um único tema
  • TypeScript sem novos erros (tsc --noEmit --skipLibCheck: 0 erros)

Para PRs com fix:

  • Bugs são structurais/de inicialização — TDZ é determinístico (falha em 100% dos mounts)
  • Schema violations causam PGRST205 em runtime sob certas condições de schema routing

Testes relacionados

Nenhum arquivo de teste novo — bugs são estruturais (TDZ de inicialização, routing de schema). A validação foi feita via:

  • tsc --noEmit --skipLibCheck → 0 erros
  • Inspeção de ordem de declarações (TDZ é determinístico)
  • Verificação de zappSupabase === supabase via supabaseClient.ts (mesma instância)

Notas para o revisor

  • useRealtimeMessages.ts é marcado @deprecated — as correções de schema são válidas mesmo assim, pois mantém consistência com o restante da codebase enquanto o hook não for removido.
  • As subscriptions Realtime em schema: 'evo' nas linhas ~208 e ~239 estão corretas e não foram alteradas — CDC físico requer o schema da tabela raiz particionada.

Generated by Claude Code


Summary by cubic

Fixes a crash in the audio recorder and aligns contact queries to the canonical zapp schema. Also repairs vercel.json, removes leaked envs, and tightens security headers.

  • Bug Fixes
    • Resolved TDZ in useAudioRecorder by moving refs and cleanupRecordingResources above the useEffect that uses them.
    • Removed .schema('evo') from evolution_contacts data queries in useRealtimeMessages and useZappContactSearch to use the zapp view; Realtime subscriptions on evo remain unchanged.
    • Cleaned up hook deps: removed redundant contactPhone in useChatMediaSending and added missing setBlobUrl in useAudioManagement.
    • Replaced base64-encoded vercel.json with valid JSON, removed committed env vars, and added stricter headers (HSTS, CSP, permissions) plus SPA rewrites.

Written for commit dad9852. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Correções

    • Melhorada a confiabilidade do envio de emojis personalizados e memes de áudio.
    • Corrigida a atualização de contatos e mensagens em tempo real.
    • Aperfeiçoada a busca de contatos por nome ou telefone.
  • Melhorias

    • O gravador de áudio agora libera recursos corretamente ao ser encerrado, reduzindo riscos de falhas e consumo desnecessário.
    • Atualizada a configuração de publicação do aplicativo, com carregamento de rotas mais consistente, cabeçalhos de segurança e cache otimizado.

claude added 3 commits July 27, 2026 19:43
…rets

vercel.json was stored as a single base64 blob, causing Vercel to reject
it with "Invalid vercel.json file provided". Decoded the content back to
valid JSON.

Also removed the hardcoded `env` block which contained the Supabase anon
key in plaintext — environment variables must be set via the Vercel
dashboard, not committed to the repository.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013jZX3jD8iLBNBqvgPVLBnE
useChatMediaSending: handleSendCustomEmoji and handleSendAudioMeme had
contactPhone in their dep arrays, but getSafePhone already captures it
via its own [contactPhone] dep. Redundant deps removed.

useAudioManagement: startRecording called setBlobUrl inside its body but
did not list it as a dep. setBlobUrl has [] deps (stable reference), so
adding it satisfies the exhaustive-deps rule without causing extra renders.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013jZX3jD8iLBNBqvgPVLBnE
…volution contact queries

- useAudioRecorder.ts: move all useRef declarations and cleanupRecordingResources
  useCallback above the useEffect that depends on it — previously the dep array
  [cleanupRecordingResources] was evaluated at render time before the const was
  initialized (TDZ), causing a ReferenceError on every mount
- useRealtimeMessages.ts: drop .schema('evo') on evolution_contacts data queries
  (lines 105/136); zapp view (security_invoker=on) is canonical per CLAUDE.md rule 2;
  remove stale ignore-audit comments
- useZappContactSearch.ts: same — zappSupabase already has db.schema='zapp',
  so .schema('evo') override was unnecessary and bypassed the zapp view

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013jZX3jD8iLBNBqvgPVLBnE
@vercel

vercel Bot commented Jul 27, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
zapp-web-v3 Ready Ready Preview, Comment Jul 27, 2026 8:47pm

@ecc-tools

ecc-tools Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 31f38ec0-f975-49ed-ac6c-3d463cc01266

📥 Commits

Reviewing files that changed from the base of the PR and between af6dffd and dad9852.

📒 Files selected for processing (6)
  • src/features/inbox/hooks/useChatMediaSending.ts
  • src/hooks/useAudioManagement.ts
  • src/hooks/useAudioRecorder.ts
  • src/hooks/useRealtimeMessages.ts
  • src/integrations/zappweb/hooks/useZappContactSearch.ts
  • vercel.json

Walkthrough

O PR ajusta o cleanup e as dependências de hooks de áudio e mídia, remove schemas explícitos nas consultas de contatos e substitui o vercel.json codificado por configurações estruturadas de build, SPA, segurança e cache.

Changes

Ciclo de vida e closures dos hooks

Layer / File(s) Summary
Cleanup e referências do gravador
src/hooks/useAudioRecorder.ts
Referências internas passam a armazenar recursos do gravador, e o cleanup de desmontagem é reposicionado após cleanupRecordingResources.
Dependências dos callbacks
src/features/inbox/hooks/useChatMediaSending.ts, src/hooks/useAudioManagement.ts
Handlers de emoji e áudio usam getSafePhone nas dependências, enquanto startRecording inclui setBlobUrl.

Consultas de contatos

Layer / File(s) Summary
Acesso às consultas de contatos
src/hooks/useRealtimeMessages.ts, src/integrations/zappweb/hooks/useZappContactSearch.ts
Consultas de contatos removem .schema('evo') e preservam os campos, filtros e processamento existentes.

Configuração do deploy Vercel

Layer / File(s) Summary
Build, roteamento e headers
vercel.json
O arquivo define build Vite com Bun, rewrite para SPA, headers de segurança e cache para arquivos estáticos e service workers.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/zapp-db-organization-docs-txezga

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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

@adm01-debug
adm01-debug marked this pull request as ready for review July 27, 2026 21:04
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@adm01-debug
adm01-debug merged commit 1ae5c6a into main Jul 27, 2026
41 checks passed
@adm01-debug
adm01-debug deleted the claude/zapp-db-organization-docs-txezga branch July 27, 2026 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants