import React, { useState, useEffect } from "react"; import { AlertOctagon, Terminal, Clipboard, Download, Mail, FileText, Check, Calendar, Settings, Layers, Radio, User, Info, ChevronDown, ChevronUp, FileCode, ShieldAlert, Archive, RefreshCw } from "lucide-react"; import { motion, AnimatePresence } from "motion/react"; export type FailureCategory = | "TRANSCRIPTION_TIMEOUT" | "EMPTY_RESPONSE" | "API_KEY_ERROR" | "CLIENT_DSP_ERROR" | "AUDIO_LENGTH_TOO_LONG" | "DASHBOARD_RENDER_ERROR" | "OTHER_SYSTEM_FAILURE"; export interface FailureReport { id: string; timestamp: string; category: FailureCategory; categoryLabel: string; errorMessage: string; logs: string[]; systemSpecs: { browser: string; os: string; webAudioSupported: boolean; localStorageSupported: boolean; screenResolution: string; timezone: string; }; audioMetadata: { fileName: string; fileSize: string; mimeType: string; durationSeconds: string; } | null; dspSettings: { preset: string; blend: number; margin: number; onsetThreshold: number; offsetThreshold: number; frameThreshold: number; bpm: number; quantize: boolean; quantizeGrid: string; }; userComments: string; expectedBehavior: string; } interface FailureReportGeneratorProps { latestError: string; transcriptionLogs: string[]; audioFile: File | null; audioDuration: number; selectedPreset: string; blend: number; margin: number; onsetThreshold: number; offsetThreshold: number; frameThreshold: number; bpm: number; quantize: boolean; quantizeGrid: string; onClearError?: () => void; } export default function FailureReportGenerator({ latestError, transcriptionLogs, audioFile, audioDuration, selectedPreset, blend, margin, onsetThreshold, offsetThreshold, frameThreshold, bpm, quantize, quantizeGrid, onClearError }: FailureReportGeneratorProps) { const [isOpen, setIsOpen] = useState(false); const [category, setCategory] = useState("EMPTY_RESPONSE"); const [userComments, setUserComments] = useState(""); const [expectedBehavior, setExpectedBehavior] = useState(""); const [copied, setCopied] = useState(false); const [reportsHistory, setReportsHistory] = useState([]); const [selectedFormat, setSelectedFormat] = useState<"markdown" | "json">("markdown"); const [activeTab, setActiveTab] = useState<"build" | "view" | "history">("build"); // Load local failure report history from browser session useEffect(() => { try { const stored = sessionStorage.getItem("stemtomidi_failure_reports"); if (stored) { setReportsHistory(JSON.parse(stored)); } } catch (e) { console.warn("Could not read reports history from session storage", e); } }, []); // Proactively open when error is received useEffect(() => { if (latestError) { setIsOpen(true); // Deduce category from error string if (latestError.toLowerCase().includes("api") || latestError.toLowerCase().includes("key")) { setCategory("API_KEY_ERROR"); } else if (latestError.toLowerCase().includes("timeout") || latestError.toLowerCase().includes("504")) { setCategory("TRANSCRIPTION_TIMEOUT"); } else if (latestError.toLowerCase().includes("resample") || latestError.toLowerCase().includes("decode")) { setCategory("CLIENT_DSP_ERROR"); } else if (latestError.toLowerCase().includes("empty") || latestError.toLowerCase().includes("0 notes")) { setCategory("EMPTY_RESPONSE"); } else { setCategory("OTHER_SYSTEM_FAILURE"); } } }, [latestError]); const CATEGORY_LABELS: Record = { TRANSCRIPTION_TIMEOUT: "Transcriber Timeout / Server Refused (504)", EMPTY_RESPONSE: "Zero Pitch Notes Detected (Empty Output)", API_KEY_ERROR: "Gemini Key or Authentication Rejected", CLIENT_DSP_ERROR: "Client-side Audio DSP / Resampling Failure", AUDIO_LENGTH_TOO_LONG: "Audio Timeline Truncated (> 50MB)", DASHBOARD_RENDER_ERROR: "Vite Client WebGL or Canvas Frame Glitch", OTHER_SYSTEM_FAILURE: "Unspecified System Pipeline Exception" }; const getSystemSpecs = () => { const userAgent = navigator.userAgent; let browser = "Unknown Browser"; if (userAgent.match(/chrome|chromium|crios/i)) browser = "Google Chrome"; else if (userAgent.match(/firefox|fxios/i)) browser = "Mozilla Firefox"; else if (userAgent.match(/safari/i)) browser = "Apple Safari"; else if (userAgent.match(/opr\//i)) browser = "Opera"; else if (userAgent.match(/edg/i)) browser = "Microsoft Edge"; let os = "Unknown Operating System"; if (userAgent.match(/windows/i)) os = "Windows OS"; else if (userAgent.match(/macintosh|mac os/i)) os = "macOS"; else if (userAgent.match(/linux/i)) os = "Linux OS"; else if (userAgent.match(/android/i)) os = "Android OS"; else if (userAgent.match(/iphone|ipad/i)) os = "iOS"; return { browser, os, webAudioSupported: typeof (window.AudioContext || (window as any).webkitAudioContext) !== "undefined", localStorageSupported: typeof window.localStorage !== "undefined", screenResolution: `${window.screen.width}x${window.screen.height}`, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC" }; }; const currentReportObj = (): FailureReport => { return { id: `REP-${Math.floor(1000 + Math.random() * 9000)}`, timestamp: new Date().toISOString(), category, categoryLabel: CATEGORY_LABELS[category], errorMessage: latestError || "None (Manual Diagnostic Report)", logs: transcriptionLogs.length > 0 ? transcriptionLogs : ["No log files registered in this cycle."], systemSpecs: getSystemSpecs(), audioMetadata: audioFile ? { fileName: audioFile.name, fileSize: `${(audioFile.size / (1024 * 1024)).toFixed(2)} MB (${audioFile.size} bytes)`, mimeType: audioFile.type || "audio/octet-stream", durationSeconds: audioDuration > 0 ? `${audioDuration.toFixed(2)}s` : "Unknown" } : null, dspSettings: { preset: selectedPreset, blend, margin, onsetThreshold, offsetThreshold, frameThreshold, bpm, quantize, quantizeGrid }, userComments: userComments.trim() || "No customized provider notes entered.", expectedBehavior: expectedBehavior.trim() || "No expected behavior specified." }; }; const generateMarkdownReport = (report: FailureReport) => { return `# STEMTOMIDI DIAGNOSTIC FAILURE REPORT Generated: ${report.timestamp} Report ID: ${report.id} ==================================================================== ## 1. FATAL INCIDENT CLASSIFICATION * **Category:** ${report.categoryLabel} * **Event Severity:** HIGH - Pipeline Interrupted * **Diagnostic Exception Code:** [${report.category}] * **Engine Statement:** "${report.errorMessage}" ## 2. ACTIVE DIGITAL SIGNAL PROCESSING (DSP) STACK * **Preset Configuration Template:** "${report.dspSettings.preset}" * **Separation Filter Blend Factor:** ${report.dspSettings.blend} * **Wiener Mask Spectral Margin:** ${report.dspSettings.margin} * **Pitch Onset Sensitivity Threshold:** ${report.dspSettings.onsetThreshold} (Upstream Target) * **Pitch Offset Exit Threshold:** ${report.dspSettings.offsetThreshold} * **Frame Amplitude Salience Floor:** ${report.dspSettings.frameThreshold} * **BPM Counter Estimate:** ${report.dspSettings.bpm} BPM * **Grid Quantize Alignment Enabled:** ${report.dspSettings.quantize ? "YES" : "NO"} * **Quantize Metric Grid Range:** "${report.dspSettings.quantizeGrid}" ## 3. FILE PROPERTY METADATA ${report.audioMetadata ? `* **Filename:** ${report.audioMetadata.fileName} * **Payload Absolute Size:** ${report.audioMetadata.fileSize} * **Encoded Mime-Type Flag:** ${report.audioMetadata.mimeType} * **Audio Track Duration Timeline:** ${report.audioMetadata.durationSeconds}` : "* **Audio Track File Status:** No active file loaded when diagnostics were triggered."} ## 4. BROWSER ENVIRONMENT CONTEXT * **Software Client:** ${report.systemSpecs.browser} * **Base Platform Kernel:** ${report.systemSpecs.os} * **HTML5 Web Audio API Core Enabled:** ${report.systemSpecs.webAudioSupported ? "YES" : "NO"} * **Local State Keystore Engine Available:** ${report.systemSpecs.localStorageSupported ? "YES" : "NO"} * **Display Output Standard:** ${report.systemSpecs.screenResolution} * **Location Timezone Offset:** ${report.systemSpecs.timezone} ## 5. PRACTITIONER DIAGNOSTIC NOTES * **Incident Description Memo:** > ${report.userComments.replace(/\n/g, "\n > ")} * **Expected Audio Output Desired:** > ${report.expectedBehavior.replace(/\n/g, "\n > ")} ## 6. COMPLETE TRANSCRIPTION CONSOLE LOGS \`\`\` ${report.logs.join("\n")} \`\`\` ==================================================================== StemToMIDI Diagnostics Subsystem - End of Registry Pack. `; }; const getFormattedReportString = () => { const report = currentReportObj(); if (selectedFormat === "json") { return JSON.stringify(report, null, 2); } return generateMarkdownReport(report); }; const handleCopy = () => { navigator.clipboard.writeText(getFormattedReportString()); setCopied(true); setTimeout(() => setCopied(false), 2000); }; const downloadReportFile = () => { const report = currentReportObj(); const content = getFormattedReportString(); const extension = selectedFormat === "json" ? "json" : "md"; const mime = selectedFormat === "json" ? "application/json" : "text/markdown"; const blob = new Blob([content], { type: mime }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = `StemToMIDI_FailureReport_${report.id.toLowerCase()}.${extension}`; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; const handleSaveReport = () => { const newReport = currentReportObj(); const updatedHistory = [newReport, ...reportsHistory].slice(0, 15); // limit to 15 records setReportsHistory(updatedHistory); sessionStorage.setItem("stemtomidi_failure_reports", JSON.stringify(updatedHistory)); // Switch to history view setActiveTab("history"); }; const clearReportHistory = () => { setReportsHistory([]); sessionStorage.removeItem("stemtomidi_failure_reports"); }; const triggerEmailReport = () => { const report = currentReportObj(); const subject = encodeURIComponent(`[StemToMIDI Failure Report] ${report.categoryLabel} (${report.id})`); // Shortened body to avoid mailto browser character limits const briefBody = `Hi Support, I encountered an error while transcribing audio in StemToMIDI. --- INCIDENT SUMMARY --- Report ID: ${report.id} Time: ${report.timestamp} Error: ${report.errorMessage} Category: ${report.categoryLabel} File Name: ${report.audioMetadata?.fileName || "None"} Browser OS: ${report.systemSpecs.browser} / ${report.systemSpecs.os} Custom Comments: ${report.userComments} Expected Behavior: ${report.expectedBehavior} ------------------------- Please find the complete markdown diagnostic report and log registry below (please copy and paste the report if needed): `; const mailto = `mailto:purarecoveryryan@gmail.com?subject=${subject}&body=${encodeURIComponent(briefBody)}`; window.open(mailto, "_blank"); }; const report = currentReportObj(); return (
{/* Decorative Warning glow background */}
{/* Accordion header bar */}
setIsOpen(!isOpen)} className="flex items-center justify-between cursor-pointer select-none pb-1" >

DIAGNOSTIC REPORT FRAMEWORK

Analyze, bundle, compile, and download diagnostic system reports when transcribing failures occur.

{isOpen && (
{/* Tab selector menu */}
{/* TAB 1: BUILD REPORT WITH METADATA */} {activeTab === "build" && (
{/* Left Parameter Inputs Column */}
{/* Failure Category */}
{/* Incidents notes */}