Skip to content

fix(chat): preserve in-flight SSE stream when switching conversations - #18037

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
dcc123456:fix/chat-switch-preserve-sse-stream
Aug 10, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
dcc123456:fix/chat-switch-preserve-sse-stream

Conversation

@dcc123456

Copy link
Copy Markdown
Collaborator

Summary

fix(chat): preserve in-flight SSE stream when switching conversations

Switching conversations no longer aborts the in-flight completion request, which could cancel server-side persistence of the just-asked question. The old SSE stream finishes in the background instead.

  • SingleChatBox ignores backend conversation.messages sync while a stream is active for that conversation, so local streaming state isn't wiped.
  • useSendMessage keeps a per-conversation message cache, restores it on switch, and routes streamed answers to the conversation they belong to (via answer.conversationId) rather than the currently displayed one.

Switching conversations no longer aborts the in-flight completion request,
which could cancel server-side persistence of the just-asked question. The
old SSE stream finishes in the background instead.

- SingleChatBox ignores backend conversation.messages sync while a stream
  is active for that conversation, so local streaming state isn't wiped.
- useSendMessage keeps a per-conversation message cache, restores it on
  switch, and routes streamed answers to the conversation they belong to
  (via answer.conversationId) rather than the currently displayed one.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧰 typescript Pull requests that update Typescript code labels Aug 10, 2026
@dcc123456
dcc123456 requested review from cike8899 and wangq8 August 10, 2026 05:52
@dcc123456 dcc123456 added the ci Continue Integration label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The chat flow now caches messages per conversation and tracks active SSE streams. Questions and answers are routed to their target conversations. Conversation switching no longer aborts the previous request, and active streams are protected from backend message replacement.

Changes

Conversation stream preservation

Layer / File(s) Summary
Conversation message cache and stream state
web/src/pages/next-chats/hooks/use-send-chat-message.ts
The chat hooks add per-conversation message caches, active-stream tracking, message helpers, cache restoration, and cache persistence.
Routed questions and streamed answers
web/src/pages/next-chats/hooks/use-send-chat-message.ts
SSE sending tracks active conversations. Questions and answers update the displayed conversation or the target conversation cache.
Conversation switching and render synchronization
web/src/pages/next-chats/hooks/use-click-card.ts, web/src/pages/next-chats/chat/chat-box/single-chat-box.tsx
Conversation-card navigation keeps the previous request running. SingleChatBox skips backend synchronization during an active stream.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant useSendMessage
  participant SSE
  participant messagesCacheRef
  participant SingleChatBox

  User->>useSendMessage: send message for conversation
  useSendMessage->>SSE: start SSE stream
  useSendMessage->>messagesCacheRef: cache question and placeholder
  SSE-->>useSendMessage: stream answer with conversationId
  useSendMessage->>messagesCacheRef: update target conversation
  SingleChatBox->>useSendMessage: read active stream state
  SingleChatBox-->>User: preserve local streamed messages
Loading

Poem

I’m a rabbit guarding each chat,
With cached little messages stacked flat.
Streams hop without fear,
Switches leave them clear,
And answers return where they’re at.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes preserving an in-flight SSE stream when switching conversations.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, solution, and key implementation changes.

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.

@dcc123456
dcc123456 marked this pull request as draft August 10, 2026 05:52
@dcc123456
dcc123456 marked this pull request as ready for review August 10, 2026 05:52

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/pages/next-chats/hooks/use-click-card.ts`:
- Around line 18-24: Remove the setController(new AbortController()) call from
the navigation flow in use-click-card.ts so the active stream controller remains
reachable by stopOutputMessage. Preserve the existing behavior of letting the
previous SSE request finish without aborting it during conversation switching.

In `@web/src/pages/next-chats/hooks/use-send-chat-message.ts`:
- Around line 55-60: Update the assistant placeholder construction in
useSendChatMessage so its id is generated independently rather than via
buildMessageUuid with the original message, ensuring it cannot reuse
questionMessage.id. Preserve the existing role, empty content, and
conversationId assignments.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: db31ec79-bf71-4428-9a14-4bde7ca34ad0

📥 Commits

Reviewing files that changed from the base of the PR and between 2584ea5 and 1e233e7.

📒 Files selected for processing (3)
  • web/src/pages/next-chats/chat/chat-box/single-chat-box.tsx
  • web/src/pages/next-chats/hooks/use-click-card.ts
  • web/src/pages/next-chats/hooks/use-send-chat-message.ts

Comment on lines +18 to +24
// Switch to a fresh controller WITHOUT aborting the previous one.
// Aborting the in-flight completion request can cancel server-side
// persistence of the just-asked question, so switching conversations
// right after asking would lose the question. Let the old SSE finish
// in the background; the unmounted SingleChatBox's setState becomes
// a no-op and the server keeps the message.
setController(new AbortController());

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep the active stream controller reachable by stopOutputMessage.

The active SSE request retains the controller that useSendMessage received before the switch. Line 24 replaces it. A later stopOutputMessage call aborts the new controller and leaves the prior stream running.

Do not replace the controller on navigation, or track controllers by active stream and abort the controller that owns the selected stream.

Small local fix
-      setController(new AbortController());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/next-chats/hooks/use-click-card.ts` around lines 18 - 24,
Remove the setController(new AbortController()) call from the navigation flow in
use-click-card.ts so the active stream controller remains reachable by
stopOutputMessage. Preserve the existing behavior of letting the previous SSE
request finish without aborting it during conversation switching.

Comment on lines +55 to +60
{
role: MessageType.Assistant,
content: '',
conversationId: message.conversationId,
id: buildMessageUuid({ ...message, role: MessageType.Assistant }),
},

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Give the assistant placeholder a distinct ID.

questionMessage always has an ID at Line 246. buildMessageUuid preserves that ID. Line 59 therefore assigns the user message ID to the assistant placeholder. This makes ID-based message removal and file reconciliation ambiguous until an answer replaces the placeholder.

Proposed fix
     {
       role: MessageType.Assistant,
       content: '',
       conversationId: message.conversationId,
-      id: buildMessageUuid({ ...message, role: MessageType.Assistant }),
+      id: buildMessageUuid({ role: MessageType.Assistant }),
     },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{
role: MessageType.Assistant,
content: '',
conversationId: message.conversationId,
id: buildMessageUuid({ ...message, role: MessageType.Assistant }),
},
{
role: MessageType.Assistant,
content: '',
conversationId: message.conversationId,
id: buildMessageUuid({ role: MessageType.Assistant }),
},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/next-chats/hooks/use-send-chat-message.ts` around lines 55 -
60, Update the assistant placeholder construction in useSendChatMessage so its
id is generated independently rather than via buildMessageUuid with the original
message, ensuring it cannot reuse questionMessage.id. Preserve the existing
role, empty content, and conversationId assignments.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice work on this PR — keeping SSE streams alive with per-conversation caching is a clean approach.

Observations (non-blocking):

  1. messagesCacheRef grows unbounded for the tab lifetime. Consider an LRU cap (20-30 conversations) for long sessions to avoid memory pressure.

  2. appendAnswerToMessages duplicates the message-building logic from addNewestAnswer in logic-hooks.ts. Extracting a shared helper would prevent drift if fields change upstream.

  3. appendAnswerToMessages assumes the last message is always the assistant placeholder — safe today given addNewestQuestion pattern, but worth a comment for future readers.

Edge cases around messagesConversationIdRef ordering and targetConversationId routing are correctly handled. LGTM overall.

@wangq8
wangq8 merged commit 2336958 into infiniflow:main Aug 10, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants