Skip to content

fix(runtime): coalesce consecutive same-role Anthropic messages before dispatch - #5360

Merged
BenTaylorDev merged 2 commits into
CopilotKit:mainfrom
rodboev:fix/2910-coalesce-anthropic-same-role
Jul 25, 2026
Merged

BenTaylorDev merged 2 commits into
CopilotKit:mainfrom
rodboev:fix/2910-coalesce-anthropic-same-role

Conversation

@rodboev

@rodboev rodboev commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In multi-turn conversations using the Anthropic adapter, a model turn that contains both assistant text and a tool call can be replayed as two consecutive {role: "assistant"} entries in the Anthropic payload. Anthropic expects one message object per turn with alternating roles, so that split payload can blur turn boundaries on the next request. This PR coalesces same-role Anthropic messages before dispatch so one assistant turn stays one assistant message.

Root cause

convertMessageToAnthropicMessage
maps each CopilotKit message independently. A mixed assistant turn, a TextMessage(role=assistant) followed by an ActionExecutionMessage, therefore becomes two separate assistant entries. The Anthropic Messages API requires all content blocks for one assistant turn to be sent in a single message object: https://docs.anthropic.com/en/api/messages

AnthropicAdapter.process()
already deduplicates tool_result blocks on the user side, but it previously forwarded the mapped assistant-side payload without a coalescing pass. Rebasing onto current main also exposed test-fixture drift in the two new regression tests, so the final branch updates those fixtures to the current object-form TextMessage constructor and removes one stale ActionInput field while keeping the production fix unchanged.

Changes

  • packages/runtime/src/service-adapters/anthropic/utils.ts: add
    coalesceConsecutiveSameRoleMessages(messages) to merge adjacent equal-role
    Anthropic messages by concatenating their content arrays.
  • packages/runtime/src/service-adapters/anthropic/anthropic-adapter.ts: call
    coalesceConsecutiveSameRoleMessages before limitMessagesToTokenCount.
  • packages/runtime/tests/service-adapters/anthropic/anthropic-adapter.test.ts:
    add same-role regression coverage, align the new fixtures with the current
    object-form TextMessage constructor, and remove the stale parameters field
    from the action fixture.
  • .changeset/coalesce-anthropic-same-role-messages.md: patch changeset for
    @copilotkit/runtime.

Scope

The tool_result allowlist deduplication stays unchanged. Token trimming and the orphan-removal post-processor still run after coalescing, so tool_use and tool_result pairing remains intact. The OpenAI, Google, LangChain, and Groq adapters are unaffected.

The reported regression and the explicit regression coverage are assistant-side. The coalescing helper itself is role-agnostic for adjacent equal-role array content, but this PR does not add a separate user-side regression case.

Related PRs and Issues

Prior attempted fix: #2864, which addressed unrelated message callbacks rather than the adapter payload.

Test plan

  • pnpm -C packages/runtime exec vitest run tests/service-adapters/anthropic/anthropic-adapter.test.ts
    10/10 tests pass, including the two same-role coalescing cases.
  • pnpm -C packages/runtime exec vitest run tests/service-adapters/anthropic/utils-token-trimming.test.ts
    9/9 tests pass.
  • CI green (static / quality, test / unit on Node 20/22/24)

Upstream

Closes #2910.
Reported by @alonronin.

@vercel

vercel Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
docs Ready Ready Preview, Comment Jun 10, 2026 8:06pm

Request Review

@vercel

vercel Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

@rodboev is attempting to deploy a commit to the CopilotKit Team on Vercel.

A member of the Team first needs to authorize it.

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. Verified against current main: the Anthropic adapter still sends consecutive same-role messages (anthropic-adapter.ts still carries the "we skip grouping by role" note), which breaks Anthropic's alternating-role requirement — the reported #2910 case (assistant text preamble + assistant tool_use → two consecutive assistant messages). The fix coalesces correctly: convertMessageToAnthropicMessage always returns array content, so the merge guard holds; tool_use (assistant) and tool_result (user) are never merged across roles; and it's scoped to Anthropic only (coalesceConsecutiveSameRoleMessages is called nowhere but anthropic-adapter.ts:334), so no cross-provider regression. Tests assert the real outgoing payload.

I bless the code with a glad heart.

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Following up on my approval — running the Anthropic adapter suite locally against current main, the two new same-role-coalescing tests fail, so the PR doesn't pass its own suite as merged. Converting to request-changes.

Both fail with the captured Anthropic messages coming back empty:

  • merges TextMessage(assistant) + ActionExecutionMessage into a single Anthropic assistant message → expected [] to have a length of 1
  • does not merge alternating user/assistant messages (no regression) → expected [] to have a length of 3

The 8 pre-existing anthropic tests pass, and the coalesce call is correctly wired (anthropic-adapter.ts:334), so this looks like the two new tests' setup/capture needs reconciling with the current process() flow rather than a problem with the coalescing logic itself. Could you rebase onto current main and confirm the two coalescing tests go green? The fix's approach is sound (Anthropic-scoped, array-content guard holds) — it just needs its own tests passing against current main before merge. Sorry for the back-and-forth.

@rodboev
rodboev force-pushed the fix/2910-coalesce-anthropic-same-role branch from f3bbed5 to 005aebb Compare July 24, 2026 23:06
@rodboev

rodboev commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for catching this. The rebase exposed test-fixture drift from current main, while the Anthropic coalescing path itself remained sound.

  1. In packages/runtime/tests/service-adapters/anthropic/anthropic-adapter.test.ts, I updated both same-role test fixtures to use the current object-form TextMessage constructor with Role, and removed the obsolete parameters field from the action fixture.
  2. I left the production call in packages/runtime/src/service-adapters/anthropic/anthropic-adapter.ts and the array-guarded merge in packages/runtime/src/service-adapters/anthropic/utils.ts unchanged.
  3. The rebased Anthropic adapter test file now passes all 10 tests, including the text plus tool_use merge and alternating-role non-regression cases.

@pkg-pr-new

pkg-pr-new Bot commented Jul 25, 2026

Copy link
Copy Markdown

Open in StackBlitz

@copilotkit/a2ui-renderer

pnpm add https://pkg.pr.new/@copilotkit/a2ui-renderer@5360

@copilotkit/agentcore-runner

pnpm add https://pkg.pr.new/@copilotkit/agentcore-runner@5360

@copilotkit/angular

pnpm add https://pkg.pr.new/@copilotkit/angular@5360

@copilotkit/channels

pnpm add https://pkg.pr.new/@copilotkit/channels@5360

@copilotkit/channels-core

pnpm add https://pkg.pr.new/@copilotkit/channels-core@5360

@copilotkit/channels-discord

pnpm add https://pkg.pr.new/@copilotkit/channels-discord@5360

@copilotkit/channels-intelligence

pnpm add https://pkg.pr.new/@copilotkit/channels-intelligence@5360

@copilotkit/channels-slack

pnpm add https://pkg.pr.new/@copilotkit/channels-slack@5360

@copilotkit/channels-teams

pnpm add https://pkg.pr.new/@copilotkit/channels-teams@5360

@copilotkit/channels-telegram

pnpm add https://pkg.pr.new/@copilotkit/channels-telegram@5360

@copilotkit/channels-ui

pnpm add https://pkg.pr.new/@copilotkit/channels-ui@5360

@copilotkit/channels-whatsapp

pnpm add https://pkg.pr.new/@copilotkit/channels-whatsapp@5360

@copilotkit/core

pnpm add https://pkg.pr.new/@copilotkit/core@5360

@copilotkit/react-core

pnpm add https://pkg.pr.new/@copilotkit/react-core@5360

@copilotkit/react-native

pnpm add https://pkg.pr.new/@copilotkit/react-native@5360

@copilotkit/react-textarea

pnpm add https://pkg.pr.new/@copilotkit/react-textarea@5360

@copilotkit/react-ui

pnpm add https://pkg.pr.new/@copilotkit/react-ui@5360

@copilotkit/runtime

pnpm add https://pkg.pr.new/@copilotkit/runtime@5360

@copilotkit/runtime-client-gql

pnpm add https://pkg.pr.new/@copilotkit/runtime-client-gql@5360

@copilotkit/sdk-js

pnpm add https://pkg.pr.new/@copilotkit/sdk-js@5360

@copilotkit/shared

pnpm add https://pkg.pr.new/@copilotkit/shared@5360

@copilotkit/sqlite-runner

pnpm add https://pkg.pr.new/@copilotkit/sqlite-runner@5360

@copilotkit/voice

pnpm add https://pkg.pr.new/@copilotkit/voice@5360

@copilotkit/vue

pnpm add https://pkg.pr.new/@copilotkit/vue@5360

@copilotkit/web-components

pnpm add https://pkg.pr.new/@copilotkit/web-components@5360

@copilotkit/web-inspector

pnpm add https://pkg.pr.new/@copilotkit/web-inspector@5360

commit: 005aebb

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-approving — the two coalescing tests pass now. Verified on the updated branch against current main: Anthropic adapter suite 10/10, lint 0 errors, no type errors in the changed files, and CI is green. The coalescing is correct and Anthropic-scoped; the fixtures now align with the current message types.

I bless the code with a glad heart.

@BenTaylorDev
BenTaylorDev merged commit 8806f66 into CopilotKit:main Jul 25, 2026
36 checks passed
BenTaylorDev added a commit that referenced this pull request Aug 6, 2026
## What does this PR do?

Community PRs keep arriving with `.changeset/*.md` files even though the
repo migrated off Changesets to conventional-commit-driven releases.
`.changeset/` has now been deleted from `main` twice (`5afa55f067` on
2026-06-16, `1e5ba689e0` on 2026-07-29) and **five open PRs carry
changeset files today** (#6287, #6289, #6290, #6292, #6346).

Three mechanisms keep feeding it:

1. **Stale forks.** `rodboev/CopilotKit`'s default branch still contains
10 of the pre-cleanup `.changeset/*.md` debris files. Three of the five
open PRs come from that fork — the contributor's agent opens the repo,
sees a directory full of changesets, and adds one more. (No
`config.json`, and `@changesets/cli` isn't installed anywhere, so these
are hand-written by agents, not CLI output.)
2. **Merging stale PRs re-seeds `main`.** The two files Tyler removed in
`1e5ba689e0` arrived via 2026-06-10-authored branches (#2910, #5360)
merged on 2026-07-25 — they sat on `main` for four days, and anyone who
forked in that window inherited the directory. His hunch in that commit
message was right.
3. **Convention inference, uncontradicted.** #6346 is from a branch in
this repo, where `.changeset/` does *not* exist, and it still has one.
The repo reads as a Changesets repo: pnpm workspace monorepo,
per-package `CHANGELOG.md` in Changesets' exact `### Patch Changes`
output format, `chore: release monorepo vX.Y.Z` release PRs. Nothing in
`CONTRIBUTING.md`, the PR template, `AGENTS.md`, `CLAUDE.md`, or
`.claude/docs/` said otherwise, so the guess was well-supported.

This PR closes all three off:

- **`CONTRIBUTING.md`** — new "Changelogs and releases — do not add a
changeset" section: we did use Changesets, `scripts/release/` now builds
changelogs from commit subjects, `.changeset/*.md` is inert, write a
good conventional commit subject instead, and leave versions/changelogs
to maintainers. Includes a note to rebase old forks.
- **`AGENTS.md` / `CLAUDE.md`** — the same rule as an Essentials bullet.
This is the highest-leverage change: the contributors doing this are
coding agents, and agents load these files automatically while mostly
not reading `CONTRIBUTING.md`.
- **`static / check binaries`** — fail the PR on added `.changeset/*`
files, so this stops depending on review catching it (which is what
failed in July and restarted the loop). Added to the existing
forbidden-files gate rather than a new workflow: it already runs on
every PR to `main`, is fork-safe (`contents: read`, no secrets), and has
exactly this `git diff --name-only origin/BASE...HEAD` + `VIOLATIONS`
shape. Filters on `--diff-filter=AM` so a PR that *deletes* stale
changesets still passes.
- **`.oxfmtrc.json`** — drop the ignore entry for
`.github/actions/changesets-action/src/run.ts`, a path that hasn't
existed for a long time. It was the last grep-visible "we use
changesets" signal in a root config file.

## Related PRs and Issues

- Follows up `1e5ba689e0` ("fix: remove all changesets"), whose commit
message asked for exactly this: a durable record of the decision that
future agents can find.
- Open PRs that would be caught by the new gate: #6287, #6289, #6290,
#6292, #6346.

## Testing

Docs + CI-config change, so verification focused on the guard.
`actionlint` was run on the workflow, then the step body was extracted
with `yq` and executed against real branches.

**Lint / parse:**
```
$ actionlint .github/workflows/static_check-binaries.yml
actionlint: clean
$ python3 -c "import json; json.load(open('.oxfmtrc.json'))"   # oxfmtrc still valid JSON
oxfmtrc JSON OK
```

**True positive** — real head of #6292, via `yq
'.jobs.check-binaries.steps[1].run'` piped to bash with `BASE_REF=main`:
```
::error::Changeset files detected in PR:
.changeset/enable-mcp-apps-tool-filters.md
This repo no longer uses Changesets — releases are driven by conventional commit subjects (see scripts/release/).
Nothing reads .changeset/*.md. Delete these files and describe the change in your commit subject instead.
See the 'Changelogs and releases' section of CONTRIBUTING.md.

This PR contains files that should not be committed (see the errors above).
Please remove them and update your .gitignore if needed.
exit=1
```

**True negative** — same script on this branch, which has five changed
files and no changesets:
```
$ git diff --name-only origin/main...HEAD
.github/workflows/static_check-binaries.yml
.oxfmtrc.json
AGENTS.md
CLAUDE.md
CONTRIBUTING.md
$ BASE_REF=main bash step.sh
No binary artifacts or oversized files detected.
exit=0
```

**Delete-safety** — a commit that *removes* changesets must not be
punished. Using the real cleanup commit (`8806f668d1...1e5ba68`):
```
unfiltered:                      with --diff-filter=AM (what the gate uses):
.changeset/coalesce-...md        (empty)
.changeset/fix-parallel-...md
```

Not verified locally: the gate firing in real GitHub Actions — that
needs this PR's own CI run (the `static / check binaries` check on this
PR exercises the true-negative path).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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.

🐛 Bug: When using Anthropic next assistant message is appended to previous one

2 participants