Skip to content

fix(frontend): parse Server-Sent Events (SSE) protocol stream correctly in askQuestionStreamApi#572

Merged
FireFistisDead merged 1 commit into
FireFistisDead:masterfrom
Sandeep6135:fix/sse-stream-parsing-leak
Jun 18, 2026
Merged

fix(frontend): parse Server-Sent Events (SSE) protocol stream correctly in askQuestionStreamApi#572
FireFistisDead merged 1 commit into
FireFistisDead:masterfrom
Sandeep6135:fix/sse-stream-parsing-leak

Conversation

@Sandeep6135

Copy link
Copy Markdown
Contributor

Pull Request: Resolve SSE Protocol Leak in Chat Interface (Broken Stream Rendering)

Closes #565

📌 Classification & Priority

Metric Value
Change Type bug-fix
Severity Level medium / critical
Target Service frontend-app
User Experience Impact exceptional-ui-rendering
Fix Strategy Stream Parser Implementation

📖 Summary

Important

This PR fixes an SSE (Server-Sent Events) protocol leak where raw control envelopes (data: ..., event: ..., and [DONE]) generated by the backend AI services were leaking into the chat interface UI instead of rendering clean, human-readable answers.

🔴 Problem

The frontend stream helper askQuestionStreamApi consumed the raw response stream by reading and decoding binary chunks. However, it lacked a protocol parser to filter SSE lines, appending the raw chunk string (including data: , event: , and data: [DONE] metadata boundaries) directly to the UI rendering state. As a result, users were shown raw SSE protocol markup instead of clean generated sentences.

🟢 Solution

Implemented a client-side stream parser inside askQuestionStreamApi:

  1. Integrated an input string buffer to handle partial chunk splits across network bounds.
  2. Segmented incoming text streams by newline delimiters (\n) and buffered trailing/incomplete lines to preserve character sequences.
  3. Cleaned carriage returns (\r) to support multi-platform protocol alignment.
  4. Extracted SSE message content values by matching and slicing the data: prefix, while ignoring control events such as [DONE].

🧪 Steps to Reproduce

  1. Navigate to the chat panel in the UI.
  2. Enter a query and hit send to open a streaming response.
  3. Look at the text chunks appearing in the chat bubbles.
  4. Verify that only the clean completed sentences are visible, and no data: or [DONE] protocol syntax leaks into the interface.

🔍 Expected Behaviour

The user sees only the clean, conversational sentence output inside the chat interface bubbles.

❌ Actual Behaviour (Before Fix)

The chat bubble leaked raw SSE envelopes such as data: Hello\n\ndata: World\n\ndata: [DONE] directly into the viewport.


🛠️ Code Diff Walkthrough

frontend/src/services/api.js

@@ -145,13 +145,29 @@ export const askQuestionStreamApi = async (question, sessionId, sessionSecret, m
   const reader = response.body.getReader();
   const decoder = new TextDecoder("utf-8");
   let fullText = "";
+  let buffer = "";
 
   while (true) {
     const { done, value } = await reader.read();
     if (done) break;
-    const chunk = decoder.decode(value, { stream: true });
-    fullText += chunk;
-    onChunk(fullText);
+    
+    buffer += decoder.decode(value, { stream: true });
+    const lines = buffer.split("\n");
+    buffer = lines.pop(); // Hold onto incomplete last line
+
+    for (let line of lines) {
+      if (line.endsWith("\r")) {
+        line = line.slice(0, -1);
+      }
+      if (line.startsWith("data: ")) {
+        const dataVal = line.slice(6);
+        if (dataVal === "[DONE]") {
+          break;
+        }
+        fullText += dataVal;
+        onChunk(fullText);
+      }
+    }
   }
 
   return fullText;

Copilot AI review requested due to automatic review settings June 18, 2026 17:41
@vercel

vercel Bot commented Jun 18, 2026

Copy link
Copy Markdown

@Sandeep6135 is attempting to deploy a commit to the firefistisdead's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@Sandeep6135, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 44 minutes and 2 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b93491ac-8a49-4150-8fce-0bbeb4daf26c

📥 Commits

Reviewing files that changed from the base of the PR and between 5590b87 and 7971fd8.

📒 Files selected for processing (1)
  • frontend/src/services/api.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added backend Express or API gateway work bug Something isn't working enhancement New feature or request feature A new feature or improvement fix A targeted fix or cleanup frontend Frontend-related work level:critical level:intermediate question Further information is requested labels Jun 18, 2026

Copilot AI 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.

Pull request overview

Fixes the frontend streaming chat rendering by parsing Server-Sent Events (SSE) frames in askQuestionStreamApi so SSE protocol envelopes (e.g., data: ..., [DONE]) don’t leak into the UI.

Changes:

  • Introduces a stream buffer to handle partial chunks and parse incoming text by newline delimiters.
  • Filters SSE data: lines and ignores the [DONE] marker when building the displayed answer.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +162 to +166
if (line.startsWith("data: ")) {
const dataVal = line.slice(6);
if (dataVal === "[DONE]") {
break;
}
@FireFistisDead FireFistisDead merged commit 2e00e7d into FireFistisDead:master Jun 18, 2026
9 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Express or API gateway work bug Something isn't working enhancement New feature or request feature A new feature or improvement frontend Frontend-related work gssoc:approved level:intermediate quality:exceptional question Further information is requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: SSE Protocol Leak in Chat Interface (Broken Stream Rendering)

3 participants