integrating CodeMirror history with app-wide history

I want to use a CodeMirror editor as a component in a larger web app, where the user can do actions that CodeMirror doesn’t know about. What is the best way to have undo/redo work in a way that makes the CodeMirror/non-CodeMirror distinction invisible to the user?

My first thought was to manage all history in a model I would maintain outside of CodeMirror and just use CodeMirror as much as a kind of view layer. But as I started to implement this, I felt that CodeMirror really wants to be top dog, and I was making things harder for myself by fighting that. So now I am thinking that maybe I should let CodeMirror manage the history for the entire app and be the source of truth even for state that it is not responsible for displaying. It seems like all I would need from CodeMirror is a way to add synthetic events to the history that I would get callbacks on when they were undone or redone. If I had to, I could probably implement this using hidden text on hidden lines in the editor. But is there an API for this sort of thing? Or am I thinking about the issue wrong?

There is no convenient functionality for this, but you might be able to override the "undo" and "redo" commands, wrapping them with your own history functionality, and falling through to the default implementation when appropriate. Something like this:

var original = CodeMirror.commands.undo

CodeMirror.commands.undo = function(cm) {
  if (myOwnEventOnTop())
    undoOwnEvent()
  else
    original(cm)
}