     1→// RateRight PWA Service Worker
     2→// Network-first for pages/API, cache-first only for static assets
     3→
     4→const CACHE_NAME = 'rateright-v2';
     5→const STATIC_CACHE = 'rateright-static-v2';
     6→
     7→const STATIC_ASSETS = [
     8→  '/offline',
     9→  '/logo_black.svg',
    10→  '/favicon.ico',
    11→];
    12→
    13→// Install — cache only truly static assets, take over immediately
    14→self.addEventListener('install', (event) => {
    15→  event.waitUntil(
    16→    caches.open(STATIC_CACHE)
    17→      .then((cache) => cache.addAll(STATIC_ASSETS))
    18→      .then(() => self.skipWaiting())
    19→  );
    20→});
    21→
    22→// Activate — purge ALL old caches, claim clients immediately
    23→self.addEventListener('activate', (event) => {
    24→  event.waitUntil(
    25→    caches.keys().then((cacheNames) => {
    26→      return Promise.all(
    27→        cacheNames.map((name) => {
    28→          if (name !== CACHE_NAME && name !== STATIC_CACHE) {
    29→            return caches.delete(name);
    30→          }
    31→        })
    32→      );
    33→    }).then(() => self.clients.claim())
    34→  );
    35→});
    36→
    37→// Fetch — network-first for everything except static assets
    38→self.addEventListener('fetch', (event) => {
    39→  const url = new URL(event.request.url);
    40→
    41→  // Skip non-GET requests
    42→  if (event.request.method !== 'GET') return;
    43→
    44→  // Skip API calls, auth callbacks, and _next/webpack — let them go straight to network
    45→  if (url.pathname.startsWith('/api/') ||
    46→      url.pathname.startsWith('/auth/') ||
    47→      url.pathname.includes('_next/webpack')) {
    48→    return;
    49→  }
    50→
    51→  // Static assets (images, fonts) — cache-first
    52→  if (url.pathname.match(/\.(svg|png|jpg|jpeg|gif|webp|ico|woff2?)$/)) {
    53→    event.respondWith(
    54→      caches.match(event.request).then((cached) => {
    55→        return cached || fetch(event.request).then((response) => {
    56→          if (response.ok) {
    57→            const clone = response.clone();
    58→            caches.open(STATIC_CACHE).then((cache) => cache.put(event.request, clone));
    59→          }
    60→          return response;
    61→        });
    62→      })
    63→    );
    64→    return;
    65→  }
    66→
    67→  // Everything else (pages, JS chunks) — NETWORK FIRST, fall back to cache
    68→  event.respondWith(
    69→    fetch(event.request)
    70→      .then((response) => {
    71→        if (response.ok) {
    72→          const clone = response.clone();
    73→          caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
    74→        }
    75→        return response;
    76→      })
    77→      .catch(() => {
    78→        return caches.match(event.request).then((cached) => {
    79→          if (cached) return cached;
    80→          // Offline fallback for navigation
    81→          if (event.request.mode === 'navigate') {
    82→            return caches.match('/offline');
    83→          }
    84→          return new Response('Offline', { status: 503 });
    85→        });
    86→      })
    87→  );
    88→});

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→// Service Worker registration script
     2→if ('serviceWorker' in navigator) {
     3→  window.addEventListener('load', () => {
     4→    navigator.serviceWorker.register('/sw.js').catch(() => {});
     5→  });
     6→}

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


Perfect! Now I have a complete picture. Let me generate the comprehensive report.

## Voice Processing Search Results

I've thoroughly searched the codebase and found all voice processing, speech recognition, and transcription-related files. Here's the complete inventory:

### 1. API Routes for Voice Processing

**File:** `/home/ccuser/the-50-dollar-app/src/app/api/ai/transcribe-voice/route.ts`
- Uses OpenAI Whisper API for audio transcription
- Takes audio blob → returns text transcript
- Includes CSRF protection, rate limiting, and auth checks
- Deprecated in favor of `/api/ai/voice-complete` for better performance
- Code snippet: Uses `openai.audio.transcriptions.create()` with whisper-1 model

**File:** `/home/ccuser/the-50-dollar-app/src/app/api/ai/parse-profile-voice/route.ts`
- Parses transcribed text using GPT-4o-mini
- Extracts structured profile data (trades, experience, location, availability)
- Uses prompt injection sanitization
- Deprecated in favor of consolidated endpoint
- Validates against TRADES constant and VALID_AVAILABILITY options

**File:** `/home/ccuser/the-50-dollar-app/src/app/api/ai/voice-complete/route.ts` (Optimized)
- Consolidated endpoint replacing the above two endpoints
- Handles transcription + parsing + profile generation in single call
- Supports both audio file upload and existing transcript input
- Enhanced error handling with fallback to manual completion
- Reduces processing time by 30-50% (from 5-12 seconds to 3-7 seconds)
- Key optimization: Merges 2 GPT-4o-mini calls into 1
- Includes performance timing data and fallback mode

**File:** `/home/ccuser/the-50-dollar-app/src/app/api/ai/voice-to-job/route.ts`
- Voice-to-job posting for contractors
- Transcribes audio and extracts structured job fields
- Returns all fields needed to auto-fill job posting form
- Validates trade IDs and applies intelligent defaults
- Includes rate clamping (MIN_RATE: $25, MAX_RATE: $500)
- Strips contact info from generated content to prevent platform bypass

---

### 2. Frontend Components and Hooks

**File:** `/home/ccuser/the-50-dollar-app/src/components/VoiceRecorder.tsx`
- Standalone reusable voice recording component
- Uses MediaRecorder API (`navigator.mediaDevices.getUserMedia`)
- Supports audio/webm or audio/mp4 MIME types
- Error handling for: NotAllowedError, NotFoundError, SecurityError, AbortError
- Shows visual feedback: mic icon, recording pulse animation, stop button
- Returns audio blob to parent component

**File:** `/home/ccuser/the-50-dollar-app/src/app/(authenticated)/worker/signup/hooks/useVoiceProcessing.ts`
- Custom hook for worker profile voice processing
- Multi-step voice completion: transcribe → parse → navigate to next form step
- Integrates with `/api/ai/transcribe-voice` and `/api/ai/parse-profile-voice`
- Smart step navigation based on parsed fields
- CSRF token management (`initializeCSRF()`, `getCSRFCookie()`)
- Error state management with user-facing messages
- Supports pre-filling multiple trades, experience, location, availability

---

### 3. Page Components with Voice Integration

**File:** `/home/ccuser/the-50-dollar-app/src/app/(authenticated)/contractor/post-job/page.tsx`
- Voice input for job posting (primary CTA)
- Large 24x24 px mic button for voice recording
- States: starting, recording, stop
- Uses `/api/ai/voice-to-job` endpoint
- Auto-fills all form fields from voice: trade, title, description, rates, certifications, location, date, workers needed
- **Error toast message:** `"Voice processing failed. Try again or type your job details."` (line 252)
- Fallback messaging: `"AI couldn't fully process your voice. Please fill in the details."` when fallback flag is set
- Loading state shows: "Listening to your voice..." → "AI writing your job post..."

**File:** `/home/ccuser/the-50-dollar-app/src/app/(authenticated)/worker/profile/build/page.tsx`
- Voice input for worker profile building
- Comments indicate optimization: "reduces voice processing time from ~5-12 seconds to ~3-7 seconds"
- Uses consolidated `/api/ai/voice-complete` endpoint (mentioned in comments)
- Multi-step form with voice-to-profile conversion
- Generates bio, skills, and certifications from voice input

---

### 4. Service Worker Files

**File:** `/home/ccuser/the-50-dollar-app/public/sw.js`
- PWA service worker with network-first strategy for pages/API
- Caches static assets (images, SVG, fonts)
- Network-first fetch for API calls (all `/api/` requests bypass cache and go straight to network)
- Important: API calls including voice processing routes are not cached

**File:** `/home/ccuser/the-50-dollar-app/public/register-sw.js`
- Simple service worker registration script
- Registered on page load event

---

### 5. Documentation Files

**File:** `/home/ccuser/the-50-dollar-app/voice-processing-analysis.md`
- Comprehensive analysis of voice processing flow
- Identifies sequential API call bottleneck (3 calls: transcribe → parse → generate)
- Details optimization opportunities
- Performance baseline: 5-12 seconds total

**File:** `/home/ccuser/the-50-dollar-app/voice-optimization-summary.md`
- Implementation summary of voice processing optimization
- Phase-based approach: API consolidation → error handling → performance monitoring → streaming
- Expected improvements: 30-50% faster (3-7 seconds)
- Testing strategy and risk assessment included

---

### 6. Summary of Voice Processing Features

**Recording:**
- Uses Web Audio API (`MediaRecorder`, `getUserMedia`)
- Captures audio in webm or mp4 format
- Blob-based transmission to API

**Transcription:**
- OpenAI Whisper API (whisper-1 model)
- Language: English
- Sanitization for injection prevention

**AI Processing:**
- GPT-4o-mini for parsing and generation
- Extracts structured data (trades, experience, location, availability)
- Generates professional bios, skills, certifications
- Temperature: 0.3 (deterministic output)

**Error Handling:**
- Toast messages: `"Voice processing failed. Try again or type your job details."` (contractor job posting)
- Fallback mode when AI processing fails
- Transcript preservation for manual completion
- Specific error messages for different failure modes

**Security:**
- CSRF protection on all voice endpoints
- Rate limiting: 10 requests per 15 minutes per user (with some endpoints at 5 per 15 minutes)
- Input sanitization (`sanitizeInput`, `stripContactInfo`)
- Auth check on all endpoints
- Contact info stripping from generated content

**Performance:**
- Consolidated endpoint reduces calls from 3 to 1-2
- Processing time: 3-7 seconds (optimized from 5-12 seconds)
- No caching in service worker for API calls
- Network-first strategy for dynamic content