Skip to content

docs(openspec): propose undo grouping by browser task - #201

Open
ilyamore88 wants to merge 9 commits into
mainfrom
claude/undo-grouping-proposal
Open

ilyamore88 wants to merge 9 commits into
mainfrom
claude/undo-grouping-proposal

Conversation

@ilyamore88

@ilyamore88 ilyamore88 commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

What

Planning only. This PR adds the undo-group-by-task OpenSpec change. It contains no code changes. It is the bottom of a stack: this ← #203 (implementation) ← #191 (clipboard paste proposal).

It changes only UndoRedoManager in core. Local model events are buffered for the current browser task (the end of the task is detected with setTimeout(0)):

  • One event in the task (a keystroke): batched exactly as today, so typing behaviour is unchanged.
  • Several events in the task (Enter split, paste, conversion): the open step is closed, and the task's events start a new step together.
  • undo() and redo() record any events still buffered before acting. destroy() also clears the task timer.
  • Fix: undo/redo of block insertions and removals currently throws, because block events carry one block while the model expects a list. The undo manager wraps the block in a one-item list (design.md, D5).

There is no public API, no event-payload change and no change in the model.

Why

Core undo currently merges only consecutive text inserts or removals in one input. Any action with several model changes becomes several undo steps. Pressing Enter mid-paragraph is two steps today: splitBlock emits TextRemoved and then BlockAdded. The upcoming paste would be three or more. All of these actions run synchronously in one browser task, so grouping by task fixes them in one place, without plugins or tools having to mark their changes.

Notes for reviewers

  • Explicit api.document.group(fn) was the first draft. It was rejected for now: it needs public API, a groupId on model events and about 24 model changes, and it doesn't fix Enter. It stays available if async actions (for example file upload) ever need to be one step (design.md, Alternatives).
  • Typing over a selection. A multi-change step can still be continued by typing under the existing text rule, so "replace selection and keep typing" undoes as one step. Earlier typing never merges into it (D2).
  • Existing quirk the design relies on. The DataNodeAddedEvents that BlockNode dispatches in a microtask during construction have no userId, so undo never records them. That is what keeps redo from throwing AlreadyExistingKeyError. A test pins this (R2).
  • Collaboration. collaboration-manager's undo/redo is unchanged, so multi-change actions still undo in several steps when collaboration is enabled. This is listed as follow-up.
  • The change is not archived. The implementation is in feat(core): group undo steps by browser task #203.

Add the undo-grouping OpenSpec change: api.document.group(fn) and group
ids on model events so a multi-operation action (e.g. paste) is a single
undo step. Prerequisite for clipboard paste (#137).
@ilyamore88
ilyamore88 added this pull request to stack #202 October 10, 2026 11:49
@ilyamore88 ilyamore88 changed the title claude/undo grouping proposal docs(openspec): propose undo grouping Oct 10, 2026
Replace the explicit api.document.group(fn) + groupId design with implicit
grouping in core's UndoRedoManager: local events of one browser task are
buffered and become one undo step when the task made several changes.
No public API, no model or event-payload changes. Rename the change to
undo-group-by-task.
@ilyamore88 ilyamore88 changed the title docs(openspec): propose undo grouping docs(openspec): propose undo grouping by browser task Oct 10, 2026
@ilyamore88
ilyamore88 marked this pull request as ready for review October 10, 2026 12:06
Block events carry a single serialized block while the model's
insertData/removeData expect a list, so undoing any block add/remove throws.
Add the fix (wrap in a one-item list in UndoRedoManager) to the proposal,
design, core spec and tasks.

@gohabereg gohabereg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have an onChange callback exposed to the API. Worth to check how it's going to work if something changes the model through API on onChange call when there's multi-operational batch in progress

Another thing to clarify — is it possible for debounce and task "timers" to conflict with each other? Or debounce timer is only for typing and taks-based batch is only for non-text operations

…up-by-task

Answers review questions on PR 201: changes made by other model listeners
(a future onChange) follow the task they run in (D6), the task timer and
debounce do separate jobs (D7), and listeners that react to undo/redo are
a known limitation (R6). Adds matching spec scenarios and test tasks.
events = #taskEvents; #taskEvents = []
events.length === 1 → existing path: #canAddToBatch(e) ? #batch.push(e)
: (#putBatchToUndo(); #batch = [e])
events.length > 1 → #putBatchToUndo(); #batch = events

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep setTimeout(0), but the task boundary should be explained in JSDoc on #closeTask (and where the timer is scheduled), short and plain: what a "task" is, why a 0 ms timer marks its end (it runs after the current handler and all its microtasks, e.g. DataNodeAdded queued by BlockNode), and why not queueMicrotask or rAF. Also worth noting the known limitation: the timer isn't guaranteed to run before the next input task, so under a busy main thread two keystrokes can land in one task.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. D3 now explains what a task is, why a 0 ms timer marks its end, why not queueMicrotask or rAF, and the busy-main-thread limitation: design.md#L55-L71. Task 2.1 asks for the same in JSDoc on #closeTask: tasks.md#L25.


Other `Changed` listeners on the model, such as a future `onChange` callback exposed through the API, may react to a user's change by changing the model themselves. The manager can't tell those changes apart from the user's, so they are grouped by when they run:

- **Synchronously during dispatch, or in a microtask** (for example after `await`): they run before the task-end timer, so they are buffered with the user's changes and undo in the same step. That is usually what's wanted: a listener that normalizes the user's input is part of the same action.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onModelUpdate already exists: Core subscribes it to the model in the constructor (core/src/index.ts:171), before UndoRedoManager is created in initialize(). A synchronous change made from it is dispatched while the outer event is still being handled, so the manager records it before the user's change, the reverse of the order applied to the model. Undo then reverts the user's change first, and index-dependent changes end up at wrong offsets. Could the test in 3.3 go through onModelUpdate with an index-dependent change, or the manager subscribe to the model first? Also "future onChange" should be dropped.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've missed onModelUpdate since my last commits. Spec is updated: design.md#L86-L106.

- **[R1] Grouping is implicit.** Two unrelated programmatic changes made in the same task become one step, for example a plugin that edits on `core:ready` while the document is initialized. → Acceptable: it's rare, and one step is usually what's wanted. If it matters, it can be revisited with the explicit API.
- **[R2] Redo still depends on block-construction `DataNodeAddedEvent`s not being recorded.** If `userId` forwarding is ever fixed, they would land in the same task and redo would throw `AlreadyExistingKeyError`. → The spec scenario "Block construction events are not recorded separately" becomes an integration test that fails in that case. Its comment names the proper fix: skip data-node events that are covered by a `BlockAdded` in the same step.
- **[R3] Behaviour change for existing multi-change actions** (Enter, block conversion, inline formatting across inputs if it emits several events in one task). → Intended. The spec scenarios cover Enter, and the proposal states the change.
- **[R4] Timer-based tests.** Existing `UndoRedoManager` tests that dispatch events and immediately call `undo()` still pass, because `undo()` records the buffer first (D4). Tests that inspect batches between events must advance timers. → Use Jest fake timers consistently.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't hold. Unit tests like "should NOT batch Added events at non-sequential positions" dispatch several events synchronously and expect separate steps; #203 had to add endTask() to them. UndoRedoManager.integration.spec.ts on main calls updatePluginData two or three times in one task and expects undo to revert only the last call; with task grouping it reverts all of them. Please update R4 and task 1.1, and state in the spec that several plugin-data writes in one task become one step.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote it in design.md#L134-L138.

  • Task 1.1 now adds endTask() to the "should NOT batch" tests and the plugin-data tests: tasks.md#L3-L5.
  • The spec now says several plugin-data writes in one task are one step: spec.md#L66-L69.

## Risks / Trade-offs

- **[R1] Grouping is implicit.** Two unrelated programmatic changes made in the same task become one step, for example a plugin that edits on `core:ready` while the document is initialized. → Acceptable: it's rare, and one step is usually what's wanted. If it matters, it can be revisited with the explicit API.
- **[R2] Redo still depends on block-construction `DataNodeAddedEvent`s not being recorded.** If `userId` forwarding is ever fixed, they would land in the same task and redo would throw `AlreadyExistingKeyError`. → The spec scenario "Block construction events are not recorded separately" becomes an integration test that fails in that case. Its comment names the proper fix: skip data-node events that are covered by a `BlockAdded` in the same step.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Undo of a BlockRemoved depends on this too: insertData → addBlock queues the DataNodeAddedEvents, and they arrive after #isApplying is reset. If userId forwarding gets fixed, they would be recorded as a new step and clear the redo stack. Worth covering in R2 and in test 3.2.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added to R2: design.md#L128-L132. There's also a new spec scenario, spec.md#L61-L64, and a second test in 3.2, tasks.md#L35-L37.

- D3: explain the task boundary, why not queueMicrotask or rAF, and the
  busy-main-thread limitation; require JSDoc on #closeTask
- D6: make UndoRedoManager the model's first Changed listener so changes
  made from onModelUpdate are recorded in the order the model applied them
- R4: name the existing tests that need endTask(), and specify that
  several plugin-data writes in one task are one step
- R2: cover undo of a block removal clearing the redo stack

**Non-Goals:**
- **Grouping across tasks.** Async actions, such as a file paste that waits for an upload, can't be grouped this way.
- **Grouping in `collaboration-manager`'s undo manager.**

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any thoughts on this one? Would we be able to extend the grouping via browser task to the collaboration manager as well?

<!-- none -->

### Modified Capabilities
- `core`: the "Local undo/redo" requirement now groups the local changes of one browser task into one undo step. The new scenarios cover Enter, multi-change tasks around typing, undo while events are still buffered, changes made by other model listeners, and how the task timer and the debounce interact.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating UndoRedoManager in Core's constructor (task 2.5, D6) contradicts the "Initialization order" scenario of "Core composition root" in openspec/specs/core/spec.md, which says the manager is resolved in initialize() after plugins and tools. Please add a MODIFIED delta for that requirement and list it here. Worth stating there that only the core:undo/core:redo subscription stays after plugins, and that destroy() before or during initialize() releases the manager's model listener. Today destroy() takes it from #services, which is only filled in initialize().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a MODIFIED delta for "Core composition root": spec.md#L153-L169.

  • "Initialization order" now says only the core:undo/core:redo subscription waits for initialize().
  • New scenarios: the manager listens to the model first, and destroy() releases it even before initialize() finishes.

Core now keeps the manager in its own field, not in #services: design.md#L111-L112. The delta is listed in the proposal: proposal.md#L35.

- the plugin-data tests in `UndoRedoManager.integration.spec.ts`, which call `updatePluginData` two or three times in one task and expect undo to revert only the last call. With task grouping, undo reverts all of them.

→ Those tests end the task (`endTask()`, which advances fake timers by 0 ms) between changes that stand for separate user actions. Several plugin-data writes in one task becoming one step is intended, and the spec states it.
- **[R5] No grouping when collaboration is enabled.** → Documented. `collaboration-manager` can adopt the same per-task buffering later.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We treat collaboration as an opt-in mode here, however, currently editorjs registers CollaborationManager unconditionally , and that plugin calls preventDefault() on core:undo/core:redo.

In the default bundle (playground, e2e fixture) this manager never acts.

Better mention this here and in the proposal (impact section).


*Alternative considered: `MessageChannel`, which fires sooner.* Not needed: the extra delay is invisible to users, because undo first records the buffered events (D4). `MessageChannel` is also harder to fake in tests.

**Known limitation.** The browser doesn't guarantee that the timer runs before the next input task. When the main thread is busy, two input tasks can run before the timer fires, so their events land in one buffer and are recorded as one task. For two keystrokes, that buffer holds two events, so they start a new step instead of continuing the open typing batch: a word may undo in two parts. A keystroke followed by Enter would undo as one step. This only changes where steps are cut, never which changes are recorded, and it needs a main thread that is busy for longer than one keystroke.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trigger is wider than "a main thread that is busy": the buffer ends when the 0 ms timer runs, so whenever the next input task is already queued, two keystrokes share a buffer and, as "several events", start a new step.

Perhaps we should treat a multi-event buffer as one action only when an event breaks the text chain?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I took your suggestion. A buffer whose events all continue typing is now recorded as typing, and only a buffer that breaks the text chain is one action: design.md#L52-L54. I also widened the limitation: a keystroke and an Enter that share a buffer still undo together: design.md#L79-L84 and spec.md#L26-L34.

#### Scenario: Several changes in one task are one undo step
- **GIVEN** the local user's action makes several model changes synchronously in one task, for example removing text, splitting a block and inserting blocks
- **WHEN** the task has ended and `undo()` is called once
- **THEN** every change made in that task is reverted, and the document equals its state before the task

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Equality with the state before the task does not hold for formatted text, because steps are replayed with plain strings: TextRemovedEvent carries no fragments and insertText joins the preceding formatted node.

So, next sequence

  1. Type **Hello**| world
  2. Enter
  3. Ctrl+Z

gives **Hello world**.

Carry fragments with removed text and restore them, or narrow this scenario to unformatted text and list formatting as a known limitation.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrowed the scenario to unformatted text: spec.md#L16-L19. Formatting is listed as a known limitation, because main behaves the same when it re-inserts removed text: design.md#L179. A test pins your example. Carrying fragments on TextRemovedEvent is a follow-up.

- **Undo of a step that removed a block:** `insertData` → `addBlock` queues the events, and they arrive after `#isApplying` is reset. They would be recorded as a new step, which clears the redo stack, so the undone removal can't be redone.

→ The spec scenario "Block construction events are not recorded separately" becomes integration tests that fail in either case. Their comments name the proper fixes: skip data-node events that are covered by a `BlockAdded` in the same step, and keep ignoring events until the microtasks queued while replaying have run.
- **[R3] Behaviour change for existing multi-change actions** (Enter, block conversion, inline formatting across inputs if it emits several events in one task). → Intended. The spec scenarios cover Enter, and the proposal states the change.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modified on DataIndex/PropertyIndex is recorded, but modifyData ignores it.

Ctrl+Z after api.blocks.updateValue changes nothing and still consumes the step; updateValue + removeText in one task reverts the text only.

Record only replayable events or implement the DataIndex case and scope "every change made in that task is reverted".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The manager now records only events it can replay. Other events still clear the redo stack, so they no longer leave empty undo steps: design.md#L134-L143 and spec.md#L36-L39. updateValue undo is listed as a limitation and follow-up: R8.


- **Code:** `packages/core/src/components/UndoRedoManager.ts` and its `.spec.ts`, plus integration tests with a real model and `BlocksManager`. In `packages/core/src/index.ts`, the manager is created in the constructor instead of in `initialize()`. Existing tests that make several changes in one task and expect separate steps, including the plugin-data integration tests, now end the task between changes. No other package changes, and no public API changes.
- **Collaboration:** `collaboration-manager` keeps its own undo manager, which takes over `core:undo`/`core:redo` when it is registered. That manager is not changed here, so multi-change actions still undo in several steps when collaboration is enabled. It can adopt the same per-task rule later, without any new event fields.
- **Not covered:** asynchronous actions, such as a file paste that waits for an upload, which span several tasks and cannot be grouped this way. If they ever need to be one step, an explicit `api.document.group(fn)` can be added then (see `design.md`, "Alternatives").

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

api.blocks.render() dispatches events without a userId, so they are not recorded and the history is not reset.

Consider case: after render() of another document, crl+z removes a character from the new document; with this change a stale BlockAdded step also inserts an old block instead of throwing.

Suggest a follow-up or a scenario here that clears both stacks when the document is (re)initialized.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed here, since the block-undo fix would otherwise insert a stale block. render() and clear() now call reset(), which clears both stacks, the buffer and both timers: design.md#L145-L151 and spec.md#L41-L44. clear() had the same problem, because it dispatches no events at all.

## MODIFIED Requirements

### Requirement: Local undo/redo
The system SHALL provide `UndoRedoManager`, which batches consecutive model events (debounced) into a single undo step, inverts `Added`/`Removed`/`Modified` events on `undo()`, and responds to cancellable `core:undo`/`core:redo` events. Local events SHALL be grouped by the browser task in which they were dispatched. When a task produced exactly one local event, that event is batched by the existing rule (consecutive text insert/remove in the same input). When a task produced more than one local event, the open batch is closed and the task's events start a new batch together. `UndoRedoManager` SHALL be the model's first `Changed` listener, so the events of a step are recorded in the order the model applied them, including changes that other listeners make while an event is dispatched.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"SHALL be grouped by the browser task in which they were dispatched" is stronger than the mechanism: the group is "events collected between two task-end timer callbacks", which can span several tasks and is cut by undo()/redo()/destroy(). Propose requirement in terms of that buffer.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworded the requirement around the buffer. It's recorded when the task-end timer fires, or earlier on undo()/redo()/destroy(), and it can span several tasks: spec.md#L3-L4 and design.md#L50.

Comment on lines +106 to +109
#### Scenario: The debounce expires while a task is buffered
- **GIVEN** the open batch's debounce timer expires while a local event of the current task is still buffered
- **WHEN** the task ends
- **THEN** the open batch is recorded as its own step, the buffered event starts a new batch, and no event is lost or recorded twice

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Contradicts "Typing keeps its current batching": two keystrokes typed 480 ms apart become two steps whenever the debounce timer is overdue while the second one is buffered.

It is avoidable by canceling the debounce when a task starts buffering; add it and drop this scenario, or keep it and state the consequence.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took the fix you suggested. The first event in an empty buffer cancels the debounce, and the debounce restarts when the buffer is recorded, so an overdue timer can't split typing: design.md#L130-L132. The old scenario is replaced: spec.md#L131-L134.

- Spec: word the requirement around the event buffer, not the task
- D1: record a buffer that only continues typing as typing
- D7: pause the debounce while events are buffered
- D8: record only events the model can replay
- D9: reset history when the document is replaced (render/clear)
- R7/R8: formatting restore and updateValue undo as known limitations
- Core composition root: MODIFIED delta for the new init order and
  destroy() before initialize() finishes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants