Duplicate content when getting connection back after lost connection

Hello, I’m using the y-Partykit server with the monaco editor.
Everything works great until, I loose connection from the server for XYZ reason. (In dev I simulate it by creating some error on the server).
But now, when I remove the error and the server get back online, the initial content is loaded again.
I think I get why it’s happening, but I can’t get my head around how to merge the documents on load.

Thank you for your help guys !

//  ############# FrontEnd  #############
function handleEditorDidMount(editor: any, monaco: any) {
  const provider = new YPartyKitProvider(
    PARTYKIT_HOST,
    roomId,
    yDoc,
    {
      connect: true,
      params: {}
    }
  );
  const monacoBinding = new MonacoBinding(
    yText,
    editor.getModel(),
    new Set([editor]),
    provider.awareness,
  )
}

<Editor key={keyToForceUpdate} options={{ hover: { enabled: false } }}
  onMount={handleEditorDidMount}
  className='w-full h-full' defaultLanguage={'javascript'} language={language.name} theme='vs-dark'
  onChange={handleEditorChange}
/>


// ############# Server  #############
export default class Server implements Party.Server {

  constructor(readonly party: Party.Party) { }

  async onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {

    return await onConnect(conn, this.party, {
      persist: { mode: "snapshot" },
      
      async load() {
        const value = `function check(arr) {
          const res = arr.map(el => el * 2);
          return res;
          }`

        const yDoc = new Y.Doc();
        yDoc.getText("monaco").insert(0, value);
        const encodedState = Y.encodeStateAsUpdate(yDoc);

        const doc = new Y.Doc();
        doc.getText("monaco")
        Y.applyUpdate(doc, encodedState);
        return doc;
      }

    });
  }
}

There are a few old posts that describe the content duplication issue:

https://discuss.yjs.dev/search?q=duplicate

This one might be of help to you:

I’m not sure how the lost connection you describe is triggering it, but it seems similar. There must be some logic that thinks the Doc is empty or does not exist when it actually does. It needs to wait until it syncs to be absolutely sure the Doc hasn’t already been created before initializing it.

@raine Thank you very much !