# Execution Plan: Fix Critical App Functionality Issues **OUTCOME_NAME:** FixCriticalAppFunctionalityIssues **Created:** 22 December 2025 **Problem Statement:** The insta-recipe application has four critical issues preventing core functionality: (1) Queued items never start processing despite the queue system being implemented, (2) Frontend SSE connection status display never updates properly, (3) Service worker never gets installed due to registration conflicts, and (4) Multiple tests are failing with incorrect error status codes and queue processing timeouts. These interconnected issues are preventing the app from functioning as intended and frustrating users who expect a working queue processing system with real-time updates and PWA functionality. --- ## Current State Analysis ### Issue 1: Queue Processing System Not Starting **Symptoms:** - Items are successfully enqueued but remain in 'pending' status indefinitely - Queue processor integration tests failing with items never progressing to 'success' - No processing activity visible in logs despite QueueProcessor being implemented **Evidence:** - Test failure: `expect(updated?.status).toBe('success')` but received `'pending'` - QueueProcessor has auto-start code: `queueProcessor.start()` on module import - But processor may not be imported anywhere in the running application ### Issue 2: SSE Connection Status Never Updates **Symptoms:** - EventSource connection may be working but UI never shows "Live updates" - Connection status indicator remains "Disconnected" even when SSE is functional - Real-time queue updates may not be displaying properly in frontend **Evidence:** - EventSource implementation exists with proper browser guards - SSE endpoint `/api/queue/stream` implemented and functional - Connection status logic: `{eventSource?.readyState === 1 ? 'Live updates' : 'Disconnected'}` ### Issue 3: Service Worker Never Installs **Symptoms:** - PWA functionality broken due to service worker registration failures - Multiple attempts to fix workbox initialization haven't resolved the core issue - Conflicts between SvelteKit and vite-pwa service worker registration **Evidence:** - Multiple registerSW.js files indicating conflicting registration attempts - Service worker has comprehensive error handling but still fails to register - SvelteKit service worker not properly disabled in configuration ### Issue 4: Test Suite Failures (16 tests failing) **Symptoms:** - Queue API endpoints returning 500 status codes instead of expected 400/404/409 - Queue processor integration tests timing out waiting for processing - Error handling not working correctly across API endpoints **Evidence:** - API tests: `expected 400 to be 500` pattern across multiple endpoints - Queue processor tests: Items remain 'pending' instead of being processed - Suggests both API error handling and queue processing are broken --- ## Root Cause Analysis ### Primary Issue: QueueProcessor Not Starting in Production The QueueProcessor module exports a singleton that auto-starts on import, but it appears not to be imported anywhere in the running application. The tests import it directly, but the actual app may not be triggering the import, leaving the processor dormant. ### Secondary Issue: API Error Handling Middleware Missing All queue API endpoints are throwing unhandled exceptions instead of returning proper HTTP status codes. This suggests missing or broken error handling middleware that should catch validation errors and return appropriate 400/404/409 responses. ### Tertiary Issue: Service Worker Registration Conflicts SvelteKit's built-in service worker registration is still active while vite-pwa is also trying to register a service worker, creating conflicts that prevent either from working correctly. ### Quaternary Issue: SSE Reactivity Problems The EventSource connection status may be working but not triggering reactive updates in the Svelte component, leaving the UI in a stale state. --- ## Solution Architecture ### Hexagonal Architecture Mapping ``` ┌─────────────────────────────────────────────────┐ │ Primary Adapters (Inbound) │ │ - Queue API Endpoints: Process requests │ │ - Queue Dashboard: Display status │ │ - Service Worker: PWA functionality │ └─────────────────┬───────────────────────────────┘ │ ┌─────────────────┴───────────────────────────────┐ │ Domain (Core) │ │ ┌────────────────────────────────────────────┐ │ │ │ QueueManager (Port) │ │ │ │ - Manages queue state and subscribers │ │ │ │ QueueProcessor (Domain Service) │ │ │ │ - Orchestrates processing workflow │ │ │ │ Error Handling (Domain Logic) │ │ │ │ - Validates inputs and manages errors │ │ │ └────────────────────────────────────────────┘ │ └─────────────────┬───────────────────────────────┘ │ ┌─────────────────┴───────────────────────────────┐ │ Secondary Adapters (Outbound) │ │ - Extraction Service: Browser automation │ │ - Parser Service: LLM recipe extraction │ │ - Tandoor Service: Recipe upload │ │ - Push Notification Service: User alerts │ └─────────────────────────────────────────────────┘ ``` ### Technical Design #### Fix 1: Queue Processor Startup Ensure QueueProcessor is imported during app initialization by adding explicit import to server hooks, guaranteeing the auto-start code executes when the server starts. #### Fix 2: API Error Handling Middleware Implement comprehensive error handling that catches different exception types and returns proper HTTP status codes based on the error category (validation → 400, not found → 404, conflict → 409). #### Fix 3: Service Worker Registration Completely disable SvelteKit's service worker and ensure only vite-pwa handles registration, with proper workbox manifest injection for development and production environments. #### Fix 4: SSE Connection Reactivity Add explicit reactivity triggers and connection state management to ensure UI updates when EventSource connection status changes. --- ## Story Breakdown ### Story 1: Fix Queue Processor Startup and Import **Priority:** Critical **Dependencies:** None **Estimated Effort:** Small (1-2 hours) **Objective:** Ensure QueueProcessor starts when the application starts, enabling automatic processing of queued items. **Root Cause:** QueueProcessor singleton auto-starts on module import, but the module isn't imported anywhere in the running application, leaving the processor dormant despite being fully implemented. **Tasks:** 1. Add explicit QueueProcessor import to `src/hooks.server.ts` 2. Add startup logging to confirm processor initialization 3. Add health check endpoint to verify processor status 4. Test that queued items are processed automatically after restart 5. Verify all existing queue processor tests pass **Technical Implementation:** ```typescript // src/hooks.server.ts import './lib/server/queue/QueueProcessor'; // Trigger auto-start export const handle: Handle = async ({ event, resolve }) => { // Existing handle logic }; ``` **Acceptance Criteria:** - ✅ QueueProcessor starts automatically when application starts - ✅ Queued items transition from 'pending' to 'in_progress' to 'success'/'error' - ✅ Server logs show processor initialization and activity - ✅ All queue processor integration tests pass - ✅ Processing works in both development and production environments **Files:** - `src/hooks.server.ts` (modify - add import) - `src/routes/api/health/+server.ts` (new - health check endpoint) --- ### Story 2: Implement Comprehensive API Error Handling **Priority:** Critical **Dependencies:** None **Estimated Effort:** Medium (2-3 hours) **Objective:** Fix API endpoints to return proper HTTP status codes instead of 500 errors, enabling correct error handling and test validation. **Root Cause:** API endpoints are throwing unhandled exceptions that result in generic 500 responses instead of specific error status codes. Missing error handling middleware to catch and classify different error types. **Tasks:** 1. Create error handling middleware for API endpoints 2. Add validation error classification (400 for bad input) 3. Add not found error handling (404 for missing resources) 4. Add conflict error handling (409 for invalid state operations) 5. Update all queue API endpoints to use proper error handling 6. Test all API endpoints return correct status codes 7. Verify all 12 failing API tests now pass **Technical Implementation:** ```typescript // src/lib/server/api/errorHandler.ts export function handleApiError(error: unknown): Response { if (error instanceof ValidationError) { return json({ message: error.message }, { status: 400 }); } if (error instanceof NotFoundError) { return json({ message: error.message }, { status: 404 }); } if (error instanceof ConflictError) { return json({ message: error.message }, { status: 409 }); } // Generic 500 for unexpected errors console.error('Unhandled API error:', error); return json({ message: 'Internal server error' }, { status: 500 }); } // Usage in API endpoints: export const POST: RequestHandler = async ({ request }) => { try { // API logic } catch (error) { return handleApiError(error); } }; ``` **Acceptance Criteria:** - ✅ All queue API endpoints return correct HTTP status codes - ✅ Validation errors return 400 with descriptive messages - ✅ Not found errors return 404 with appropriate messages - ✅ Conflict errors return 409 with state information - ✅ All 12 failing API tests now pass - ✅ Error responses include helpful error messages - ✅ Unexpected errors still log to server console **Files:** - `src/lib/server/api/errorHandler.ts` (new) - `src/lib/server/api/errors.ts` (new - error classes) - `src/routes/api/queue/+server.ts` (modify) - `src/routes/api/queue/[id]/+server.ts` (modify) - `src/routes/api/queue/[id]/retry/+server.ts` (modify) --- ### Story 3: Resolve Service Worker Registration Conflicts **Priority:** High **Dependencies:** None **Estimated Effort:** Medium (2-3 hours) **Objective:** Fix service worker registration by eliminating conflicts and ensuring proper PWA functionality. **Root Cause:** SvelteKit's built-in service worker registration is still active while vite-pwa is also trying to register a service worker, creating conflicts. Additionally, workbox manifest injection may not be working correctly in the build process. **Tasks:** 1. Disable SvelteKit service worker registration in `svelte.config.js` 2. Verify vite-pwa configuration for proper workbox manifest injection 3. Ensure service worker TypeScript compilation produces valid code 4. Add environment-specific service worker behavior 5. Test service worker registration in both development and production 6. Verify PWA functionality (installation, offline, push notifications) 7. Clean up conflicting registerSW.js files **Technical Implementation:** ```typescript // svelte.config.js const config = { kit: { adapter: adapter(), serviceWorker: { register: false // Disable SvelteKit's service worker } } }; // vite.config.ts - enhanced configuration SvelteKitPWA({ strategies: 'injectManifest', filename: 'service-worker.ts', mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', injectManifest: { swSrc: 'src/service-worker.ts', swDest: 'service-worker.js', injectionPoint: 'self.__WB_MANIFEST' }, workbox: { globPatterns: ['client/**/*.{js,css,ico,png,svg,webp,woff,woff2}'], cleanupOutdatedCaches: true }, devOptions: { enabled: true, suppressWarnings: true, type: 'module' } }); ``` **Acceptance Criteria:** - ✅ Service worker registers successfully without evaluation errors - ✅ Only one service worker registration visible in browser DevTools - ✅ Workbox precaching initializes correctly with proper manifest - ✅ Push notifications continue to work as before - ✅ PWA installation prompt appears correctly - ✅ Service worker works in both development and production - ✅ No service worker-related console errors **Files:** - `svelte.config.js` (modify - disable service worker registration) - `vite.config.ts` (modify - enhance vite-pwa config) - `src/service-worker.ts` (modify - add better error handling) --- ### Story 4: Fix SSE Connection Status Display **Priority:** Medium **Dependencies:** Story 1 (for queue updates to flow) **Estimated Effort:** Small (1-2 hours) **Objective:** Ensure frontend correctly displays SSE connection status and receives real-time updates from the queue processing system. **Root Cause:** EventSource connection may be working but not triggering reactive updates in the Svelte component, or event handling is not properly updating the UI state. **Tasks:** 1. Debug EventSource connection establishment and event flow 2. Add explicit reactivity triggers for connection status changes 3. Enhance SSE event handling with better error recovery 4. Add connection status indicators with proper state management 5. Test real-time queue updates display correctly 6. Add reconnection logic for dropped connections 7. Verify connection status updates in real-time **Technical Implementation:** ```svelte