Repository navigation
fix(web): keep single-chat SSE stream alive across route changes - #18180
Conversation
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
📝 WalkthroughWalkthroughThis 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. ChangesChat stream architecture
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
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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.
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
📒 Files selected for processing (10)
web/src/pages/next-chats/chat-stream/constants.tsweb/src/pages/next-chats/chat-stream/run-stream.tsweb/src/pages/next-chats/chat-stream/store.tsweb/src/pages/next-chats/chat-stream/utils.tsweb/src/pages/next-chats/chat/chat-box/single-chat-box.tsxweb/src/pages/next-chats/chat/conversation-dropdown.tsxweb/src/pages/next-chats/chat/index.tsxweb/src/pages/next-chats/chat/sessions.tsxweb/src/pages/next-chats/hooks/use-send-chat-message.tsweb/src/services/chat-completion-stream.ts
| // 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; | ||
| } |
There was a problem hiding this comment.
🩺 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 -250Repository: 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 -400Repository: 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 -500Repository: 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 -600Repository: 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 -500Repository: 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 -500Repository: 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 -700Repository: 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 -250Repository: 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
}));
});
JSRepository: 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)' apiRepository: 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.
| 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', | ||
| ); | ||
| }, |
There was a problem hiding this comment.
🩺 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/srcRepository: 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:
- 1: https://zustand.docs.pmnd.rs/reference/middlewares/devtools
- 2: https://deepwiki.com/pmndrs/zustand/3.2-devtools-middleware
- 3: docs and tests: filter out specific actions from being sent to Redux DevTools pmndrs/zustand#3252
- 4: Fix Devtools action dispatching pmndrs/zustand#3333
🏁 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-chatsRepository: 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),
})
PYRepository: 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.
| 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', | ||
| ); | ||
| }, |
There was a problem hiding this comment.
🎯 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.
| 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.
| 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', | ||
| ); | ||
| }, |
There was a problem hiding this comment.
🎯 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.
| 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.
| 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') }); | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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, | ||
| }); |
There was a problem hiding this comment.
🎯 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.
| 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), |
There was a problem hiding this comment.
🗄️ 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.
| 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.
| const data = payload?.data; | ||
| // The backend signals termination with a boolean `data` field. | ||
| if (typeof data === 'boolean') continue; | ||
|
|
||
| yield data as CompletionChunk; |
There was a problem hiding this comment.
🩺 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.
| 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
left a comment
There was a problem hiding this comment.
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.
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: