Repository navigation
fix(ai): always end an agent turn with a reply to the user - #3060
Conversation
Every tool loop stopped as soon as the model called `finish`. The finish call is hidden in the UI, so a model that ran tools and then called `finish` without writing anything (common with Gemini and OpenAI models) left the user with a silent turn. The prompt also asked for the summary after finish, when no step was left to send it. - final-reply.ts: `finishWithReply` stops on finish only when that step also wrote text. A silent finish gets one more step with `toolChoice: 'none'` (`forceReplyStep`), so the model can only answer in text. Wired into all six tool loops. - run-agent-with-retry: when a clean chat loop's last step wrote no text (an empty `stop` after tools), make one text-only call that continues from the loop, in the same message envelope and billing. - finish tool description and system prompt: reply before or with finish. - turn-duplication ratchet 155 -> 156 for the shared module's import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QyQdJ2GvFyjsanGXdxhvW6
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 5 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 856953e7f6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else if (!replied) { | ||
| logger.warn('runAgentWithRetry: agent turn ended without a reply to the user', { | ||
| finishReason: replyCall.finishReason, | ||
| error: replyCall.caughtError instanceof Error ? replyCall.caughtError.message : undefined, | ||
| }); |
There was a problem hiding this comment.
Surface provider failures from the final-reply call
If the text-only final-reply call fails, its error is suppressed by runCall, but this branch leaves finalOutcome as clean and never sets terminalReason. Consequently, the error-emission block below is skipped and the client receives a normal finish with neither a reply nor an error. This also hides failures that truncate a partially streamed final reply. A mocked empty-stop followed by a provider-error response reproduces this: the emitted chunks contain only start and finish. Classify the continuation's failure and propagate a terminal error instead of treating it as successful completion.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b466b2. A failed or dropped final-reply call (thrown error or finishReason: 'error') now ends the run terminal / provider-error, so the existing error chunk is written instead of a silent finish. Covered by two new cases in run-agent-with-retry.test.ts: a pre-content provider failure on the reply call, and a reply that streams text and then drops.
If the text-only final-reply call failed, runCall suppressed its error and the turn stayed `clean`, so the client got a finish with neither a reply nor an error. Treat it as the after-content provider-error terminal it is, so the existing error chunk is written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QyQdJ2GvFyjsanGXdxhvW6
# Conflicts: # CHANGELOG.md
Problem
Models, most often Gemini and OpenAI, routinely ended a turn after tool calls without writing anything to the user. The chat showed only tool activity.
Root cause: every tool loop stopped as soon as the model called
finish:finish, and there was no step after it.finishcall is hidden in the UI (useGroupedParts.ts), so a silentfinishshowed the user nothing.tool-calls + finishand an emptystopasclean.Fix
The server now guarantees the closing reply; it no longer relies on the prompt.
lib/ai/core/final-reply.ts(new, pure)finishWithReply(finish)replaceshasToolCall(finish). It stops onfinishonly when that same step also wrote text.forceReplyStepruns the step after a silentfinishwithtoolChoice: 'none', so the model can only answer in text. The loop then ends by itself.toolChoicerather thanactiveTools: [], because Anthropic rejects tool-call history when no tools are declared.finishcalls in a row stop the loop instead of running to the step cap.Wired into all six tool loops:
agentLoopPrepareStep)ask_agentEach one keeps its
capStepToolPayloadscall.run-agent-with-retry.ts: safety net for an emptystop. A model that stops after tool results with no text and nofinishcall ends the loop before any stop condition runs.ask_user, or terminal outcomes.agent turn ended without a reply to the user.Prompt changes
finishtool description now says to reply before or alongsidefinish. Agents with a custom system prompt also see this, since they get no shared behavior prompt.system-prompt.tsno longer asks for the summary afterfinish, and clarifies that the closing summary is not a "postamble".Turn-duplication ratchet: 155 → 156. The one new identical line is the shared module's import. The rationale is recorded in the test,
handle-chat-turn.tsanddocs/2.0-architecture/agent-sessions.md.CHANGELOG entry under Unreleased.
Scope note: the empty-
stopsafety net applies only to the two chat turns (page agents and the global assistant). The silent-finishforced step applies to every loop.PageSpace
Builder: ag-vrei76f0
Criteria
finishwith no text, should run a text-only step and stream its replyapps/web/src/lib/ai/core/final-reply.ts:49,:68apps/web/src/lib/ai/core/__tests__/final-reply.test.ts:229streamText+MockLanguageModelV3; toolChoice['auto','auto','none']; 856953efinish, should stop with no extra callfinal-reply.ts:49final-reply.test.ts:252stopafter tools, should make one text-only call continuing from the tool resultsapps/web/src/lib/ai/core/run-agent-with-retry.ts:460final-reply.test.ts:274,run-agent-with-retry.test.ts:203finishcalls in a row, should stop rather than loop to the step capfinal-reply.ts:49final-reply.test.ts:64ask_userpause or an abort, should not force a replyrun-agent-with-retry.ts:460run-agent-with-retry.test.ts:241,:259run-agent-with-retry.tsrun-agent-with-retry.test.ts:271tool-payload-cap-callsites.guard.test.tsbun run devwith live provider keysVerification (at 856953e)
bun run typecheckinapps/web(withNODE_OPTIONS=--max-old-space-size=16384; the default heap runs out of memory): pass.eslinton every changed file: pass.vitest runon these files: 58/58 pass:final-replyrun-agent-with-retryrun-agent-with-retry-abortturn-duplication-ratchettool-payload-cap-callsites.guardenv-approval-toolsconsult/step-cap-parityvitest runonsrc/lib/ai,src/app/api/ai,src/app/api/v1,src/lib/workflows,src/app/api/ai/chat: every unit test passes.*.integrationand*.securitytests that need a provisioned Postgres (role "test" does not exist).imago-global-parity.integration(the full-turn test). The shared test DB on :5433 is behind this branch's migrations (missingmodel_key_managed_conversations), and I did not migrate a database that other sessions share. CI'sbun run testprovisions its own.🤖 Generated with Claude Code
https://claude.ai/code/session_01QyQdJ2GvFyjsanGXdxhvW6