{"record":{"id":"bff863e461b4b7d9","repo":"firecrawl/open-lovable","slug":"failed-to-apply-code-response-statustext","errorCode":null,"errorMessage":"Failed to apply code: ${response.statusText}","messagePattern":"Failed to apply code: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"app/generation/page.tsx","lineNumber":657,"sourceCode":"        // Clear pending packages after use\n        (window as any).pendingPackages = [];\n      }\n      \n      // Use streaming endpoint for real-time feedback\n      const effectiveSandboxData = overrideSandboxData || sandboxData;\n      const response = await fetch('/api/apply-ai-code-stream', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ \n          response: code,\n          isEdit: isEdit,\n          packages: pendingPackages,\n          sandboxId: effectiveSandboxData?.sandboxId // Pass the sandbox ID to ensure proper connection\n        })\n      });\n      \n      if (!response.ok) {\n        throw new Error(`Failed to apply code: ${response.statusText}`);\n      }\n      \n      // Handle streaming response\n      const reader = response.body?.getReader();\n      const decoder = new TextDecoder();\n      let finalData: any = null;\n      \n      while (reader) {\n        const { done, value } = await reader.read();\n        if (done) break;\n        \n        const chunk = decoder.decode(value);\n        const lines = chunk.split('\\n');\n        \n        for (const line of lines) {\n          if (line.startsWith('data: ')) {\n            try {\n              const data = JSON.parse(line.slice(6));","sourceCodeStart":639,"sourceCodeEnd":675,"githubUrl":"https://github.com/firecrawl/open-lovable/blob/69bd93bae7a9c97ef989eb70aabe6797fb3dac89/app/generation/page.tsx#L639-L675","documentation":"This is a client-side guard thrown by the AISandboxPage component when the POST to the streaming /api/apply-ai-code-stream endpoint returns a non-2xx HTTP status. The API route failed before it could start streaming generated code into the sandbox, so response.ok is false. The statusText from the fetch Response is appended to expose the HTTP reason phrase (e.g. 'Internal Server Error', 'Not Found', 'Too Many Requests').","triggerScenarios":"fetch('/api/apply-ai-code-stream') returns response.ok === false — the route handler threw (bad sandboxId, sandbox WebSocket disconnected, package install failure), the route does not exist (404), or the request body (response/isEdit/packages/sandboxId) caused a server-side validation or runtime error.","commonSituations":"Sandbox was recycled or expired so the passed sandboxId is stale; dev server restarted while a long-running session kept an old sandbox ID; the API route crashes installing pendingPackages (npm registry down, invalid package name); proxy/load-balancer returns 502/504 for long streaming requests; deploying without the API route present (404 Not Found).","solutions":["Check the browser Network tab for the /api/apply-ai-code-stream request and read the actual status code and response body for the server-side error detail","Verify sandboxData.sandboxId is fresh — reinitialize the sandbox and retry instead of reusing a stale ID","Confirm the /api/apply-ai-code-stream route exists and inspect its server logs for the underlying exception","Clear or validate pendingPackages; a failing npm install on the server often 500s this endpoint","Retry with backoff if the status is 502/503/504 (transient gateway/timeout)"],"exampleFix":"// before\nif (!response.ok) {\n  throw new Error(`Failed to apply code: ${response.statusText}`);\n}\n// after\nif (!response.ok) {\n  let detail = response.statusText;\n  try { detail = (await response.json()).error ?? detail; } catch {}\n  if (response.status >= 500) { /* retry once with fresh sandbox */ }\n  throw new Error(`Failed to apply code (${response.status}): ${detail}`);\n}","handlingStrategy":"try-catch","validationCode":"const res = await fetch('/api/health/apply-stream', { method: 'HEAD' }).catch(() => null);\nif (!res || !res.ok) throw new Error('apply-ai-code-stream endpoint unavailable');\nif (!sandboxData?.sandboxId) throw new Error('No active sandbox — initialize one before applying code');","typeGuard":"function isOkResponse(r: Response): r is Response & { ok: true; body: ReadableStream } {\n  return r.ok && r.body !== null;\n}","tryCatchPattern":"try {\n  const response = await fetch('/api/apply-ai-code-stream', { ... });\n  if (!response.ok) {\n    const body = await response.text().catch(() => '');\n    throw Object.assign(new Error(`Apply failed: ${response.status} ${body || response.statusText}`), { status: response.status });\n  }\n  // ... stream reading\n} catch (err: any) {\n  addChatMessage(`Code application failed: ${err.message}`, 'system');\n  if (err.status >= 500) queueRetryWithBackoff();\n}","preventionTips":["Check response.ok and read the error body for diagnostics instead of relying on statusText alone","Validate sandboxId freshness before each apply; reinitialize stale sandboxes","Keep pendingPackages validated (name@version) to avoid server-side install failures","Add automatic retry with backoff for 5xx/429 statuses","Monitor the API route's server logs to catch recurring apply failures early"],"tags":["network","fetch","http-status","streaming","sandbox"],"backgroundTag":"http-non-2xx-response","analyzedSha":"69bd93bae7a9c97ef989eb70aabe6797fb3dac89","analyzedAt":"2026-08-28T22:20:32.339Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}