Skip to content

fix(ai): always end an agent turn with a reply to the user - #3060

Merged
2witstudios merged 3 commits into
masterfrom
pu/onfinish
Dec 1, 2026
Merged

2witstudios merged 3 commits into
masterfrom
pu/onfinish

Conversation

@2witstudios

Copy link
Copy Markdown
Owner

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:

stopWhen: [hasToolCall(FINISH_TOOL_NAME), …]
  • A reply had to arrive in the same step as finish, and there was no step after it.
  • The prompt asked for the summary "whenever finish is called", which had no step to land in.
  • The finish call is hidden in the UI (useGroupedParts.ts), so a silent finish showed the user nothing.
  • The classifier treated both tool-calls + finish and an empty stop as clean.

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) replaces hasToolCall(finish). It stops on finish only when that same step also wrote text.
    • forceReplyStep runs the step after a silent finish with toolChoice: 'none', so the model can only answer in text. The loop then ends by itself.
    • It uses toolChoice rather than activeTools: [], because Anthropic rejects tool-call history when no tools are declared.
    • Two silent finish calls in a row stop the loop instead of running to the step cap.
  • Wired into all six tool loops:

    • page chat and global chat (through the shared agentLoopPrepareStep)
    • consult
    • ask_agent
    • workflows and scheduled agents
    • v1 completions in server-only mode

    Each one keeps its capStepToolPayloads call.

  • run-agent-with-retry.ts: safety net for an empty stop. A model that stops after tool results with no text and no finish call ends the loop before any stop condition runs.

    • When a clean chat loop's last step has no text, the shell makes one text-only call, continuing from the loop's own messages. Empty assistant messages are dropped first.
    • The reply lands in the same message envelope, and its steps and usage are added to the turn's billing.
    • The shell never does this for aborts, pause tools such as ask_user, or terminal outcomes.
    • If that call is also empty, it logs agent turn ended without a reply to the user.
  • Prompt changes

    • The finish tool description now says to reply before or alongside finish. Agents with a custom system prompt also see this, since they get no shared behavior prompt.
    • system-prompt.ts no longer asks for the summary after finish, 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.ts and docs/2.0-architecture/agent-sessions.md.

  • CHANGELOG entry under Unreleased.

Scope note: the empty-stop safety net applies only to the two chat turns (page agents and the global assistant). The silent-finish forced step applies to every loop.

PageSpace

  • Tasks: none. This was a direct bug-fix request from the owner, with no board task.
  • Plan: none in PageSpace. The plan is this description.
  • Prompt: none. The owner asked in-session.

Builder: ag-vrei76f0

Criteria

Criterion Code Test Evidence
Given finish with no text, should run a text-only step and stream its reply apps/web/src/lib/ai/core/final-reply.ts:49, :68 apps/web/src/lib/ai/core/__tests__/final-reply.test.ts:229 real ai@6 streamText + MockLanguageModelV3; toolChoice ['auto','auto','none']; 856953e
Given a reply written alongside finish, should stop with no extra call final-reply.ts:49 final-reply.test.ts:252 1 model call; 856953e
Given an empty stop after tools, should make one text-only call continuing from the tool results apps/web/src/lib/ai/core/run-agent-with-retry.ts:460 final-reply.test.ts:274, run-agent-with-retry.test.ts:203 856953e
Given two silent finish calls in a row, should stop rather than loop to the step cap final-reply.ts:49 final-reply.test.ts:64 856953e
Given an ask_user pause or an abort, should not force a reply run-agent-with-retry.ts:460 run-agent-with-retry.test.ts:241, :259 856953e
Given the forced call is also empty, should report it and warn run-agent-with-retry.ts run-agent-with-retry.test.ts:271 856953e
Every multi-step tool loop still caps its tool payloads all six call sites tool-payload-cap-callsites.guard.test.ts passes; 856953e
Real Gemini or OpenAI turn ends with a visible reply n/a n/a NOT RUN — needs bun run dev with live provider keys

Verification (at 856953e)

  • bun run typecheck in apps/web (with NODE_OPTIONS=--max-old-space-size=16384; the default heap runs out of memory): pass.
  • eslint on every changed file: pass.
  • vitest run on these files: 58/58 pass:
    • final-reply
    • run-agent-with-retry
    • run-agent-with-retry-abort
    • turn-duplication-ratchet
    • tool-payload-cap-callsites.guard
    • env-approval-tools
    • consult/step-cap-parity
  • vitest run on src/lib/ai, src/app/api/ai, src/app/api/v1, src/lib/workflows, src/app/api/ai/chat: every unit test passes.
    • The only failures are *.integration and *.security tests that need a provisioned Postgres (role "test" does not exist).
  • NOT RUN: the Postgres integration suites, including imago-global-parity.integration (the full-turn test). The shared test DB on :5433 is behind this branch's migrations (missing model_key_managed_conversations), and I did not migrate a database that other sessions share. CI's bun run test provisions its own.
  • NOT RUN: a manual test with live models.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QyQdJ2GvFyjsanGXdxhvW6

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
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: be3ab2ed-3517-43f1-8c45-2e08ae405168
Commits

Reviewing files that changed from the base of the PR and between 5ef5e60 and eb4a701.

Files selected for processing: 17

  • CHANGELOG.md
  • apps/web/src/app/api/ai/page-agents/consult/route.ts
  • apps/web/src/app/api/v1/chat/completions/route.ts
  • apps/web/src/lib/ai/chat-pipeline/__tests__/turn-duplication-ratchet.test.ts
  • apps/web/src/lib/ai/chat-pipeline/global-chat-turn.ts
  • apps/web/src/lib/ai/chat-pipeline/handle-chat-turn.ts
  • apps/web/src/lib/ai/chat-pipeline/page-chat-turn.ts
  • apps/web/src/lib/ai/core/__tests__/final-reply.test.ts
  • apps/web/src/lib/ai/core/__tests__/run-agent-with-retry.test.ts
  • apps/web/src/lib/ai/core/context-assembly.ts
  • apps/web/src/lib/ai/core/final-reply.ts
  • apps/web/src/lib/ai/core/run-agent-with-retry.ts
  • apps/web/src/lib/ai/core/system-prompt.ts
  • apps/web/src/lib/ai/tools/agent-communication-tools.ts
  • apps/web/src/lib/ai/tools/finish-tool.ts
  • apps/web/src/lib/workflows/workflow-executor.ts
  • docs/2.0-architecture/agent-sessions.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T22:03:47.094695Z 856953e PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +475 to +479
} 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,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

2witstudios and others added 2 commits November 30, 2026 16:32
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
@2witstudios
2witstudios merged commit b153e14 into master Dec 1, 2026
17 checks passed
@2witstudios
2witstudios deleted the pu/onfinish branch December 1, 2026 02:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant