Files
karaoke-gen/frontend/lib/client-error-setup.ts
Andrew Beveridge ☄️andClaude Opus 5.5 a2e8e98eaf fix: user-instrumental renders for any audio format + crash-report diagnostics (v0.243.1) (#1060)
## Summary
**1. User-instrumental renders failed for WAV/M4A/OGG/AAC** (job
3ea34552: "Encoding failed on retry: No instrumental audio found")
- The orchestrator render path sent only
`instrumental_selection="custom"` to the GCE encoder.
- The encoder's custom lookup accepted just
`*custom_instrumental*.{flac,mp3}`, and the staged copy kept its
original extension. Tenant MP3s worked; a `.wav` didn't.
- Fix: the orchestrator now passes `existing_instrumental`, so the
encoder downloads the file and matches any extension. The custom lookup
(extracted as `resolve_instrumental`, now tested directly rather than
via copied globs) also accepts any audio extension.

**2. Crash reports now carry enough to diagnose.** A Firefox "Uncaught
out of memory" froze a tab and the alert was useless:
- There was no Error object, so the reporter's own stack became the
pattern.
- The stack pushed URL/UA/build out of Discord's view.
- `extra` was never kept.

Changes:
- **Frontend:** `lib/diagnostics.ts` keeps a 30-entry breadcrumb trail
(nav, clicks, upload phases, errors) and snapshots page age,
DOM/canvas/audio counts, live blob URLs and the JS heap (Chromium).
Errors without an Error object are flagged `synthetic` (reporter stack
dropped, location kept). Each page load can send at most 20 reports.
Benign media `AbortError` rejections are still filtered.
- **Backend:**
- Sample order is now message → location → URL/UA/build → `Diag:` →
`Trail:` → trimmed stack.
  - Stackless errors group by message.
- The full `extra` is logged as `client_extra` on
`frontend_crash_reported`.
  - `TROUBLESHOOTING.md` has a runbook entry.

## Testing
- New backend tests: `resolve_instrumental` across extensions,
orchestrator config, GCE backend config forwarding, and ingestion
sample/grouping.
- New Jest tests: diagnostics, reporter, global handlers, upload
breadcrumbs.
- Targeted backend suites pass. The frontend Jest suite passes in full.
- The full local backend run hit 93 failures from the shared dev env's
`idna` being upgraded mid-run by another process (`ImportError:
uts46data`). These are unrelated to this diff; CI is the gate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Custom instrumentals can now be used in renders from WAV, M4A, OGG,
AAC, MP3, and FLAC files. When multiple supported versions are
available, FLAC is preferred.
* Crash reports now include additional browser diagnostics and recent
activity, helping provide more context when an error occurs.
* **Bug Fixes**
* Added a clearer message when an uploaded instrumental exceeds the size
limit, including the maximum size and supported format suggestions.
* Improved grouping of frontend errors when a stack trace is
unavailable.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 21:36:09 -04:00

118 lines
4.3 KiB
TypeScript

'use client'
import { isBenignError, reportClientError } from '@/lib/crash-reporter'
import { addBreadcrumb, installDiagnostics } from '@/lib/diagnostics'
import { hardReload, isChunkLoadError, isStale, startAmbientVersionPoll } from '@/lib/version-check'
let installed = false
// Known locale prefixes — matches next-intl routing config. Any route whose
// first segment isn't in this set (e.g. /admin, /app) falls through to 'en'.
const KNOWN_LOCALES = new Set([
'ar', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'fi', 'fr', 'he', 'hi', 'hr',
'hu', 'id', 'it', 'ja', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv',
'th', 'tl', 'tr', 'uk', 'vi', 'zh',
])
function detectLocale(): string {
if (typeof window === 'undefined') return 'en'
const first = window.location.pathname.split('/').filter(Boolean)[0]
if (first && KNOWN_LOCALES.has(first)) return first
return 'en'
}
function buildContext(userEmail: string | null) {
return {
href: typeof window !== 'undefined' ? window.location.href : '',
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
innerWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,
innerHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,
locale: detectLocale(),
userEmail,
}
}
/**
* Browsers hide errors thrown by cross-origin scripts (third-party tags, in-app
* browser/extension injections) behind a bare "Script error." with no error
* object, filename or line. There's nothing actionable in them — the only stack
* we'd get is our own handler's — so they're alert noise.
*/
export function isOpaqueCrossOriginError(
event: Pick<ErrorEvent, 'error' | 'message'>
): boolean {
return event.error == null && /^Script error\.?$/i.test((event.message ?? '').trim())
}
export function installGlobalErrorHandlers(getUserEmail: () => string | null) {
if (installed) return
if (typeof window === 'undefined') return
installed = true
installDiagnostics()
const maybeReloadForChunkError = async (err: unknown): Promise<boolean> => {
if (!isChunkLoadError(err)) return false
const staleResult = await isStale().catch(() => null)
// If the bundle is stale OR we can't verify, still reload — ChunkLoadError
// by itself is strong signal of post-deploy mismatch.
const triggered = hardReload(staleResult?.latestSha)
return triggered
}
window.addEventListener('error', (event) => {
if (isOpaqueCrossOriginError(event)) return
// Some engine-level failures (Firefox "out of memory") arrive with no Error
// object — or a non-Error value — so there is no real stack to send.
const synthetic = !(event.error instanceof Error)
const err = synthetic
? new Error(event.message || String(event.error ?? 'Unknown window error'))
: event.error
addBreadcrumb('error', (err as Error).message)
void (async () => {
const reloaded = await maybeReloadForChunkError(err)
if (reloaded) return
void reportClientError({
error: err,
source: 'window.onerror',
context: buildContext(getUserEmail()),
synthetic,
extra: {
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
},
})
})()
})
window.addEventListener('unhandledrejection', (event) => {
// Check the raw reason before wrapping so e.g. a media AbortError DOMException
// is still recognised as benign.
if (isBenignError(event.reason)) return
const synthetic = !(event.reason instanceof Error)
const err = synthetic ? new Error(String(event.reason)) : event.reason
addBreadcrumb('error', `unhandledrejection: ${(err as Error).message}`)
void (async () => {
const reloaded = await maybeReloadForChunkError(err)
if (reloaded) return
void reportClientError({
error: err,
source: 'unhandledrejection',
context: buildContext(getUserEmail()),
synthetic,
})
})()
})
// Ambient poll: every 10 min, if stale, stash info for UI to pick up via
// a CustomEvent. We do NOT auto-reload here — that's reserved for crashes.
startAmbientVersionPoll((r) => {
try {
sessionStorage.setItem('karaoke_latest_sha', r.latestSha)
window.dispatchEvent(new CustomEvent('karaoke:stale-version', { detail: r }))
} catch {
/* ignore */
}
})
}