How to Debug AI-Generated Code When Your Coding Agent Gets Stuck
Every AI-assisted builder eventually hits the loop. The app throws an error, you paste it to your coding agent, it says "I've fixed the issue", the error changes slightly or comes back, and twenty prompts later you are further from a working app than when you started. The agent is not lazy and you are not doing it wrong. Debugging is simply the part of programming where guessing works worst, and an agent without good information is forced to guess.
This guide gives you a repeatable method for debugging AI-generated code, whether you build with Cursor, Claude Code, Windsurf, Replit, Bolt or Lovable. It works even if you cannot read every line of the code yourself, because the main skill is not reading code. It is collecting evidence and narrowing down where the problem lives.
Step 0: Stop the loop
The first rule is to recognise the loop early. If the agent has tried to fix the same problem two or three times without success, stop prompting "it still doesn't work". Each failed attempt adds changes on top of changes, and the original bug gets buried under fixes for imaginary bugs.
Do this instead:
- Go back to a known good state if you have one. With Git,
git restore .discards uncommitted changes, andgit logplusgit revertundo bad commits. If you are not using Git yet, read Git for vibe coders; it is the single biggest upgrade to debugging. - Start a fresh chat session. A long conversation full of wrong theories steers the model towards more wrong theories. A clean session with good evidence often solves in one step what the old session could not solve in twenty.
- Switch from "fix it" to "find it". The rest of this guide is about finding.
Step 1: Describe the bug precisely
Vague reports get vague fixes. Before involving the agent again, write down four things:
- What you did: the exact steps. "Logged in as a new user, clicked 'Create project', typed a name, pressed Save."
- What you expected: "The project appears in the list."
- What actually happened: "The button spins forever. Nothing appears. No error on screen."
- When it started: "It worked yesterday. Since then I added the team-invite feature."
That last line is gold. Most bugs in AI-built apps appear right after a change, and knowing which change narrows the search enormously.
Step 2: Collect the real error messages
The error the user sees ("Something went wrong") is almost never the real error. The real one is somewhere else, and you need to fetch it. There are three main places to look.
The browser console and network tab
Every modern browser has developer tools (press F12, or right-click and choose Inspect). MDN has a clear introduction to browser developer tools. Two tabs matter most:
- Console: red error messages from your frontend code, with file names and line numbers.
- Network: every request your page makes. Reproduce the bug, then click the failed request (often shown in red, with a status like 400, 401, 403, 404 or 500) and read its response. A 500 means the server crashed; a 401 or 403 usually means an authentication or permission problem; a 404 means the URL is wrong or the route does not exist.
On a phone, these tools are harder to reach, so reproduce bugs on a computer where you can, using the browser's device emulation mode for mobile layouts.
Server logs
If your app has a backend (API routes, server functions, PHP files), its errors are written to server logs, not the browser. Where they live depends on your platform: the terminal where you ran the development server, the logs or functions section of your hosting dashboard, or an error log file on shared hosting. Find out where yours are before you need them.
Database and auth provider logs
Hosted databases and auth services usually have their own logs and dashboards. If a query returns nothing when it should return data, the cause is often an access rule (for example, row-level security in Supabase or Security Rules in Firebase) silently filtering rows out. Those logs will show it.
Step 3: Reproduce it reliably
A bug you can trigger every time is half solved. Find the shortest sequence of steps that causes it. Then check what changes it:
- Does it happen for every user or only new users? Only for one account?
- Only on mobile? Only in one browser? Only on the live site and not locally?
- Only with certain input, such as long text, an empty field, a Hindi name, or a file over a certain size?
"Only on the live site" points to configuration: a missing environment variable, a different database URL, a domain not added to an allowed list, or a build step. "Only for new users" points to missing data that older test accounts happen to have. These patterns tell you where to look before you read a single line of code.
Step 4: Give the agent evidence, not frustration
Now go back to the agent, in a fresh session, with a structured report. A template that works well:
Bug report. Do not change any code yet.
Steps: <exact steps>
Expected: <what should happen>
Actual: <what happens>
Started after: <recent change, if known>
Browser console error:
<paste the exact text>
Failed network request:
<method, URL, status code, response body>
Server log:
<paste the relevant lines>
Task: list the 3 most likely causes, ranked, and for each one tell me
how to confirm or rule it out. Point to the specific files and lines.
The key phrase is "do not change any code yet". You want a diagnosis first. Asking for ranked hypotheses with ways to test them turns the agent from a guesser into an investigator, and gives you a way to check its reasoning. Our prompt tips for coding agents cover more patterns like this.
Step 5: Test one hypothesis at a time
Pick the most likely cause and confirm it before fixing it. Useful ways to confirm:
- Add logging. Ask the agent to add temporary log lines that print the values at each step of the failing flow ("log the user ID, the query and the result"). Run it again and read the output. Logging is the most reliable debugging tool there is, and it works in any language.
- Check assumptions directly. Is the environment variable actually set on the server? Does the database row actually exist? Is the user actually logged in at that point? Look, do not assume.
- Simplify. Temporarily hard-code a value or skip a step to see whether the problem disappears. If it does, the problem is in what you removed.
Once a hypothesis is confirmed, ask for the smallest fix that addresses it: "Cause confirmed: the insert fails because the team_id column is required but the form does not send it. Make the smallest change that fixes this. Do not refactor anything else." Then test, and remove the temporary logging.
Step 6: Narrow down by halving
When you have no idea where the bug is, cut the search space in half repeatedly:
- In time: if it worked a week ago, test a commit from the middle of that week. Working? The bug came later. Broken? Earlier. Git can automate this with git bisect.
- In code: comment out or bypass half of a long function or half of the components on a page. Does the problem remain? It is in the other half.
- In data: if one big import fails, try half the rows, then half of that half.
Halving feels slow, but it is guaranteed to converge, unlike guessing.
Step 7: Explain it out loud
Programmers have a famous trick called rubber duck debugging: explain the code, line by line, to someone (or something) who knows nothing about it. Saying "and then this function gets the user, and then..." often reveals the step where your understanding and the code disagree. With AI tools you can turn this around: ask the agent to "explain step by step what happens in this flow, from the button click to the database and back, citing files". Read the explanation carefully. The bug is often hiding in a step that sounds wrong when described in plain words.
Common bug patterns in AI-generated apps
Certain problems come up again and again in apps built with AI tools. Check these early:
- Missing or wrong environment variables on the live server, especially after deploying. Local works, live fails.
- Access rules blocking queries. Database rules that return empty results instead of errors.
- Authentication timing. Code that runs before the logged-in user has loaded, so the user is briefly empty.
- Mismatched names. The frontend sends
userId, the backend expectsuser_id; or a column was renamed in one place only. - Duplicated logic. The agent created a second version of a function instead of updating the first, and you are editing the one that is not used.
- Outdated library usage. Models sometimes write code for an older version of a library. Check the library's current documentation, and tell the agent which version you use.
- Silent error handling. A
try/catchthat swallows the error and shows nothing. Ask the agent to log every caught error during debugging. - Hallucinated APIs. A function or option that does not exist in the library at all. If you cannot find it in the official docs, it probably is not real.
Prevent the next bug
Debugging gets much easier with a few habits:
- Commit after every working step, so you always have a known good state to compare against.
- Make one change at a time and test it before asking for the next.
- Ask for tests for important flows, especially login, payments and anything involving permissions.
- Keep a project brief so the agent knows what the app is supposed to do. See how to write a project brief for AI coding agents.
- Keep error logging on in production (without logging passwords or tokens), so live bugs leave evidence. The vibe coding security checklist covers what not to log.
When to get human help
Some problems are worth taking to people: payment or security issues on a live app with real users, data loss, or a bug you have spent hours on with no progress. Official documentation, a framework's community forum or Discord, and Q&A sites are good places to ask. Bring the same structured report from Step 4. It gets far better answers than "my app is broken", from humans and AI alike.
FAQ
Why does my AI agent keep saying it fixed the bug when it did not?
Because without error messages or test results, it can only predict a plausible fix, not verify one. Give it real evidence (console errors, network responses, server logs) and ask it to explain how to confirm the fix before you accept it.
Should I switch to a different AI model when one gets stuck?
Sometimes a different model helps, but a fresh session with a precise bug report usually helps more. Changing models while keeping a vague description often just produces a different wrong guess.
Do I need to understand the code to debug it?
Less than you might think. Collecting errors, reproducing the bug, checking environment variables and testing one change at a time do not require reading every line. Over time, debugging is also the fastest way to learn how your code actually works.
Is it safe to paste error logs into an AI tool?
Usually, but remove secrets first. Logs can contain API keys, tokens, email addresses or other personal data. Replace them with placeholders like <API_KEY> before pasting.