fix(gateway): handle brackets in JSON strings - #1594
Conversation
The mightBeCompleteJson heuristic was incorrectly counting brackets and braces inside JSON string values, causing valid JSON to be marked as incomplete. This led to SSE events being concatenated together, resulting in JSON parse errors during streaming. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
WalkthroughUpdates the Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Pull request overview
This PR tightens the mightBeCompleteJson heuristic used in SSE parsing so that it no longer misclassifies valid JSON as incomplete when brackets or braces appear inside string values, and adds targeted unit tests around this behavior.
Changes:
- Updated
mightBeCompleteJsonto scan the JSON string character-by-character, tracking whether the cursor is inside a string and ignoring brackets/braces there, while handling escaped characters. - Added a dedicated
might-be-complete-json.spec.tstest suite with cases for simple structures, unbalanced input, escaped characters, and the real-world production failure scenario.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| apps/gateway/src/chat/tools/might-be-complete-json.ts | Refines the JSON completeness heuristic to skip bracket/brace counting inside string literals and to treat unterminated strings as incomplete. |
| apps/gateway/src/chat/tools/might-be-complete-json.spec.ts | Introduces comprehensive unit tests validating the heuristic across normal, edge, and production-derived JSON examples. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Summary
mightBeCompleteJsonheuristic to skip brackets/braces inside JSON string valuesThe heuristic was incorrectly counting brackets inside strings (e.g.,
"delta":"\"]\"") as unbalanced, causing valid JSON to be marked as incomplete. This led to SSE events being concatenated together during streaming, resulting in JSON parse errors.Test plan
pnpm test:unit)pnpm build)pnpm format)🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests