Skip to content

fix(web): keep single-chat SSE stream alive across route changes - #18180

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
dcc123456:fix/chat-stream-survives-navigation
Aug 13, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
dcc123456:fix/chat-stream-survives-navigation

Conversation

@dcc123456

Copy link
Copy Markdown
Collaborator

Summary

fix(web): keep single-chat SSE stream alive across route changes

Asking a question and navigating away mid-answer lost the stream: the answer bubble came back empty or frozen, and the real answer only appeared once the backend had finished and the session was refetched.

All SSE state lived in component-local state and refs, so unmounting /chat/:id destroyed it. The fetch and reader loop already survived the unmount, but every chunk was written into a dead setState and silently discarded, and on return a fresh hook found an empty cache while the server had not persisted the answer yet.

Hoist the message list, the streaming flag and the AbortController into a module-level Zustand store keyed by conversation id, and move the reader loop into a plain module-level async function that writes into that store. Components become pure subscribers, so unmounting no longer touches the stream.

Scope is the single-chat path only; useSendMessageWithSse and the multi-model path are untouched. Recovery across a hard reload is out of scope, since the browser kills the request.

Also on this path:

  • a server response resolving right after a stream ends can no longer truncate the finished answer (message-count comparison in hydrateFromServer), while still letting real message ids, references and out-of-band updates through
  • a failed stream parks the question text on its own session instead of typing it into whichever input happens to be mounted, and now raises a notification instead of failing silently
  • chunks are coalesced into one store write per 60ms and the store no longer records every chunk into Redux DevTools, which is what made navigating away mid-answer feel slow
  • a non-abort reader error breaks out of the parse loop instead of spinning forever

Asking a question and navigating away mid-answer lost the stream: the
answer bubble came back empty or frozen, and the real answer only
appeared once the backend had finished and the session was refetched.

All SSE state lived in component-local state and refs, so unmounting
/chat/:id destroyed it. The fetch and reader loop already survived the
unmount, but every chunk was written into a dead setState and silently
discarded, and on return a fresh hook found an empty cache while the
server had not persisted the answer yet.

Hoist the message list, the streaming flag and the AbortController into
a module-level Zustand store keyed by conversation id, and move the
reader loop into a plain module-level async function that writes into
that store. Components become pure subscribers, so unmounting no longer
touches the stream.

Scope is the single-chat path only; useSendMessageWithSse and the
multi-model path are untouched. Recovery across a hard reload is out of
scope, since the browser kills the request.

Also on this path:
- a server response resolving right after a stream ends can no longer
  truncate the finished answer (message-count comparison in
  hydrateFromServer), while still letting real message ids, references
  and out-of-band updates through
- a failed stream parks the question text on its own session instead of
  typing it into whichever input happens to be mounted, and now raises
  a notification instead of failing silently
- chunks are coalesced into one store write per 60ms and the store no
  longer records every chunk into Redux DevTools, which is what made
  navigating away mid-answer feel slow
- a non-abort reader error breaks out of the parse loop instead of
  spinning forever
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧰 typescript Pull requests that update Typescript code labels Aug 12, 2026
@dcc123456
dcc123456 requested review from cike8899 and wangq8 August 12, 2026 11:55
@dcc123456 dcc123456 added the ci Continue Integration label Aug 12, 2026
@dcc123456
dcc123456 marked this pull request as draft August 12, 2026 11:56
@dcc123456
dcc123456 marked this pull request as ready for review August 12, 2026 11:56
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds a shared Zustand chat-stream store, native SSE transport, module-level stream orchestration, and store-backed chat UI integration. It also adds session eviction, hydration, failure recovery, abort handling, and stream cleanup after conversation deletion.

Changes

Chat stream architecture

Layer / File(s) Summary
SSE completion transport
web/src/services/chat-completion-stream.ts
Adds native fetch requests, SSE parsing, malformed-payload tolerance, abort handling, and safe JSON parsing.
Session state and message model
web/src/pages/next-chats/chat-stream/constants.ts, web/src/pages/next-chats/chat-stream/store.ts, web/src/pages/next-chats/chat-stream/utils.ts
Adds cached conversation sessions, hydration, prologue seeding, message operations, local-file restoration, selectors, and message-building utilities.
Stream lifecycle orchestration
web/src/pages/next-chats/chat-stream/run-stream.ts, web/src/pages/next-chats/chat-stream/store.ts
Adds guarded stream startup, answer chunk coalescing, metadata preservation, failure recovery, abort handling, and final stream cleanup.
Chat hook and UI integration
web/src/pages/next-chats/hooks/use-send-chat-message.ts, web/src/pages/next-chats/chat/chat-box/single-chat-box.tsx, web/src/pages/next-chats/chat/index.tsx, web/src/pages/next-chats/chat/conversation-dropdown.tsx, web/src/pages/next-chats/chat/sessions.tsx
Moves message state and stream controls to the shared store. Chat deletion now removes related stream sessions.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatInput
  participant useSendMessage
  participant runChatCompletionStream
  participant ChatCompletionService
  participant ChatStreamStore
  ChatInput->>useSendMessage: submit message
  useSendMessage->>ChatStreamStore: append question and placeholder
  useSendMessage->>runChatCompletionStream: start stream
  runChatCompletionStream->>ChatCompletionService: request SSE completion
  ChatCompletionService-->>runChatCompletionStream: return completion chunks
  runChatCompletionStream->>ChatStreamStore: apply coalesced answer
  runChatCompletionStream->>ChatStreamStore: complete or abort stream
Loading

Possibly related PRs

Poem

A rabbit watched the answer stream,
While chunks arrived in one neat dream.
The store kept every message near,
And cleared old sessions without fear.
“Hop on,” said Bun, “the chat is clear!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 summarizes the main change: keeping single-chat SSE streams active across route changes.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, solution, scope, and related behavior 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.

@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: 8

🤖 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/chat-stream/run-stream.ts`:
- Around line 83-117: Update the response handling around
parseCompletionEventStream to inspect response.ok and Content-Type before
choosing a body parser: only parse the original response as SSE for the
confirmed text/event-stream; charset=utf-8 media type, and otherwise parse its
body as JSON. Mark ok false when response.ok is false or the parsed error code
is non-zero, including non-JSON error responses, and remove the
response.clone/readJsonSafely tee so the SSE body is consumed only once.

In `@web/src/pages/next-chats/chat-stream/store.ts`:
- Around line 266-286: Update failStream to remove the question and placeholder
only when both messages exist, preserving shorter sessions such as a seeded
prologue. Also refresh the session’s lastActiveAt when storing pendingInput so
evictIdleSessions does not treat the failed session as idle.
- Around line 327-363: Update truncateAfterMessage so the matched message is
only followed by and reset when an assistant message exists at index + 1.
Preserve the existing truncation and assistant-clearing behavior when that
following message exists, but leave the final message unchanged when messageId
identifies the last entry.
- Around line 238-261: The comment for EnableChatStreamDevtools should
explicitly state that setting it to false disables all chat-stream DevTools
actions, including applyAnswer and other non-chunk updates, rather than only
chunk-update actions.

In `@web/src/pages/next-chats/hooks/use-send-chat-message.ts`:
- Around line 108-128: Update runChatCompletionStream and its beginStream
refusal path to return a distinct started outcome: set started to false when a
duplicate stream start is rejected and true when the stream begins normally. In
use-send-chat-message.ts, gate the !ok && !aborted failure handling on started
so refused starts neither call failStream nor show a request-error notification.
- Around line 188-226: Update the message construction in the send flow around
appendQuestion and sendMessage so both use one shared message object with
identical trimmed content. Preserve the existing id, role, files, and
conversationId fields, and reuse that object for both the local question and
request payload without separately using value and value.trim().

In `@web/src/services/chat-completion-stream.ts`:
- Line 50: Update the reasoning field in the chat completion request to
explicitly default the optional enableThinking flag before numeric conversion,
ensuring absent values produce a valid numeric flag rather than NaN or null.
Preserve numeric conversion for provided values.
- Around line 96-100: Update the payload handling before yielding in the chat
completion stream so only payloads with an object-valued data field are emitted;
skip absent, null, boolean, and other non-object data values. Preserve yielding
valid CompletionChunk objects and prevent run-stream’s chunk.final access from
receiving invalid values.
🪄 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: 7ab27167-a652-4924-9649-672e0d10a722

📥 Commits

Reviewing files that changed from the base of the PR and between 207e2ea and 3325feb.

📒 Files selected for processing (10)
  • web/src/pages/next-chats/chat-stream/constants.ts
  • web/src/pages/next-chats/chat-stream/run-stream.ts
  • web/src/pages/next-chats/chat-stream/store.ts
  • web/src/pages/next-chats/chat-stream/utils.ts
  • web/src/pages/next-chats/chat/chat-box/single-chat-box.tsx
  • web/src/pages/next-chats/chat/conversation-dropdown.tsx
  • web/src/pages/next-chats/chat/index.tsx
  • web/src/pages/next-chats/chat/sessions.tsx
  • web/src/pages/next-chats/hooks/use-send-chat-message.ts
  • web/src/services/chat-completion-stream.ts

Comment on lines +83 to +117
// Clone before the body is consumed: an error response carries a JSON
// body, which is how a failed completion is detected. On a successful SSE
// response this parse simply fails and yields undefined.
const errorBodyPromise = readJsonSafely(response.clone());

try {
for await (const chunk of parseCompletionEventStream(response)) {
accumulatedAnswer = mergeAnswerChunk(accumulatedAnswer, chunk);
pendingChunk = pendingChunk ? { ...pendingChunk, ...chunk } : chunk;

// The first chunk flushes immediately (lastFlushAt is 0), so the empty
// placeholder is replaced without waiting out an interval.
if (chunk.final || Date.now() - lastFlushAt >= AnswerFlushIntervalMs) {
flushAnswer();
}
}
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') {
aborted = true;
} else {
throw error;
}
}

// A healthy stream body isn't valid JSON, so errorBody stays undefined and
// the request counts as successful. A parseable body means the endpoint
// answered with an error envelope instead of a stream.
const errorBody = await errorBodyPromise;
if (
!aborted &&
errorBody !== undefined &&
(response.status !== 200 || errorBody.code !== 0)
) {
ok = false;
}

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target file outline ---'
ast-grep outline web/src/pages/next-chats/chat-stream/run-stream.ts --view expanded || true
printf '%s\n' '--- target source ---'
cat -n web/src/pages/next-chats/chat-stream/run-stream.ts | sed -n '1,190p'
printf '%s\n' '--- related symbols and endpoint references ---'
rg -n --glob '!node_modules' 'parseCompletionEventStream|readJsonSafely|AnswerFlushIntervalMs|endStream|text/event-stream|next-chats|completion' web/src | head -250
printf '%s\n' '--- repository files near chat stream and server endpoint candidates ---'
git ls-files | rg '(^|/)(run-stream|chat|completion|stream|next-chats)' | head -250

Repository: infiniflow/ragflow

Length of output: 17800


🏁 Script executed:

#!/bin/bash
set -e
cat -n web/src/pages/next-chats/chat-stream/run-stream.ts | sed -n '1,180p'
printf '%s\n' '--- definitions ---'
rg -n -C 8 'function (readJsonSafely|parseCompletionEventStream)|const (readJsonSafely|parseCompletionEventStream)|readJsonSafely|parseCompletionEventStream' web/src
printf '%s\n' '--- all uses of the runner and response stream ---'
rg -n -C 6 'runStream|run-stream|response\.status|response\.ok|Content-Type.*text/event-stream|text/event-stream' web/src | head -400

Repository: infiniflow/ragflow

Length of output: 36538


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate endpoint and route files ---'
git ls-files | rg -i '(chat|completion|stream|next)' | head -300
printf '%s\n' '--- response header assignments ---'
rg -n -C 5 'text/event-stream|Content-Type|content-type|ReadableStream|SSE|event stream' --glob '*.{ts,tsx,js,jsx,go,py}' . | head -500

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target ---'
cat -n web/src/pages/next-chats/chat-stream/run-stream.ts | sed -n '1,180p'
printf '%s\n' '--- helpers and call sites ---'
rg -n -C 10 'readJsonSafely|parseCompletionEventStream|runStream|endStream|AnswerFlushIntervalMs' web/src | head -500
printf '%s\n' '--- endpoint headers and stream construction ---'
rg -n -C 8 'text/event-stream|Content-Type|content-type|ReadableStream|parseCompletionEventStream' --glob '*.{ts,tsx,js,jsx,go,py}' . | head -600

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -e
cat -n web/src/pages/next-chats/chat-stream/run-stream.ts | sed -n '1,180p'
rg -n -C 8 'readJsonSafely|parseCompletionEventStream|endStream|runStream|text/event-stream|Content-Type' web/src --glob '*.{ts,tsx,js,jsx}'
rg -n -C 8 'text/event-stream|Content-Type|content-type|ReadableStream' . --glob '*.{ts,tsx,js,jsx,go,py}'

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- frontend stream service ---'
cat -n web/src/services/chat-completion-stream.ts | sed -n '1,140p'
printf '%s\n' '--- frontend request contract ---'
cat -n web/src/pages/next-chats/hooks/use-send-chat-message.ts | sed -n '1,180p'
printf '%s\n' '--- exact backend completion handlers and stream responses ---'
rg -n -l 'chatbot_completions|chat_completions|agent_bot_completions|text/event-stream' api internal test | head -100
rg -n -C 12 'chatbot_completions|chat_completions|agent_bot_completions|text/event-stream' api/apps api | head -500

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- focused backend header evidence ---'
rg -n -C 18 'text/event-stream|StreamingResponse|stream_with_context|Response\(' api/apps/restful_apis/chat_api.py api/apps/restful_apis/chat_channel_api.py api | rg -B 18 -A 18 'text/event-stream|StreamingResponse|stream_with_context' | head -500
printf '%s\n' '--- focused stream tests ---'
rg -n -C 10 'text/event-stream|Content-Type|stream.*completion|completion.*stream' test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py test/testcases/restful_api test/unit_test | head -500

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -e
cat -n web/src/services/chat-completion-stream.ts | sed -n '1,140p'
rg -n -C 20 'chatbot_completions|chat_completions|text/event-stream|StreamingResponse' api/apps api internal test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py | head -700

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- completion URL and owning handler ---'
cat -n web/src/utils/api.ts | sed -n '295,325p'
rg -n -C 8 'route\("/chat/completions"|async def session_completion|stream_mode\s*=' api/apps/restful_apis/chat_api.py
cat -n api/apps/restful_apis/chat_api.py | sed -n '1260,1410p'
printf '%s\n' '--- response helpers and their status behavior ---'
rg -n -C 8 'def (get_json_result|get_error_data_result|server_error_response)|get_json_result|get_error_data_result|server_error_response' api | head -250

Repository: infiniflow/ragflow

Length of output: 31622


🏁 Script executed:

#!/bin/bash
set -e
node - <<'JS'
const body = 'data: {"code":0,"message":"","data":{"answer":"x"}}\n\n'.repeat(1000);
const response = new Response(new ReadableStream({
  start(controller) { controller.enqueue(new TextEncoder().encode(body)); controller.close(); }
}), {
  status: 502,
  headers: {'Content-Type': 'text/html; charset=utf-8'}
});
const clone = response.clone();
const jsonResult = clone.json().then(
  value => ({parsed: true, value}),
  error => ({parsed: false, name: error.name})
);
const originalText = response.text();
Promise.all([jsonResult, originalText]).then(([json, text]) => {
  console.log(JSON.stringify({
    status: response.status,
    ok: response.ok,
    originalBytes: text.length,
    cloneJson: json
  }));
});
JS

Repository: infiniflow/ragflow

Length of output: 417


🏁 Script executed:

#!/bin/bash
set -e
cat -n web/src/utils/api.ts | sed -n '300,320p'
rg -n -C 10 'route\("/chat/completions"|async def session_completion|stream_mode\s*=' api/apps/restful_apis/chat_api.py
cat -n api/apps/restful_apis/chat_api.py | sed -n '1260,1410p'
rg -n -C 8 'def (get_json_result|get_error_data_result|server_error_response)' api

Repository: infiniflow/ragflow

Length of output: 16197


Use response.ok before parsing the response body.

A non-200 response with a non-JSON body leaves ok as true. The caller then keeps the empty assistant placeholder. response.clone() also tees and fully drains the SSE body, which duplicates stream data and delays completion.

Use the Content-Type check for the confirmed text/event-stream; charset=utf-8 streaming response. Otherwise, read the response as JSON and return failure when response.ok is false or code is non-zero.

🤖 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/chat-stream/run-stream.ts` around lines 83 - 117,
Update the response handling around parseCompletionEventStream to inspect
response.ok and Content-Type before choosing a body parser: only parse the
original response as SSE for the confirmed text/event-stream; charset=utf-8
media type, and otherwise parse its body as JSON. Mark ok false when response.ok
is false or the parsed error code is non-zero, including non-JSON error
responses, and remove the response.clone/readJsonSafely tee so the SSE body is
consumed only once.

Comment on lines +238 to +261
applyAnswer: (conversationId, answer) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
return {
sessions: {
...state.sessions,
[conversationId]: {
...previous,
messages: [
...previous.messages.slice(0, -1),
buildAssistantMessageFromAnswer(answer),
],
lastActiveAt: Date.now(),
},
},
};
},
false,
'applyAnswer',
);
},

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the devtools flag and the flush interval constant
fd -t f 'constants.ts' web/src/pages/next-chats/chat-stream --exec cat -n {} \;

# Confirm no other opt-out mechanism is wired for applyAnswer
rg -n 'EnableChatStreamDevtools|AnswerFlushIntervalMs' web/src

Repository: infiniflow/ragflow

Length of output: 2331


🌐 Web query:

Does Zustand 4 devtools middleware support skipping individual set calls from the Redux DevTools action log?

💡 Result:

Zustand 4's devtools middleware does not natively support "skipping" individual set calls within the Redux DevTools action log (i.e., toggling an action's effect on/off while preserving subsequent states) in the same way Redux does [1][2]. While you can use the actionsDenylist option to hide specific actions from the DevTools UI, this only filters the display; it does not stop the actions from being processed by the store or provide a mechanism to toggle their impact on the state [1][3]. Zustand's implementation of Redux DevTools is focused on monitoring and state synchronization rather than a full Redux-compatible reducer-based architecture [2]. Consequently, features that rely on reducers—such as the ability to "skip" an action to recompute state—are generally not supported [4][2]. Although the devtools middleware supports time-travel debugging through JUMP_TO_STATE, JUMP_TO_ACTION, and COMMIT/ROLLBACK commands, these operate by restoring snapshots of the state rather than replaying or skipping individual actions [2].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- store middleware and actions ---'
sed -n '380,425p' web/src/pages/next-chats/chat-stream/store.ts
printf '%s\n' '--- stream write path ---'
sed -n '1,125p' web/src/pages/next-chats/chat-stream/run-stream.ts
printf '%s\n' '--- applyAnswer references ---'
rg -n -C 4 'applyAnswer|EnableChatStreamDevtools|devtools' web/src/pages/next-chats/chat-stream web/src/pages/next-chats

Repository: infiniflow/ragflow

Length of output: 19000


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
from pathlib import Path
import re

constants = Path("web/src/pages/next-chats/chat-stream/constants.ts").read_text()
store = Path("web/src/pages/next-chats/chat-stream/store.ts").read_text()

enabled = re.search(r"export const EnableChatStreamDevtools\s*=\s*(true|false)", constants)
middleware = re.search(
    r"devtools\([\s\S]*?\{\s*name:\s*'chat-stream',\s*enabled:\s*EnableChatStreamDevtools\s*\}",
    store,
)
apply_answer = re.search(
    r"applyAnswer:[\s\S]*?set\([\s\S]*?false,\s*'applyAnswer'",
    store,
)

print({
    "EnableChatStreamDevtools": enabled.group(1) if enabled else None,
    "middleware_uses_flag": bool(middleware),
    "applyAnswer_has_devtools_action_name": bool(apply_answer),
})
PY

Repository: infiniflow/ragflow

Length of output: 270


Clarify the global DevTools switch

applyAnswer records an 'applyAnswer' action when the middleware is enabled. EnableChatStreamDevtools = false disables all chat-stream actions, not only chunk updates. Clarify this in the flag comment.

🤖 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/chat-stream/store.ts` around lines 238 - 261, The
comment for EnableChatStreamDevtools should explicitly state that setting it to
false disables all chat-stream DevTools actions, including applyAnswer and other
non-chunk updates, rather than only chunk-update actions.

Comment on lines +266 to +286
failStream: (conversationId, pendingInput) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
return {
sessions: {
...state.sessions,
[conversationId]: {
...previous,
messages: previous.messages.slice(0, -2),
pendingInput,
},
},
};
},
false,
'failStream',
);
},

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

failStream does not refresh lastActiveAt and can slice a short list.

Line 277 uses slice(0, -2) to drop the question and the placeholder. When the session holds fewer than two messages the result is an empty list, which silently discards a seeded prologue. The action also leaves lastActiveAt unchanged, so a session that just failed looks idle to evictIdleSessions and can be evicted together with its pendingInput. The parked question text is then lost before the user returns.

🔧 Proposed fix
                 [conversationId]: {
                   ...previous,
-                  messages: previous.messages.slice(0, -2),
+                  messages:
+                    previous.messages.length >= 2
+                      ? previous.messages.slice(0, -2)
+                      : previous.messages,
                   pendingInput,
+                  lastActiveAt: Date.now(),
                 },
📝 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
failStream: (conversationId, pendingInput) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
return {
sessions: {
...state.sessions,
[conversationId]: {
...previous,
messages: previous.messages.slice(0, -2),
pendingInput,
},
},
};
},
false,
'failStream',
);
},
failStream: (conversationId, pendingInput) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
return {
sessions: {
...state.sessions,
[conversationId]: {
...previous,
messages:
previous.messages.length >= 2
? previous.messages.slice(0, -2)
: previous.messages,
pendingInput,
lastActiveAt: Date.now(),
},
},
};
},
false,
'failStream',
);
},
🤖 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/chat-stream/store.ts` around lines 266 - 286, Update
failStream to remove the question and placeholder only when both messages exist,
preserving shorter sessions such as a seeded prologue. Also refresh the
session’s lastActiveAt when storing pendingInput so evictIdleSessions does not
treat the failed session as idle.

Comment on lines +327 to +363
truncateAfterMessage: (conversationId, messageId) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;

const index = previous.messages.findIndex(
(x) => x.id === messageId,
);
if (index === -1) return state;

const kept = previous.messages.slice(0, index + 2);
const latest = kept.at(-1);
const messages = latest
? [
...kept.slice(0, -1),
{
...latest,
content: '',
reference: undefined,
prompt: undefined,
},
]
: kept;

return {
sessions: {
...state.sessions,
[conversationId]: { ...previous, messages },
},
};
},
false,
'truncateAfterMessage',
);
},

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

truncateAfterMessage clears the question when the target message is last.

Line 339 takes slice(0, index + 2) and assumes an assistant message always follows the matched message. When messageId identifies the final message in the list, kept equals the whole list and latest is that same message. Lines 344-349 then blank its content, so a user question loses its text.

Reset the assistant message only when it exists after index.

🐛 Proposed fix
-            const kept = previous.messages.slice(0, index + 2);
-            const latest = kept.at(-1);
-            const messages = latest
-              ? [
-                  ...kept.slice(0, -1),
-                  {
-                    ...latest,
-                    content: '',
-                    reference: undefined,
-                    prompt: undefined,
-                  },
-                ]
-              : kept;
+            const answer = previous.messages[index + 1];
+            const messages = answer
+              ? [
+                  ...previous.messages.slice(0, index + 1),
+                  {
+                    ...answer,
+                    content: '',
+                    reference: undefined,
+                    prompt: undefined,
+                  },
+                ]
+              : previous.messages.slice(0, index + 1);
📝 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
truncateAfterMessage: (conversationId, messageId) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
const index = previous.messages.findIndex(
(x) => x.id === messageId,
);
if (index === -1) return state;
const kept = previous.messages.slice(0, index + 2);
const latest = kept.at(-1);
const messages = latest
? [
...kept.slice(0, -1),
{
...latest,
content: '',
reference: undefined,
prompt: undefined,
},
]
: kept;
return {
sessions: {
...state.sessions,
[conversationId]: { ...previous, messages },
},
};
},
false,
'truncateAfterMessage',
);
},
truncateAfterMessage: (conversationId, messageId) => {
if (!conversationId) return;
set(
(state) => {
const previous = state.sessions[conversationId];
if (!previous) return state;
const index = previous.messages.findIndex(
(x) => x.id === messageId,
);
if (index === -1) return state;
const answer = previous.messages[index + 1];
const messages = answer
? [
...previous.messages.slice(0, index + 1),
{
...answer,
content: '',
reference: undefined,
prompt: undefined,
},
]
: previous.messages.slice(0, index + 1);
return {
sessions: {
...state.sessions,
[conversationId]: { ...previous, messages },
},
};
},
false,
'truncateAfterMessage',
);
},
🤖 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/chat-stream/store.ts` around lines 327 - 363, Update
truncateAfterMessage so the matched message is only followed by and reset when
an assistant message exists at index + 1. Preserve the existing truncation and
assistant-clearing behavior when that following message exists, but leave the
final message unchanged when messageId identifies the last entry.

Comment on lines +108 to 128
const { ok, aborted } = await runChatCompletionStream({
conversationId: sessionId,
chatId,
// An explicitly provided list is authoritative, even when empty
// (e.g. regenerating the first question must truncate history).
messages: [
...(Array.isArray(explicitMessages) ? explicitMessages : messages),
message,
],
enableThinking,
enableInternet,
});

if (!ok && !aborted) {
// The failure can land long after the page unmounted or after the user
// switched conversations, so don't write to the input box here: park the
// text on the failing session instead, and tell the user something went
// wrong wherever they currently are.
failStream(sessionId, message.content);
notification.error({ message: t('message.requestError') });
}

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

A refused stream start is reported as a request failure.

runChatCompletionStream returns { ok: false, aborted: false } when beginStream rejects a duplicate start (web/src/pages/next-chats/chat-stream/run-stream.ts:39-42). This branch then calls failStream(sessionId, message.content) and shows message.requestError, although no request was sent and a stream is still running. handlePressEnter guards this case with its own getState() check, but regenerateMessage does not, so regenerating during an active stream shows a false error and parks the question text.

Return a distinct outcome for the refused start and skip the failure handling for it.

🐛 Proposed direction
-      const { ok, aborted } = await runChatCompletionStream({
+      const { ok, aborted, started } = await runChatCompletionStream({
-      if (!ok && !aborted) {
+      if (started && !ok && !aborted) {

Then set started: false in the beginStream refusal path of run-stream.ts and started: true otherwise.

🤖 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 108 -
128, Update runChatCompletionStream and its beginStream refusal path to return a
distinct started outcome: set started to false when a duplicate stream start is
rejected and true when the stream begins normally. In use-send-chat-message.ts,
gate the !ok && !aborted failure handling on started so refused starts neither
call failStream nor show a request-error notification.

Comment on lines 188 to +226
const id = uuid();

const questionMessage = {
// useUploadFile tracks files as loosely typed records; narrow once here.
const attachedFiles = files as IMessage['files'];

const questionMessage: IMessage = {
content: value,
files: files,
files: attachedFiles,
id,
role: MessageType.User,
conversationId: targetConversationId,
};
// The await on createConversationBeforeSendMessage above can span a
// conversation switch. Route the question to the conversation it was
// asked in, not whichever is currently displayed.
if (targetConversationId === conversationId) {
addNewestQuestion(questionMessage);
} else {
const cached = messagesCacheRef.current[targetConversationId] ?? [];
messagesCacheRef.current[targetConversationId] =
appendQuestionToMessages(cached, questionMessage);
}

if (done) {
setValue('');
sendMessage({
currentConversationId: targetConversationId,
// For an existing conversation currentMessages is empty; fall back
// to derivedMessages instead of sending an empty history.
messages: currentMessages.length > 0 ? currentMessages : undefined,
message: {
id,
content: value.trim(),
role: MessageType.User,
files,
conversationId: targetConversationId,
},
enableInternet,
enableThinking,
});
}
// Route the question to the conversation it was asked in, not whichever
// is currently displayed.
//
// Do NOT hydrate from currentMessages here. For a freshly created
// conversation the server only returns the seeded prologue, which
// seedPrologue has already put in the store — and hydrating now would
// pass the authority check (not streaming yet) and wipe the question and
// placeholder that were just appended.
appendQuestion(targetConversationId, questionMessage);

setValue('');
sendMessage({
currentConversationId: targetConversationId,
// For an existing conversation currentMessages is empty; fall back to
// the store's message list instead of sending an empty history.
messages: currentMessages.length > 0 ? currentMessages : undefined,
message: {
id,
content: value.trim(),
role: MessageType.User,
files: attachedFiles,
conversationId: targetConversationId,
},
enableInternet,
enableThinking,
});

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

The displayed question and the sent question use different text.

Line 194 stores content: value. Line 219 sends content: value.trim(). The local bubble keeps the surrounding whitespace until server hydration replaces it. Build the message once and reuse it for both the store and the request.

♻️ Proposed fix
       const questionMessage: IMessage = {
-        content: value,
+        content: value.trim(),
         files: attachedFiles,
         id,
         role: MessageType.User,
         conversationId: targetConversationId,
       };
@@
       setValue('');
       sendMessage({
         currentConversationId: targetConversationId,
         messages: currentMessages.length > 0 ? currentMessages : undefined,
-        message: {
-          id,
-          content: value.trim(),
-          role: MessageType.User,
-          files: attachedFiles,
-          conversationId: targetConversationId,
-        },
+        message: questionMessage,
         enableInternet,
         enableThinking,
       });
📝 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
const id = uuid();
const questionMessage = {
// useUploadFile tracks files as loosely typed records; narrow once here.
const attachedFiles = files as IMessage['files'];
const questionMessage: IMessage = {
content: value,
files: files,
files: attachedFiles,
id,
role: MessageType.User,
conversationId: targetConversationId,
};
// The await on createConversationBeforeSendMessage above can span a
// conversation switch. Route the question to the conversation it was
// asked in, not whichever is currently displayed.
if (targetConversationId === conversationId) {
addNewestQuestion(questionMessage);
} else {
const cached = messagesCacheRef.current[targetConversationId] ?? [];
messagesCacheRef.current[targetConversationId] =
appendQuestionToMessages(cached, questionMessage);
}
if (done) {
setValue('');
sendMessage({
currentConversationId: targetConversationId,
// For an existing conversation currentMessages is empty; fall back
// to derivedMessages instead of sending an empty history.
messages: currentMessages.length > 0 ? currentMessages : undefined,
message: {
id,
content: value.trim(),
role: MessageType.User,
files,
conversationId: targetConversationId,
},
enableInternet,
enableThinking,
});
}
// Route the question to the conversation it was asked in, not whichever
// is currently displayed.
//
// Do NOT hydrate from currentMessages here. For a freshly created
// conversation the server only returns the seeded prologue, which
// seedPrologue has already put in the store — and hydrating now would
// pass the authority check (not streaming yet) and wipe the question and
// placeholder that were just appended.
appendQuestion(targetConversationId, questionMessage);
setValue('');
sendMessage({
currentConversationId: targetConversationId,
// For an existing conversation currentMessages is empty; fall back to
// the store's message list instead of sending an empty history.
messages: currentMessages.length > 0 ? currentMessages : undefined,
message: {
id,
content: value.trim(),
role: MessageType.User,
files: attachedFiles,
conversationId: targetConversationId,
},
enableInternet,
enableThinking,
});
const id = uuid();
// useUploadFile tracks files as loosely typed records; narrow once here.
const attachedFiles = files as IMessage['files'];
const questionMessage: IMessage = {
content: value.trim(),
files: attachedFiles,
id,
role: MessageType.User,
conversationId: targetConversationId,
};
// Route the question to the conversation it was asked in, not whichever
// is currently displayed.
//
// Do NOT hydrate from currentMessages here. For a freshly created
// conversation the server only returns the seeded prologue, which
// seedPrologue has already put in the store — and hydrating now would
// pass the authority check (not streaming yet) and wipe the question and
// placeholder that were just appended.
appendQuestion(targetConversationId, questionMessage);
setValue('');
sendMessage({
currentConversationId: targetConversationId,
// For an existing conversation currentMessages is empty; fall back to
// the store's message list instead of sending an empty history.
messages: currentMessages.length > 0 ? currentMessages : undefined,
message: questionMessage,
enableInternet,
enableThinking,
});
🤖 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 188 -
226, Update the message construction in the send flow around appendQuestion and
sendMessage so both use one shared message object with identical trimmed
content. Preserve the existing id, role, files, and conversationId fields, and
reuse that object for both the local question and request payload without
separately using value and value.trim().

session_id: sessionId,
messages,
pass_all_history_messages: true,
reasoning: Number(enableThinking),

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Number(enableThinking) produces NaN when the flag is absent.

enableThinking is optional. Number(undefined) is NaN, and JSON.stringify serializes NaN as null. The backend then receives "reasoning": null instead of a numeric flag. Send an explicit default.

🔧 Proposed fix
-      reasoning: Number(enableThinking),
+      reasoning: Number(enableThinking ?? 0),
📝 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
reasoning: Number(enableThinking),
reasoning: Number(enableThinking ?? 0),
🤖 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/services/chat-completion-stream.ts` at line 50, Update the reasoning
field in the chat completion request to explicitly default the optional
enableThinking flag before numeric conversion, ensuring absent values produce a
valid numeric flag rather than NaN or null. Preserve numeric conversion for
provided values.

Comment on lines +96 to +100
const data = payload?.data;
// The backend signals termination with a boolean `data` field.
if (typeof data === 'boolean') continue;

yield data as CompletionChunk;

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard against a payload without an object data field.

Line 98 skips only boolean values. Any event whose data field is absent or null is yielded as undefined or null. The consumer in web/src/pages/next-chats/chat-stream/run-stream.ts then reads chunk.final at line 95, which throws a TypeError and aborts the stream loop. Fix it here at the source instead of adding a guard in the driver.

🛡️ Proposed fix
     const data = payload?.data;
     // The backend signals termination with a boolean `data` field.
     if (typeof data === 'boolean') continue;
+    // Heartbeats and envelopes without a payload object carry nothing to render.
+    if (data === null || typeof data !== 'object') continue;
 
     yield data as CompletionChunk;
📝 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
const data = payload?.data;
// The backend signals termination with a boolean `data` field.
if (typeof data === 'boolean') continue;
yield data as CompletionChunk;
const data = payload?.data;
// The backend signals termination with a boolean `data` field.
if (typeof data === 'boolean') continue;
// Heartbeats and envelopes without a payload object carry nothing to render.
if (data === null || typeof data !== 'object') continue;
yield data as CompletionChunk;
🤖 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/services/chat-completion-stream.ts` around lines 96 - 100, Update the
payload handling before yielding in the chat completion stream so only payloads
with an object-valued data field are emitted; skip absent, null, boolean, and
other non-object data values. Preserve yielding valid CompletionChunk objects
and prevent run-stream’s chunk.final access from receiving invalid values.

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

Thanks for this PR — the architecture is well thought-out and the Zustand store at module level is the right approach for keeping SSE streams alive across unmounts. The attention to edge cases (StrictMode double effects, hydration races, eviction policy) shows careful engineering.

A few observations and questions:

1. chat-completion-stream.ts — bypassing axios
The new requestChatCompletionStream uses native fetch directly instead of @/utils/next-request (axios). The comment explains this is for ReadableStream access. However, this means it bypasses any global request interceptors (auth refresh, error normalization, base URL resolution). If the axios instance has important middleware, this could cause subtle issues. Is getAuthorization() alone sufficient for all deployment scenarios (e.g. token refresh on expiry)?

2. zod validation for SSE payloads
parseCompletionEventStream parses SSE data with bare JSON.parse and yields as CompletionChunk — there is no runtime validation of the chunk shape. If the backend changes the payload schema, a missing answer field would silently produce undefined and break mergeAnswerChunk. Consider adding a lightweight schema check or at least a defensive typeof chunk.answer !== "string" guard.

3. Store eviction vs. hydration race
evictIdleSessions is called before many store actions but never on the hot path (applyAnswer). However, if a session is evicted while its runChatCompletionStream is still feeding chunks, applyAnswer would target a missing session — the if (!previous) return state guard in applyAnswer silently drops the write. Is there a path where a streaming session could be evicted? (The comment says "Never evicts a streaming session", which evictIdleSessions does enforce — confirming this is safe.)

4. hydrateFromServer message-count comparison
if (session && messages.length < session.messages.length) return; — this correctly prevents a shorter server list from truncating a just-finished answer. However, is it possible for the server to legitimately return fewer messages (e.g. after a message deletion from another tab)? In that case the store would hold stale deleted messages indefinitely. This is probably an acceptable tradeoff vs. the truncation bug, but worth noting.

5. tenant.go in a different PR?
The diff shows an unrelated change to internal/service/tenant.go (removing factory model type validation), but that appears to be from PR #18121 (separate review). Just confirming this PR does not touch that file.

6. useCurrentChatSession — scroll ref
useScrollToBottom(messages, messageContainerRef) is called unconditionally every render. The scrollRef it returns is passed up through useSendMessage. Does the scroll-to-bottom logic correctly handle the case where new chunks arrive while the user has scrolled up to read earlier messages? Some implementations auto-scroll when streaming but respect user scroll-away — worth confirming.

7. PrologueMessageIdPrefix — collision risk
${PrologueMessageIdPrefix}${conversationId} — if conversationId is a UUID this is safe, but if two conversations happen to have the same id prefix string this could collide. This is probably fine.

Overall strong PR with well-documented tradeoffs. The chunk coalescing (60ms batches) and DevTools opt-out are good performance-conscious choices. None of the above is blocking — just things to consider or clarify.

@wangq8
wangq8 merged commit ab99942 into infiniflow:main Aug 13, 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:XXL This PR changes 1000+ 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