{"record":{"id":"00451c396c2d0d9b","repo":"firecrawl/open-lovable","slug":"failed-to-generate-code","errorCode":null,"errorMessage":"Failed to generate code","messagePattern":"Failed to generate code","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"app/generation/page.tsx","lineNumber":3032,"sourceCode":"          lastProcessedPosition: 0\n        }));\n        \n        const aiResponse = await fetch('/api/generate-ai-code-stream', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify({ \n            prompt,\n            model: aiModel,\n            context: {\n              sandboxId: sandboxData?.sandboxId,\n              structure: structureContent,\n              conversationContext: conversationContext\n            }\n          })\n        });\n        \n        if (!aiResponse.ok || !aiResponse.body) {\n          throw new Error('Failed to generate code');\n        }\n        \n        const reader = aiResponse.body.getReader();\n        const decoder = new TextDecoder();\n        let generatedCode = '';\n        let explanation = '';\n        \n        while (true) {\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":3014,"sourceCodeEnd":3050,"githubUrl":"https://github.com/firecrawl/open-lovable/blob/69bd93bae7a9c97ef989eb70aabe6797fb3dac89/app/generation/page.tsx#L3014-L3050","documentation":"Thrown when the AI code-generation streaming endpoint returns a non-2xx status or a response without a readable body (aiResponse.ok === false || !aiResponse.body). The clone/brand generation request failed before any streamed code or explanation could be read, so the generation flow aborts. Note !response.body also fires on opaque or body-less responses even when status is OK.","triggerScenarios":"fetch to the generation route (with scraped content, brand guidelines, conversationContext) resolves with ok === false (route validation failure, upstream LLM error, missing route) OR resolves with no body stream (proxies stripping the body, unsupported streaming in the environment, opaque cross-origin response).","commonSituations":"LLM provider key/quota problems (401/402/429) after a long scraping session; oversized prompt from accumulated scrapedWebsites exceeding model context or body limits (413); environment without streaming support (older browsers/proxies buffering responses); generation route missing after a redeploy; streaming disabled by an intermediary.","solutions":["Inspect the failed generation request's status and body in the Network tab for the server-side reason","Verify the LLM API key, quota, and rate limits server-side if the status is 401/402/429","Trim conversationContext/scrapedWebsites to shrink the prompt if you hit 413 or context-length errors","Confirm the route exists and that no proxy strips the response body (test streaming via curl)","Retry with exponential backoff for 429/5xx; check aiResponse.body nullability to distinguish no-stream from HTTP failure"],"exampleFix":"// before\nif (!aiResponse.ok || !aiResponse.body) {\n  throw new Error('Failed to generate code');\n}\n// after\nif (!aiResponse.ok || !aiResponse.body) {\n  let detail = '';\n  try { detail = await aiResponse.text(); } catch {}\n  const cause = !aiResponse.ok\n    ? `HTTP ${aiResponse.status}: ${detail || aiResponse.statusText}`\n    : 'response has no readable body stream';\n  throw new Error(`Failed to generate code (${cause})`);\n}","handlingStrategy":"retry","validationCode":"const res = await fetch(GENERATION_URL, { method: 'POST', body: JSON.stringify(payload) });\nif (!res.ok) throw new Error(`Generation HTTP ${res.status}: ${await res.text().catch(() => res.statusText)}`);\nif (!res.body) throw new Error('Generation response has no body stream — check proxy/streaming support');","typeGuard":"function isStreamable(r: Response): r is Response & { ok: true; body: ReadableStream<Uint8Array> } {\n  return r.ok && r.body !== null && typeof r.body.getReader === 'function';\n}","tryCatchPattern":"async function generateStream(payload: unknown, retries = 3): Promise<Response> {\n  for (let attempt = 0; attempt < retries; attempt++) {\n    const res = await fetch(GENERATION_URL, { method: 'POST', body: JSON.stringify(payload) });\n    if (isStreamable(res)) return res;\n    const detail = await res.text().catch(() => '');\n    const retryable = [429, 500, 502, 503, 504].includes(res.status);\n    if (!retryable || attempt === retries - 1) {\n      throw new Error(`Failed to generate code (${res.status}): ${detail || res.statusText}`);\n    }\n    await new Promise(r => setTimeout(r, 2 ** attempt * 1000));\n  }\n  throw new Error('unreachable');\n}","preventionTips":["Distinguish HTTP failure (ok false) from missing-stream (body null) in error messages","Retry 429/5xx with exponential backoff; surface 4xx details immediately","Trim scrapedWebsites/conversationContext to keep prompts within limits","Verify the environment/proxy supports streaming response bodies","Confirm LLM provider credentials and quota server-side before long generation sessions"],"tags":["network","llm","streaming","http-status"],"backgroundTag":"http-non-2xx-response","analyzedSha":"69bd93bae7a9c97ef989eb70aabe6797fb3dac89","analyzedAt":"2026-08-28T22:20:32.339Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}