ai icon indicating copy to clipboard operation
ai copied to clipboard

Partial streamed message and metadata are lost on useChat error

Open nick-rackauckas opened this issue 1 year ago • 2 comments

Problem

When an error occurs during message streaming in useChat in v5, the partial message being streamed (including any associated messageMetadata) is discarded and not persisted to the messages array. This leads to data loss and an inconsistent state.

Current Behavior

  1. An onError callback (if provided) is executed.
  2. The chat's error state is updated.
  3. The chat's status changes to 'error'.
  4. However, the activeResponse.state.message (the partial message being built) is not pushed to the main messages array.
  5. Consequently, when the activeResponse is cleared in the finally block, all data for the partial message, including any messageMetadata (which might contain important error details), is permanently lost.

Why this is a bug

  • Inconsistent State: Data exists in memory (activeResponse.state.message) but is not persisted to the application's main message store (messages array).
  • Data Loss: Any messageMetadata (e.g., error details, partial content) that was accumulated during the stream is lost, preventing proper error display, logging, or recovery mechanisms.
  • Asymmetric Behavior: During successful streaming, messages are continuously updated in the messages array. On error, this update mechanism abruptly stops without saving the last known good state of the partial message.
  • Conflict with Use Cases: This behavior prevents valid use cases such as displaying error details directly on the affected message in the UI or preserving partial responses for retry logic.

Expected Behavior

When an error occurs during streaming, the partial message (along with its messageMetadata) should be pushed to the messages array before the error state is fully set. This ensures that valuable information about the error context is retained.

Proposed Solution

Modify the catch block in packages/ai/src/ui/chat.ts to save the activeResponse.state.message to the messages array before setting the error status. This would ensure that any metadata set during streaming (including error information) is preserved.

A possible implementation for the catch block could be:

} catch (err) {
  // Ignore abort errors as they are expected.
  if ((err as any).name === 'AbortError') {
    this.setStatus({ status: 'ready' });
    return null;
  }

  // Save the partial message before setting error state
  if (activeResponse && activeResponse.state.message) {
    const replaceLastMessage =
      activeResponse.state.message.id === this.lastMessage?.id;

    if (replaceLastMessage) {
      this.state.replaceMessage(
        this.state.messages.length - 1,
        activeResponse.state.message,
      );
    } else {
      this.state.pushMessage(activeResponse.state.message);
    }
  }

  if (this.onError && err instanceof Error) {
    this.onError(err);
  }

  this.setStatus({ status: 'error', error: err as Error });
}

This change would ensure consistency and prevent data loss when errors occur during useChat streaming, allowing developers to utilize messageMetadata for richer error handling experiences.

nick-rackauckas avatar Jul 25 '25 18:07 nick-rackauckas

Identify issue type

Identified type: Bug
Confidence: High

Rationale: This describes a concrete failure in current SDK behavior during error handling that loses streamed message data and metadata, with a proposed code fix. That fits a bug report rather than a feature request.

Evidence:

  • The issue reports that when useChat streaming errors in v5, the partial streamed message and its messageMetadata are discarded instead of persisted to messages.
  • The described current behavior causes data loss and inconsistent state after activeResponse is cleared.
  • The expected behavior is to preserve the partial message on stream error before setting error status.

lgrammel avatar Jul 02 '26 09:07 lgrammel

I could not reproduce the reported loss of partial message content. Partial content and metadata received before the error are written to messages as each chunk is processed.

There were two related behaviors that may explain the report. In the original v5 implementation, onFinish did not run after an error. Also, metadata emitted after an error chunk was not processed because the client stopped consuming the stream at that chunk. The onFinish behavior has since changed. Metadata ordering after an error is a separate issue, and the proposed catch-block change would not address it.

Closing this issue because the reported messages state behavior does not reproduce. Please provide a minimal stream sequence if the report concerns another case.

n1ckoates avatar Aug 24 '26 22:08 n1ckoates