plate icon indicating copy to clipboard operation
plate copied to clipboard

AIMenu: Cannot read properties of undefined (reading '0') during streaming

Open ribantech opened this issue 4 months ago • 2 comments

Description

I'm generating long form (more than 3000 word) content using openai api with streaming enabled. Streaming is getting started, but in between while the client waits for the messages from Openai, it breaks the flow with the below exception.

Open ai model - o4-mini maxTokens - 100000

React.useEffect(() => {
    if (streaming) {
      const anchor = api.aiChat.node({ anchor: true }); 
      setTimeout(() => {
        const anchorDom = editor.api.toDOMNode(anchor![0])!;   // ---> failing here
        setAnchorElement(anchorDom);
      }, 0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [streaming]);

Reproduction URL

No response

Reproduction steps

1. Create a Plate editor with Markdown & AI plugin
2. In the api/ai/command, configure streaming with below model configuration
Model - o4-mini
maxToken - 100000
3. Set the prompt to write a blog post with minimum 3000 words.

Plate version

49.0.2

Slate React version

latest

Screenshots


Logs


Browsers

No response

ribantech avatar Jul 29 '25 07:07 ribantech

Hi @ribantech! I'm Dosu and I’m helping the plate team.

The error happens because during streaming, api.aiChat.node({ anchor: true }) can return undefined or an empty array—especially when the editor state is changing quickly or the anchor node isn't available yet. Accessing anchor![0] without checking if anchor exists or has elements will throw this error.

To fix it, add a defensive check before using anchor[0]:

React.useEffect(() => {
  if (streaming) {
    const anchor = api.aiChat.node({ anchor: true });
    setTimeout(() => {
      if (anchor && anchor.length > 0) {
        const anchorDom = editor.api.toDOMNode(anchor[0]);
        setAnchorElement(anchorDom);
      }
    }, 0);
  }
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [streaming]);

Recent Plate AI plugin updates improved streaming and anchor handling, making these errors less likely—especially with long-form content and markdown streaming. If you’re not on the latest Plate version, consider upgrading for better stability and edge-case handling [changelog].

In general, always check for undefined or empty values when working with async or streaming APIs in Plate to avoid similar runtime errors.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

dosubot[bot] avatar Jul 29 '25 07:07 dosubot[bot]

Can you paste the chunks? you can find it in dev tools network tab. so that I can check from it.

felixfeng33 avatar Jul 29 '25 09:07 felixfeng33