Back to the blog

October 12, 2026 · 7 min · engineering · product · companion

.md

Build AI Roleplay Chat with Edits, Rewinds and Separate Story Branches

Build AI roleplay chat with distinct edit, regenerate, rewind and branch actions, consistent checkpoints, and guards against canceled or stale replies.

Build AI roleplay edits and rewinds around an application-owned story timeline, not a mutable chat transcript. Keep accepted messages immutable, give each branch its own current endpoint and revision, and construct the next response only from that branch's accepted path. Editing an earlier choice must exclude its later consequences. Canceling generation must also prevent a late reply from becoming part of the story.

Part 4 of The 2027 AI Character Business Playbook. Give players control of the story they may eventually pay to keep. This series turns consumer-character demand into specific experiments and implementation decisions; revenue targets are scenarios, not promised results.

Give four controls four different meanings

A player correcting a sentence is not necessarily asking to lose an evening's story. Make the consequence visible before saving. The following semantics are a proposed product design, not a description of every roleplay app.

  • Edit replaces one accepted message with a new version. Later messages leave the active path; offer to preserve the old continuation as a separate branch.
  • Regenerate creates another candidate reply to the same parent. Candidates stay outside accepted history until selected. Switching an earlier reply also retires its downstream continuation.
  • Rewind moves the active endpoint to a selected message, keeping that message and excluding everything after it. State that boundary explicitly in the confirmation.
  • Branch creates a separately named continuation from an accepted point. The original keeps its endpoint. Editing the copy must never mutate the shared prefix.

AI Dungeon's official guide makes a useful distinction: its Erase to Here removes later actions and outputs, while the erasure itself can be undone or redone. Editing history and story position are different things. That documented interaction supports the distinction; it does not establish AI Dungeon's database architecture or promise identical behavior elsewhere.

Trace one changed choice through the whole scene

Consider an original coastal mystery for adults. Mira, a 36-year-old lighthouse keeper, meets Jules, a 32-year-old cartographer played by the user. Mira offers a sealed letter. The question is whether Jules opens it, not whether the model can write an atmospheric lighthouse description.

  1. Branch A accepts e1: Mira offers the letter. It then accepts e2: Jules says, ‘I open the letter.’
  2. A accepts e3: the letter reveals the tide gate code. Then e4 records Jules entering it, and e5 records the gate opening. A's checkpoint says the code is known and the gate is open.
  3. Jules chooses Save another version. Branch B initially points to e5, sharing A's immutable events. Jules edits e2 to e2b: ‘I return the letter, still sealed.’
  4. B now contains only e1 and e2b. Events e3 through e5 remain accessible in A, but are not B's past. B must rebuild its checkpoint without the code or the opened gate.
  5. A valid B continuation has Mira take back the envelope and ask which route Jules wants. ‘We walk through the gate you opened’ fails because it imports A's consequence.

Show the result as ‘Letter returned — alternate version,’ with the original still selectable. Do not make users inspect internal identifiers to understand whether their first ending survived.

Store an accepted path, then derive its context

Use immutable message events with an identifier, parent and content. A branch record points to its accepted head and carries a monotonically increasing revision. An edited event keeps the replaced event's parent; it does not overwrite the old text. Resolve membership by walking the head's ancestry, not by collecting every message created before a timestamp.

Anchor each summary or checkpoint to both its branch and the exact accepted head it summarizes. Before using it, verify that head remains on the current path. Then append only accepted descendants after that checkpoint. A checkpoint beyond the edited choice is ineligible even if its summary looks plausible. Start without it and rebuild from an earlier valid point.

Apply the same rule to extracted facts, search results and pending summary jobs. Filter eligibility before retrieval output enters the prompt; invalidating a cache later is insufficient. Keep story knowledge branch-scoped rather than attaching ‘Jules knows the code’ to the account. Global presentation preferences may be shared, but they are not story events.

Reject stale edits and canceled generations at commit

Two tabs can edit the same branch revision. Authorize the branch against the signed-in account, then compare the expected revision inside the write transaction. One edit wins; the other receives a conflict and retains its unsaved text. Never silently apply the loser to the winner's new story.

A generation job also captures branch, revision, parent head and a unique request identifier. Starting a replacement job advances the revision and replaces the pending request. Canceling clears that request and advances the revision, even when the story head stays unchanged. Abort the network work as well, but treat that as cleanup rather than your correctness guarantee.

This SQL is the exact commit predicate exercised by the article's local SQLite fixture, not an RTA endpoint. Require one changed row, insert the accepted event in the same transaction, and roll back both if either step fails. Account authorization and request validation belong before this storage operation.

UPDATE branch SET head = ?, revision = revision + 1, pending = NULL WHERE id = ? AND revision = ? AND head = ? AND pending = ?

Checking only the head is insufficient: a user can rewind away and return to the same event while an old request is still running. The revision distinguishes those visits. Streamed text remains provisional until acceptance; an obsolete stream cannot create a checkpoint, trigger a story consequence or show a saved confirmation.

Keep live calls attached to the chosen version

Realtime Avatar provides a developer API, SDK and Studio for live characters, not a packaged roleplay app with edit history. Your application owns persistence, branches and consumer pricing. Your server supplies character instructions and the selected branch's context when starting a call. New sessions do not automatically inherit story memory.

After a rewind or branch switch, end the old call and start a fresh one with rebuilt context. A database change cannot remove facts already supplied to a running conversation. Bind optional post-call transcript delivery to the originating branch and revision; a late transcript must not append itself to whichever branch the user currently has open.

Test the timeline before testing the prose

An article-local SQLite fixture passed nine deterministic cases covering branch isolation, checkpoint invalidation, competing edits, late generation, cancellation, replacement requests, returning to an earlier head, duplicate completion and transaction rollback. Replacing the commit guard with a head-only check made three cases fail: cancellation, replacement requests and returning to the same head. These are ordered interleavings on an in-memory database, not simultaneous browser sessions or a deployed integration.

Next, run the lighthouse scene through the actual interface. Inspect both the assembled context and the visible reply. Reopen A and B after reconnecting, deliver an old completion, and confirm the gate stays open only in A. Those application and model checks remain acceptance criteria, not reported results here.

Frequently asked questions

Should a typo edit invalidate later replies?

By default, yes. A small textual change can alter meaning. A display-only correction is possible, but label it explicitly: the original accepted content still governs the story.

Is rewind the same as deleting my data?

No. This design retains alternate history. Offer deletion separately and explain what happens to branches, derived summaries and retained copies. Do not label a rewind as erasure.

Can branches share summaries?

Only when you explicitly verify the same immutable prefix. Start with branch-specific checkpoints; never reuse a summary just because both versions feature the same character.

Do I need an avatar to build this?

No. Prove editing and replay in text first. Add voice or video when speaking a role improves the experience, while keeping the same application-owned timeline authoritative.

Build the next part of the business

Ready to build? The Next.js guide provides a public starter ZIP. Run it locally with your own server-side key; calls consume credits and the example caps each call at 60 seconds. Its local-only authorization must be replaced with real sign-in, balance checks and persisted session ownership before public deployment. A downloaded example is not yet a tested consumer product.

Meet the live avatars. Hold the first conversation.

Enter the studio