Guides · Updated October 25, 2026
GitHub Copilot agent mode stuck in a loop: how to stop it and keep it from repeating
Copilot’s agent edits a file, runs the tests, gets the same failure, and edits the file again. Or it keeps rewriting one function back and forth. After a couple of dozen steps VS Code stops and asks whether you want it to keep going. This guide covers how to stop the loop, undo what it did, restart so it doesn’t walk straight back in, which settings bound it, and how to make the agent refuse an identical repeat with a hook.
Signs the agent is looping, not iterating
- Same command, same output. The terminal tool runs
npm testthree times and the failure is identical each time. - Edit ping-pong. The agent changes a line, then changes it back a few steps later, then changes it again.
- The “continue?” prompt. The agent hit its request limit for this turn (below) and the task still isn’t done.
- “I see the issue now.” Followed by the fix it already tried.
Edit, test, a different result, edit again: that’s normal work. It’s a loop when nothing changes between attempts, so the next attempt can’t turn out differently.
Stop it now
- Click Stop in the Chat view (the stop button replaces Send while the agent works).
- At the “continue?” prompt, don’t just click Continue. If the last steps were the same command and the same error, continuing buys more of the same. Stop and give it a new fact instead.
- Read the last few tool calls first. If the same command failed the same way three times, the agent needs something it doesn’t have: the full error, a file it hasn’t opened, or a decision from you. Another attempt won’t supply it.
Undo what the loop changed
VS Code takes a checkpoint before each chat request (chat.checkpoints.enabled, on by default). Hover over an earlier request and choose Restore Checkpoint. That restores the files the agent changed and removes the later requests from the conversation, which is what you want after a loop: the failed attempts are gone from the context too. Redo brings them back if you went too far.
- Terminal commands aren’t undone. Installs, migrations, files written by scripts and anything sent over the network stay. Check
git statusand clean up with git. - Checkpoints are temporary. Commit or stash before a long debugging task so you have a point to return to that doesn’t depend on the chat.
- Edit the request instead. Editing an earlier prompt reverts that request’s changes and everything after, then resends your new wording. Handy when the original instruction is what sent it in circles.
Restart without walking back into it
- Ask for a handoff note before you stop: “In five lines: the goal, what you tried, the exact failing output, your best hypothesis.” Then start a new chat session with that note. A fresh, short chat also uses far less context per step.
- Paste the real error. Loops often start because the agent read a truncated tail of the output. Copy the whole failing block.
- Forbid the rerun. “Don’t run the tests again until you have changed the code and can explain why the change fixes this failure.”
- Narrow the scope. Attach only the files that matter with
#file, and say which files it may edit. Ping-pong between two files stops when one is off limits. - Switch models deliberately. A different model sometimes spots what the first keeps missing. Check the model’s premium-request multiplier before you do.
The settings that bound a loop
chat.agent.maxRequests(default25): the most requests the agent makes in one turn before VS Code asks whether to continue. Lower it if you’d rather be asked sooner; raising it lets a loop run longer unattended.- Terminal auto-approve. If you’ve auto-approved terminal commands, the agent can rerun them without asking. Keep test and build commands on manual approval while you’re debugging something stubborn, and you’ll see each repeat before it runs.
github.copilot.chat.agent.autoFix(default on): the agent automatically tries to fix problems in the code it just generated. Usually helpful; worth knowing about when you see unrequested follow-up edits.
What a loop costs on Copilot
Copilot bills premium requests, not tokens. In agent mode, each prompt you send counts as one premium request multiplied by the model’s rate; the tool calls the agent makes on its own don’t add requests. So a loop inside one turn mostly costs time, but each “try again” you type, on a model with a high multiplier, eats into your allowance, and after that into paid usage.
To cap the money side, open github.com/settings/billing → Budgets and alerts, create a budget for Copilot premium requests (or a bundled premium requests budget), and tick Stop usage when budget limit is reached. Without that box ticked, a budget only sends emails. For organizations, the “Premium request paid usage” policy decides whether users can go past their allowance at all.
Why “stop after 3 tries” in your instructions doesn’t hold
A line in .github/copilot-instructions.md is context, not enforcement. In a long chat the model loses count, and it won’t notice that npm test and npx vitest run on the same file are the same attempt. A limit you can rely on has to run outside the model, on every tool call, and be able to refuse one. Copilot has that: agent hooks (in preview).
Make Copilot refuse an identical repeat with a hook
In the Copilot harness, a preToolUse hook receives the tool name and arguments as JSON on stdin and can answer {"permissionDecision": "deny"} with a reason the agent reads. Hooks load from .github/hooks/*.json in the repository or ~/.copilot/hooks/ for all your projects. Here’s a minimal repeat guard. Create .github/hooks/repeat-guard.json:
{
"version": 1,
"hooks": {
"preToolUse": [
{ "type": "command", "command": "node .github/hooks/repeat-guard.cjs", "timeoutSec": 10 }
]
}
}and .github/hooks/repeat-guard.cjs (needs Node.js):
// Deny the 4th identical tool call within 10 minutes in the same session.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const crypto = require('node:crypto');
const MAX = 3, WINDOW_MS = 10 * 60 * 1000;
const ev = JSON.parse(fs.readFileSync(0, 'utf8'));
const key = crypto.createHash('sha1')
.update(String(ev.toolName) + JSON.stringify(ev.toolArgs ?? null)).digest('hex');
const file = path.join(os.tmpdir(), 'copilot-repeat-' + String(ev.sessionId || 'x').replace(/\W/g, '') + '.json');
let seen = {};
try { seen = JSON.parse(fs.readFileSync(file, 'utf8')); } catch {}
const now = Date.now();
const hits = (seen[key] || []).filter(t => now - t < WINDOW_MS);
if (hits.length >= MAX) {
process.stdout.write(JSON.stringify({
permissionDecision: 'deny',
permissionDecisionReason: 'Same tool call ' + hits.length + ' times in 10 minutes with no change. ' +
'Stop rerunning it. Summarize the goal, what you tried and the exact error, then fix the root cause.',
}));
} else {
seen[key] = [...hits, now];
fs.writeFileSync(file, JSON.stringify(seen));
process.stdout.write('{}');
}Start a new Copilot session so it picks up the hook, and test it on something harmless first. Things to know:
- It counts exact repeats only.
npm testandnpm test 2>&1 | tail -40look different to it, and a legitimate test → fix → test cycle with the same command will trip it after three runs. A better guard also checks whether files or the output changed between calls. - Failure behavior matters. GitHub documents that a
preToolUsecommand that errors denies the tool call, while a timeout falls through to normal permissions. Keep the script fast and test it with a sample event. - Hooks run as code on your machine. Review any hook before you enable it, especially ones that come with a repository.
Where LoopGuard fits
LoopGuard is an open-source CLI that does this properly for Claude Code, Codex CLI and Cursor: it only counts repeats when nothing changed (it fingerprints the git working tree and each tool’s output), treats reworded commands as the same call, and adds per-session and daily dollar caps. It doesn’t install into Copilot yet, so for Copilot use the settings, budget and hook above. If you also run one of those agents, see how to stop runaway agent loops or Cursor agent stuck in a loop.
Related
- How to stop runaway Claude Code, Codex and Cursor agent loops
- How to track AI coding agent token costs per session
- How to set a spending limit for Claude Code
- How to limit Cursor agent usage costs
- How to cap OpenAI Codex CLI spend
- Claude Code usage limit reached: why it happens and how to monitor it
- How to set a hard budget for AI coding agents in CI
- Claude Code stuck in a loop: how to break it and stop it repeating the same command
- Codex usage limit reached: 5-hour and weekly limits explained
- Cursor agent stuck in a loop: how to stop it, roll back, and keep it from repeating
- Why Claude Code uses so many tokens, and how to use fewer
- How to set a budget limit for Aider
- Cline stuck in a loop: how to stop it, roll back, and cap what it spends
- Gemini CLI usage limits: daily quotas, the June 2026 change, and keeping costs in check
- Codex stuck in a loop: how to stop it, undo it, and keep it from repeating