Skip to content

fix(react-core): rerender activity messages after ACTIVITY_DELTA - #6295

Closed
rodboev wants to merge 1 commit into
CopilotKit:mainfrom
rodboev:fix/6001-activity-delta-rerender
Closed

rodboev wants to merge 1 commit into
CopilotKit:mainfrom
rodboev:fix/6001-activity-delta-rerender

Conversation

@rodboev

@rodboev rodboev commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This fixes stale A2UI activity content in CopilotChat when ACTIVITY_DELTA updates an existing activity object without changing its message ID.

The CopilotChat message memo key now hashes object content and includes the activity type, so a retained-ID delta produces a new key and the memoized boundary re-renders. Existing string, array, role, message-ID, and tool-call grouping behavior stays intact. A2UI event handling and backend protocol behavior remain unchanged.

Fixes #6001

Changes

  • Hash object content and include activityType in the CopilotChat message memo key so a retained-ID ACTIVITY_DELTA invalidates the memoized messages array.
  • getContentMemoKey returns a deterministic hash for serializable object content, a stable value for immutable primitives, and a fail-safe fresh value for unsupported or cyclic content, so the memo can always invalidate.
  • Add end-to-end regressions for the retained-ID ACTIVITY_DELTA sequence, the retained activity-type switch, and unchanged-serializable-content memoization.
  • Preserve existing text, array, and tool-call memoization behavior.
  • Follow the current release.config.json and Nx release convention; no Changeset is included.

Test Plan

  • pnpm -C packages/react-core exec vitest run src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx
  • pnpm exec oxfmt --check packages/react-core/src/v2/components/chat/CopilotChat.tsx packages/react-core/src/v2/components/chat/content-memo-key.ts packages/react-core/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx
  • pnpm exec oxlint packages/react-core/src/v2/components/chat/CopilotChat.tsx packages/react-core/src/v2/components/chat/content-memo-key.ts packages/react-core/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx
  • pnpm -C packages/react-core exec tsc --noEmit
  • pnpm exec commitlint --from origin/main --to HEAD
  • A retained-ID activity updates immediately after ACTIVITY_DELTA.
  • Existing string, array, and tool-call grouping tests remain green.
  • Release metadata remains aligned with release.config.json and Nx release; no Changeset is included.

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

Thanks for this — the bug is real and I reproduced it. I'd like to resolve one thing before it lands, because I think the fix is aimed at a mechanism that isn't the actual cause.

The premise

The comment in CopilotChat.tsx describes "retained message objects with in-place activity mutations." I scripted ACTIVITY_SNAPSHOT -> ACTIVITY_DELTA against the pinned @ag-ui/client 0.0.57, reading agent.messages at each onMessagesChanged:

#1 sameObject=true  sameContentRef=true  content={"step":1,"label":"starting"}
#2 sameObject=false sameContentRef=false content={"step":2,"label":"working"}

The client replaces both the message and its content with new objects. There's no in-place mutation to defend against.

What the actual cause is

messagesMemoKey computes:

const contentKey = typeof m.content === "string" ? m.content.length
  : Array.isArray(m.content) ? m.content.length : 0;

ActivityMessage.content is z.ZodRecord -> Record<string, any>, so it always takes the : 0 branch. The key is act-1:activity:0: before and after the delta — and activityType isn't in the key either. Two independent blind spots, which is why useMemo returns the stale array and the memoized child never sees new props.

So the two changes that actually fix this are the ones inside messagesMemoKey: hash object content, and add activityType. Once new message objects reach the child, the existing JSON.stringify(content) comparator already detects the change on its own.

That would let the messagesRevisionRef subscription, the WeakMap cache, refreshContentKeys, the CONTENT_MEMO_KEY symbol, the defineProperty stamping, and the per-render shallow copies all come out. I'd much rather carry the smaller version.

Two issues worth fixing either way

  1. getContentMemoKey returns a constant 0 on its catch path. A nested Date, Map, Set, or class instance anywhere in the payload throws Unsupported content object, yields 0 on every render, and leaves the memo permanently unable to invalidate — the same symptom this PR fixes, for that class of payload. (Current main has the same blind spot, so this isn't a regression — but the fallback asserts equality, which is the unsafe default. Returning a monotonic counter would fail safe.)

  2. Render-phase ref mutation. previousMessagesRef.current and previousMessagesRevisionRef.current are assigned during render rather than in an effect. A render React discards (concurrent interrupt, StrictMode double-invoke) still advances them, so a later render can see "unchanged" and reuse a stale cached key.

One thing I checked that's fine

Stamping new message identities doesn't regress the other memoized rows — the comparators at CopilotChatMessageView.tsx:94, :172, :246, and :300 compare message.content by reference, which a shallow {...message} copy preserves.

Also: this shares CopilotChat.tsx with #6291, so whichever lands second will need a rebase.

@rodboev
rodboev force-pushed the fix/6001-activity-delta-rerender branch from ea26358 to 7faafb4 Compare August 5, 2026 17:30
@rodboev

rodboev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Ben. That diagnosis is right and I've confirmed it against the pinned client: ACTIVITY_SNAPSHOT -> ACTIVITY_DELTA replaces both the message and its content with new objects, so there is no in-place mutation to defend against. The real blind spot was messagesMemoKey: every object content collapsed to the : 0 branch and activityType wasn't in the key, so the digest was identical before and after the delta and useMemo never re-emitted.

I've shrunk the fix to where you pointed:

  1. messagesMemoKey now hashes object content via getContentMemoKey and includes activityType in the key, so a retained-ID delta produces a new digest and the memoized boundary re-renders.
  2. Removed the extra mechanism: the messagesRevisionRef subscription, the WeakMap key cache, refreshContentKeys, the CONTENT_MEMO_KEY symbol, the defineProperty stamping, and the per-render shallow copies are all gone. messages is a plain [...agent.messages] again.
  3. getContentMemoKey's catch path now returns a monotonic counter instead of a constant 0, so a payload with a nested Date/Map/Set/class instance fails safe (re-renders) rather than permanently freezing memoization.
  4. Dropped the contentMemoKey prop plumbing and the try/catch wrapper in CopilotChatMessageView; the retained-ID delta now reaches the existing JSON.stringify(content) comparator on its own.

The retained-ID ACTIVITY_DELTA regression, the activityType retention case, and the unchanged-serializable-content memoization case are kept; tests that only exercised the removed mechanism are gone.

Also noting we both touch CopilotChat.tsx (via #6291) since you flagged it; the branch is rebased against current main and will resolve cleanly on whichever lands second.

@BenTaylorDev

Copy link
Copy Markdown
Contributor

Closing this as superseded, and I want to be clear that's about timing rather than the work.

Your second push was exactly the shrink I asked for, and the diagnosis behind it was right. What happened is that #6325 landed after your last push here and fixed the same blind spot on main:

: m.content && typeof m.content === "object"
  ? JSON.stringify(m.content)
  : 0;

I ran your reproduction test — should re-render retained activity content after an ACTIVITY_DELTA — against current main unmodified, and it passes. That's the scenario from #6001, so the headline fix here is already in place, and this branch now conflicts with main on exactly those lines.

On the rest of the diff: I'd rather not carry content-memo-key.ts, for two reasons I measured rather than guessed.

hashStableContent has no case for undefined, so a nested undefined property throws and falls to the counter. That means content: { status: "x", detail: undefined } produces a fresh key on every render, useMemo re-emits, and the message-list memo boundary busts on every parent render — including every keystroke in the input. Your own memoization test with that content gives expected 6 to be 3; on main it passes, because JSON.stringify drops undefined properties. Same story for Date, Map, Set, and class instances, all of which JSON.stringify handles. So the monotonic counter is the right last resort, but it needs JSON.stringify in front of it rather than behind it. Separately, the per-character hash costs about 12× what it replaces, and it runs on every render: 13µs → 142µs on a 10 KB payload, 422µs → 5118µs on a 410 KB one.

There is one part of this PR that is still a real fix. Adding activityType to the key closes a gap main still has. My first read was that it only mattered for an ACTIVITY_DELTA whose activityType diverges from its snapshot, which the protocol doesn't really sanction — ACTIVITY_DELTA.activityType is documented as mirroring the most recent snapshot. But ACTIVITY_SNAPSHOT carries a required activityType alongside required content, and that path is legitimate. Two snapshots with the same message ID and byte-identical content but different types:

agent.emit(activitySnapshotEvent({ messageId: id, activityType: "progress", content }));
agent.emit(activitySnapshotEvent({ messageId: id, activityType: "complete", content: { ...content } }));

× expected 'progress:Same content' to be 'complete:Same content'

The old renderer stays on screen. Your one-liner fixes it.

Thanks for the digging on this one — the contentKey = 0 diagnosis was the useful part.

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.

CopilotChat keeps stale A2UI activity content after ACTIVITY_DELTA from a userAction run

2 participants