Skip to main content
An agent edits a document with the Office.js facade: WordDocument, body.search, insertText and so on. This page shows how its edit reaches the document that the user has open in the editor, or in Word.

Choose a pattern

Reopen the bytes

Take the bytes out, edit them, and open them again with keepView:
keepView keeps the old pages on screen until the new layout is ready, and keeps the scroll position and the caret. The undo history starts again.

Same session

Run the facade in the editor’s worker, on the session the editor has open. The edit is one step in the user’s undo history. The worker serves the editor on a MessagePort and takes your own messages on self:
The page gives the editor a new port each time it opens a document, and asks the model to repaint after the edit:
recordExternal makes the whole edit one undo step. It waits for the request the editor is busy with, and the next keystroke waits for it. In a live session, the edit goes to the server as one change when the code ends. refreshFromHost() lays out again and keeps the caret where it can.

Rebase

The agent edits on your server while the user keeps typing. The agent and each browser tab are writers of one shared session. The server puts their changes in one order, and each tab rebases the keystrokes it has not sent yet. No edit is lost, and the user does not wait.

Server

The document server does this for you: it orders and rebases the changes, stores each document and runs agent code on it. Run the code below only to keep this on your own server.
For each open document, the server keeps a sequencer (CollabServer) and a mirror (SessionReplica): a copy that every change is written into, so it can give the bytes at any seq.
A change to a part other than the body opens the mirror again, so always read it through replica.session. The new session keeps the revisionAuthor and revisionDate that you set on the old one.

Agent turn

Give the sandbox the bytes, take back the bytes it wrote, and send the difference. collabChange diffs the body token by token, so the change holds only what the agent changed:
The sandbox needs nothing from collab:
If the agent runs the facade in the server process, it can edit a SessionReplica of its own and send await replica.commit() instead of a diff.

Browser tab

Open the bytes of a known seq, then join:
Pass the same block to CollabBinding.start or SessionReplica.start when you drive one directly.

What merges

Show where a writer is

A presence is a selection as body token indices after a given seq. A tab can show the agent’s range, and the agent can read the user’s selection:
  • place moves an older presence forward. It gives undefined until this writer reaches the presence’s seq, and when the presence is more than 256 changes old.
  • presence and place give undefined while the writer holds an edit it did not send. On a SessionReplica, call commit() first.
Positions come in four kinds. Do not use a number from one where another is expected:

When the agent settles a revision

The agent can accept or reject a revision that another author made (TrackedChange.accept() in the sandbox). That edit is its own card:
  • kinds is ["review"]. The card has no revisions, and settles names the ids as the forked document numbers them.
  • Each piece of its preview carries review: { action, kind, author }, and previewText reads it as {accept +forty+} or {reject -thirty-}.
  • It has no text to rewrite.
  • In a header, a footer or a note, the card names the ids of the revisions in that story.
  • Accepting the card settles the revision as Word does: no new revision, one undo step. revert puts the revision back with its author and date.
An edit is not a review:
  • An author who rewrites words inside her own pending insertion edits it. When one author has both the text the card takes out and the text it puts in at that place, the card is text with no settles, under every grouping.
  • An untracked edit that takes letters out of a word and puts letters in replaces the whole word.

Limits

  • Two writers who change the same header, footer, settings part, comment, note, list or style at the same time: the later change wins, and nothing reports it.
  • Presence is for the body only.
  • A remote change to a part other than the body opens the writer’s session again. Read it through replica.session or binding.host. TrackMineOnly reopens as TrackAll.
  • An undo of a style the tab added keeps the style definition, because another writer may use it.
  • w14:paraId and revision w:id values are not in a writer’s id block. Two writers can make the same one.
  • Two concurrent changes to the structure of one table can leave rows with different cell counts.
  • The sequencer does not check a change. Accept changes only from writers you trust.

Suggestion cards

The agent’s edits do not reach the document until the user accepts them. The agent edits a copy with Track Changes on, and the page cuts what it wrote into cards. The user keeps typing while the agent works, and each card follows those edits.
startCollab without send makes a session of one, with no server. If the page is already in a shared session, pass observe to that startCollab call, and an accepted card goes to the other writers like typing. The sandbox edits with tracking on and returns the whole file. A file that Word saved works too:

The fork

fork() takes the bytes and starts to record each edit the document takes. The cards move past those edits. So:
  1. Send run.bytes, nothing else. A saved file or a stored copy does not have the user’s unsaved edits, and the cards would undo them.
  2. Give run.id back with the result: load(run.id, bytes). Several runs can be open.
  3. Do not diff the result against the live document. load diffs against the fork, then moves the cards forward.
  4. Keep the page open from fork() to load(). A run that is not loaded is in the page only. After a loaded run, use save and restore.
  5. One load per run. To revise, start a new run. A new run does not see pending cards of earlier runs, so tell the agent which ones are open. When two runs suggest the same change, accepting one makes the other stale.

How cards are cut

By default, edits in one paragraph are separate cards unless they touch or only spaces part them, so the user can take one and leave the other. Pass group: "paragraph" to make each changed paragraph one card:
New paragraphs inserted together are one card, apart from the paragraph after them, even when that paragraph is edited too. Pass group: "revision" when the agent answers other authors’ changes:
  • Each change of theirs that the agent accepts or rejects is a card of its own. The two halves of a replacement are one change.
  • The agent’s own edits are cut as by default, apart from those answers.
  • An answer and an edit join only when they share text or an insert point, for example when the agent types inside the insertion it rejects.
save keeps the choice, and restore cuts the run the same way. A row, a table or a list still makes one card, whatever the choice.

What a card has

Overlapping cards

overlaps is a hint on a pending card that edits text. It lists the pending cards of runs forked later (r3 after r2) that edit the same text too. The agent may have redlined the text again, or made a second edit that goes with the first: you decide what to show.
  • Accepting both merges the later card as stale.
  • Only cards with revisions of their own count. A card that only comments, or only settles another author’s revisions, does not.
  • Edits elsewhere in the same paragraph do not count. Compare paragraphs for that.
  • Without the editor, spansOverlap(a.spans, b.spans) tests two DeckCards that follow one document.

The paragraphs a card reaches

paragraphs lists the body paragraphs the card reaches now. For an accepted card, that is where it landed.
  • index counts in doc.body.paragraphs order (cells included).
  • paraId is the paragraph’s w14:paraId when the file has one.
  • An edit in a text box names the paragraph that holds the box.
  • The list is empty for a card only in a header, footer, note or other part.
  • Each list() reads the paragraphs again, since an edit above moves the index.
  • Without the editor, redlineCards gives the same field on each RedlineCard, counted in the base (Redline.tokens). new ParagraphIndex(tokens).of(card.spans) counts a DeckCard against the tokens its spans count in.

Card states

Revert an accepted card

revert(id) applies the change that undoes the accept, moved past every edit since. It takes the card back out: its text, its comments and the revisions it settled.
  • Revert in any order: accept A, B and C, then revert only A. What another accepted card shares with it stays.
  • A comment the user put on only the card’s inserted words goes with them, as in Word. A comment that also covers other words stays.
  • It works after restore too: save keeps the change and the document it fits.
revert throws when:
  • the review margin already settled the card’s revisions
  • another accepted card edits inside its text (revert that card first)
  • nothing of the card is left

When the user edited the same text

By default a card merges: if the user deleted the words it replaces, it inserts its words there; if the user typed new words there, both stay. A refuse policy stops that. It gets each pending card and returns a reason, or undefined to let it merge:
list() gives the reason as blocked, accept throws it, and acceptAll skips the card. The policy runs again each time, so an undo can make a card clean again. A tracked deletion by the user is a format change, so it does not add to missing; stale catches it.

Save and restore

save(run.id) gives a SavedRun: the fork, the sandbox’s bytes, your keys and each card’s state. Its base, redlined and at are whole .docx files as Uint8Array. Structured clone keeps them, so you can put a SavedRun in IndexedDB as it is:
JSON.stringify does not keep the bytes. For a server, a database column or any other text store, use savedRunToJSON, which writes the files in base64, and savedRunFromJSON to read the text back:
restore also reads a run that went through plain JSON.stringify, or that holds its files as base64 text or number arrays. It throws a TypeError that names the field when a field is not a .docx. Each card comes back in the state it was saved in, also when two cards hold pieces of one revision: You may change SavedCard.state in a stored run, for example when the user dismisses a card while the editor is closed: A SavedRun holds up to three whole files (base, redlined, at) plus one change per accepted card (SavedCard.inverse). A run saved before 0.0.17 has no inverse: revert on its accepted cards rejects their revisions by id, and throws on a card without revisions.

Rewrite a card

Show card.text.after in a text box, and accept what the user wrote:
The card lands as a redline from the document’s text to the user’s, cut by words as Word’s compare cuts them, and signed by the agent. A word deleted from another author’s insertion is the agent’s deletion inside it, as in Word. accept throws on a line break and on text equal to the document’s. The same works in a header, a footer, a footnote or an endnote: a card that changes text in one paragraph there has text, and the rewrite lands in that story. A card that edits two stories, or a story and the body, has no text.

Reword or drop a card’s comment

card.preview.comments holds the text of each comment the card adds. Pass comment to word it your way (one paragraph per line), or null to keep the edit without the comment:
One text replaces every comment the card adds and keeps the first run’s look. When a card adds more than one comment, pass an array with one entry per preview.comments entry, in that order. Each entry is the new text, or null to drop that comment alone:
  • A dropped comment takes its anchors and the comment parts it alone made.
  • save keeps the wording, so a restored card shows it.
  • comment and text can go together.
accept throws when:
  • the card adds no comment
  • the array has the wrong length
  • every comment is dropped from a card that is only comments. Reject that card instead.
After the accept, the card’s comments are ordinary comments: the user edits, answers or deletes them in the margin (editComment, replyComment, deleteComment). The card follows:
  • preview.comments reads them as the document has them, and a restore does too.
  • A revert takes them out as they are. The card then waits with the user’s words, or without a deleted comment, and the next accept puts that back.
  • Replies go out with the comment.

Sign an accepted card as the reviewer

By default an accepted card stays the agent’s tracked change. Pass sign to make it the reviewer’s: its revisions and the comments it adds take the editor’s author (model.revisionAuthor) and the time of the accept. Other authors’ revisions in the card keep their names.
accept throws when sign: true and the editor has no author.

Answer another author’s change yourself

A review card accepts or rejects revisions of another author (settles). The user can answer them in place of the agent:
To answer only some of them, pass { choice, ids } with ids from the card’s theirs. Those take choice. The rest keep the agent’s answer and its edits on them, or stay as they are when the agent did not answer them. accept throws on an id that is not in theirs, and on an empty list:
How the answer lands:
  • Marks it adds are the reviewer’s (sign, else model.revisionAuthor).
  • It goes in the header, footer or note the card edits.
  • A format change can only be accepted.
  • Undo, revert, save and restore work as for any accept.
The agent’s own edits in the card:
  • They land as they are, except edits of words the answer takes out where the agent kept them: those go, with any words the agent typed beside them.
  • Under group: "revision" such edits are another card, so accept throws while that card is accepted, and that card’s accept throws while the answer is in.
  • A card that settles nothing but edits on or beside another author’s change (its theirs) takes review too: the answer replaces the agent’s edits on that change, and its other edits land.
accept throws on a card that settles nothing and has no theirs, and when review comes with text or comment.

Edit a card any way you like

For a change that text, comment and review do not cover, edit the card yourself. draft(id) gives the document with the card in, as a file. Edit it with any Word API, with Track Changes on as the reviewer, and give it back to accept:
The card lands as the edited file reads, as one undo step: the agent’s change, then the host’s edits, each mark with the author the file gives it. revert and undo take all of it back out. The user can keep typing while the host holds the draft: the edits are carried past what the document takes meanwhile. Settings a save writes (rsids, the Track Changes switch) stay out.
  • Once reverted, the card waits as it landed, with the host’s edits in it
  • To reword text the card inserts, edit as the card’s author (revisionAuthor set to the agent’s name), with Track Changes on and sign at the accept. Text an author deletes from their own insertion goes with no deletion mark, as in Word, and sign makes every mark the reviewer’s. As the reviewer, the replaced words stay as a deletion inside the new text
  • With Track Changes off, every edit lands untracked: inside the card’s insertion that reads the same, but an edit to text the card does not insert changes the document with no mark
  • save keeps how the card read (SavedCard.drafted), so a restored card shows the host’s version
  • accept throws on a draft draft() did not give for that card, and when draft comes with text, comment or review
  • sign signs every new mark the card lands, the host’s too; other authors’ revisions keep their names
  • Each draft is a whole file: about 50 ms for an 800-paragraph form, about 2 s for a 4,600-paragraph contract

Your own ids

To show why the agent made an edit, map its revision ids to your key in the sandbox, and pass the map to load:
The page can join your edits into one card, so a card can hold several keys. It does not cut one card finer, because each card must apply alone. save and restore keep the keys.

Limits

  • Pending cards are not in the document. Keep the SavedRun with the document to show them again.
  • Word gives new w:id values to revisions when it saves the file. After that, a restored accepted card cannot find its revisions, and your keys do not match.
  • A card rejected in the review margin and then edited can read accepted. A format card accepted in the margin and then formatted again can read rejected.
  • When the agent deletes across another author’s tracked deletion (a counterparty’s), that deletion stays theirs. Formatting over another author’s insertion is signed by the agent.
  • The agent’s edits and its settles are separate cards unless they touch. revert on a card that does both takes out its edits and puts the settled revisions back.
  • A revision in the sandbox’s file that marks nothing (an empty w:ins a tool left) makes no card.
  • Keep tracking on in the sandbox. Untracked edits give coarse cards (a one-word change can replace its paragraph), and they land untracked.

Word add-in

The same cards work when the user reviews in Word. WordReview from @reductoai/docx/redline follows Word’s file. Word has no live change feed, so there is no fork(): the fork is the file you read before the agent starts, and WordReview diffs each file you give it against the last one.
Each edit replaces a run of paragraphs, a table or a cell’s content with insertOoxml “Replace”. The OOXML holds the agent’s tracked markup and the styles, lists, pictures, links, comments and notes it uses, so applyWordEdits turns Word’s tracking off while it replaces.

Limits

  • WordReview cannot tell when the user undid an accept (Ctrl+Z removes the card’s revisions in one step) or settled it in the margin. The card stays accepted.
  • It has no revert, no text rewrite, no refuse policy and no save.
  • A card that changes a style, list or comment that Word already has is unsupported.
  • An accept replaces whole paragraphs, so paragraph ids and Word’s state inside them change.