Editor state selection not resolving positions after setSelection transaction

I have a complex transaction in place (delete+insert+setSelection):

    if (dispatch) {
		let trx = state.tr.delete($pos.before(), $pos.after());

		const index = ref.$to.index(1);
		const siblingsCount = speakerNode.node.childCount;

		let insertPos = 0;
		let selectionOffset = 0;

		if(index == 0) {
			if(siblingsCount == 1) {
				trx = state.tr.delete($pos.before()-1, $pos.after()+1); //delete wrapping speaker node
			}

			insertPos = $pos.before() - 1;
			selectionOffset = 1;
		} else if (index > 0 && index < siblingsCount - 1) {
			insertPos = $pos.before();
			selectionOffset = 2;
		}
		else {
			insertPos = $pos.before() + 1;
			selectionOffset = 1;
		}

		const newNode = schema.node('richparagraph', null, paragraphNode.content);

		trx = trx.insert(insertPos, newNode);
		const selection = TextSelection.create(state.doc, $pos.parentOffset+insertPos+selectionOffset);
		trx = trx.setSelection(selection);

		dispatch(trx.scrollIntoView());
		return true;

	}

What it does is lifting the node up while converting to another node type (the one compatible with the schema). I then have a custom dispatcher that would report the document selection to the outside users:

    dispatchTransaction = function(tr) {
				const updatedState = this.state.apply(tr);
				this.updateState(updatedState);

				const posNum = updatedState.selection.$to.pos;

				const ref = updatedState.doc.resolve(posNum);

				//console.log(updatedState.doc);

				const absolutePos = ref.pos;
				const speakerNode = commands.findSpeakerNode(ref);

				const channelId = speakerNode ? speakerNode.node.attrs.author : -1;

				if(self.selectionCallback) {
					self.selectionCallback(absolutePos, channelId);
				}

				if (self.updateCallback) {
					self.updateCallback();
				}
			};

So what happens is state.selection will contain resolved positions ($anchor, $head, $to and $from) that are resolved relative to a previous version of a document. That results in all the followup commands to rely on incorrect state causing all sorts of problems. I can probably do a dirty hack - re-resolve the position relatively to a new document and then manually update state.selection but in my opinion that shouldn’t happen - once the transaction has been applied - the updated state’s selection should contain positions resolved relative to the new state

The problem is that you’re creating a selection from the original document, rather than trx.doc—as selection’s document should match the state/transaction document.

Thanks, that fixed it