From 82d13207a9bb1de79fb899fdc571b3d6174d9ed6 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 24 Nov 2026 21:19:16 +0800 Subject: [PATCH] fix(editor): keep saving edits when touched ranges are out of date (#5638) A range past the end of the document in ModifiedRanges made ChangeSet.mapPos throw inside onLocal, after the edit reached the backend but before the document was marked dirty, so autosave never wrote a reopened external file. Such ranges are now dropped with a warning. Fixes #5528. --- src/editor/core/model/document.test.ts | 20 +++++++++++++++++++- src/editor/core/model/document.ts | 7 ++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/editor/core/model/document.test.ts b/src/editor/core/model/document.test.ts index c86306a9d3..23ef30d0b1 100644 --- a/src/editor/core/model/document.test.ts +++ b/src/editor/core/model/document.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { EditorState, StateEffect } from "@codemirror/state"; +import { ChangeSet, EditorState, StateEffect } from "@codemirror/state"; import { showTooltip, type Tooltip } from "@codemirror/view"; import { indentUnit, language as languageFacet } from "@codemirror/language"; import { HEAVY_LIMIT, onEditorEvent, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api"; @@ -675,6 +675,24 @@ describe("DocumentManager + slots", () => { }); }); +describe("modified ranges", () => { + it("drops a range past the end instead of throwing out of the edit", () => { + const m = new ModifiedRanges(); + m.ranges = [ + [2, 4], + [580, 587], + ]; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + m.add(ChangeSet.of({ from: 0, insert: "ab" }, 10)); + expect(m.ranges).toEqual([ + [4, 6], + [0, 2], + ]); + expect(warn).toHaveBeenCalledOnce(); + warn.mockRestore(); + }); +}); + describe("save cleanup", () => { it("keeps the caret line and untouched lines", () => { const state = EditorState.create({ doc: "a \nb \nc " }); diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index ba166b5e9c..d456a6aeb5 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -146,7 +146,12 @@ export class ModifiedRanges { map(changes: ChangeSet) { if (this.all) return; - this.ranges = this.ranges.map(([a, b]): [number, number] => [changes.mapPos(a, -1), changes.mapPos(b, 1)]); + // A range past the end belongs to another version of the text; mapping it would throw out of the + // edit (before the document is marked dirty, so the edit would never be saved). Drop it instead. + const kept = this.ranges.filter(([, b]) => b <= changes.length); + if (kept.length < this.ranges.length) + console.warn(`modified ranges past the end (${changes.length}) dropped`, this.ranges.length - kept.length); + this.ranges = kept.map(([a, b]): [number, number] => [changes.mapPos(a, -1), changes.mapPos(b, 1)]); } add(changes: ChangeSet) {