ai icon indicating copy to clipboard operation
ai copied to clipboard

Streaming not working on first load / hard refresh (fixes after fast-refresh) on local dev

Open Potrock opened this issue 1 year ago • 4 comments

Description

Text Streaming is not working on first page load / hard refresh on nextjs in development mode. If I send a message asking for a long response after a hard refresh, the network streaming tab shows the chunks coming in, but the messages array from useChat only updates with the first step-start and state: streaming, and then at the very end with the final message.

If I leave the page open and cause an update with Fast Refresh, then streaming works properly until I reload the page.

If the model makes tool calls before responding, the first tool call gets parsed in the messages array with "input-streaming". Then streaming stops being parsed, and the next update to messages contains the full tool call, it's output, any other tool calls and the final text response with state: "done".

Streaming works as expected after a hot/fast reload (If I add a console.log and then save)

Tested on Chrome, Safari, Arc

AI SDK Version

ai-sdk/react: 2.0.0-beta.22 ai: 5.0.0-beta.22 next: 15.3.4

Potrock avatar Jul 17 '25 15:07 Potrock

@dancer following up here from our discussion

Potrock avatar Jul 17 '25 15:07 Potrock

I've isolated the issue a bit further. On initial mount, my chat id is undefined, it is fetched client side. Even though the chat id is ready, and the transport sends the correct payload (with the correct chat id in the body), the streaming is broken. If I hardcode the chat id on the initial load then the streaming works as expected.

Potrock avatar Jul 17 '25 19:07 Potrock

I think what's happening is that undefined chatId causes the sdk to generate it's own chat Id, and the message streaming subscriptions get set up and don't get updated when the chat ID changes later. Simply updating the callback dependency array to rerun on a new chatId (or when it goes from undefined->defined) fixes it.

Potrock avatar Jul 17 '25 23:07 Potrock

Identify issue type

Identified as Bug
Confidence: High

Rationale

This describes a concrete failure in existing useChat streaming behavior caused by stale subscriptions when the chat ID changes after mount.

Evidence

  • On first load or hard refresh, network chunks arrive but useChat only updates at stream start and completion.
  • Streaming begins working after Fast Refresh, indicating inconsistent runtime behavior.
  • The issue was isolated to a client-fetched chat ID changing from undefined to a value; subscriptions appear not to update when the ID changes.
  • Hardcoding the chat ID initially or updating callback dependencies reportedly restores streaming.

lgrammel avatar Jul 22 '26 14:07 lgrammel