/** * Tests for the buffer sync: a fake engine with real versioning answers * `buffer.edit` and `buffer.get` after random delays and makes edits of its * own (as a reload from disk or the control channel would). Bursts of local * keystrokes must all reach the engine, and both sides must converge. */ import { describe, expect, it } from "vitest"; import { BufferSync, type BufferInfo, type EditParams, type EditResult, type SyncTransport, } from "../../src/components/editor/bufferSync"; import type { RunResult } from "../../src/ipc"; /** Deterministic pseudo-random numbers (mulberry32). */ function rng(seed: number): () => number { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** A fake engine buffer with the engine's edit protocol. */ class FakeEngine implements SyncTransport { text: string; version = 1; readonly lineEnding: string; /** Answers waiting to be delivered. */ private queue: (() => void)[] = []; /** Versions to report through `bufferChanged`. */ events: number[] = []; editCalls = 0; staleRejections = 0; constructor(text: string, lineEnding = "lf", private random: () => number = Math.random) { this.text = text; this.lineEnding = lineEnding; } info(): BufferInfo { return { id: 1, path: "a.txt", text: this.text, version: this.version, dirty: this.version !== 1, lineEnding: this.lineEnding, }; } edit(params: EditParams): Promise> { this.editCalls += 1; return this.later(() => { if (params.baseVersion !== this.version) { this.staleRejections += 1; return { ok: false, error: { code: "stale_version", message: "stale" } }; } let out = ""; let pos = 0; for (const e of params.edits) { expect(e.from).toBeGreaterThanOrEqual(pos); expect(e.to).toBeLessThanOrEqual(this.text.length); out += this.text.slice(pos, e.from) + e.insert; pos = e.to; } this.text = out + this.text.slice(pos); this.version += 1; this.events.push(this.version); return { ok: true, value: { id: 1, version: this.version, dirty: true } }; }); } get(): Promise> { return this.later(() => ({ ok: true, value: this.info() })); } /** * An edit made outside the editor: inserts `text` at a line start. * * @param text - inserted text. * @param line - 0-based line; random when omitted. */ external(text: string, line?: number): void { const starts = [0]; for (let i = 0; i < this.text.length; i += 1) { if (this.text[i] === "\n") { starts.push(i + 1); } } const at = starts[line ?? Math.floor(this.random() * starts.length)] ?? 0; this.text = this.text.slice(0, at) + text + this.text.slice(at); this.version += 1; this.events.push(this.version); } /** Queues an answer; {@link step} delivers queued answers in random order. */ private later(answer: () => T): Promise { return new Promise((resolve) => { this.queue.push(() => { resolve(answer()); }); }); } /** Delivers one queued answer, if any. */ step(): boolean { if (this.queue.length === 0) { return false; } const index = Math.floor(this.random() * this.queue.length); const [answer] = this.queue.splice(index, 1); answer?.(); return true; } } /** Lets promise callbacks run. */ async function tick(): Promise { for (let i = 0; i < 5; i += 1) { await Promise.resolve(); } } /** * Delivers every pending answer and event until the sync is idle. * * @param engine - the fake engine. * @param sync - the sync under test. */ async function drain(engine: FakeEngine, sync: BufferSync): Promise { for (let i = 0; i < 10_000; i += 1) { const events = engine.events.splice(0); for (const v of events) { sync.notifyVersion(v); } const stepped = engine.step(); await tick(); if (!stepped && events.length === 0 && !sync.pending) { return; } } throw new Error("sync did not settle"); } /** * The engine text with CodeMirror's line breaks, for comparison. * * @param text - engine text. */ function normalised(text: string): string { return text.replace(/\r\n?/g, "\n"); } describe("BufferSync", () => { it("sends local edits with the base version and tracks versions", async () => { const engine = new FakeEngine("hello\n"); const sync = new BufferSync(engine.info(), [], engine); sync.dispatch({ changes: { from: 5, insert: " world" } }); expect(sync.pending).toBe(true); await drain(engine, sync); expect(engine.text).toBe("hello world\n"); expect(sync.baseVersion).toBe(2); expect(sync.pending).toBe(false); }); it("applies a change made in the engine", async () => { const engine = new FakeEngine("one\ntwo\n"); const sync = new BufferSync(engine.info(), [], engine); engine.external("zero\n", 0); await drain(engine, sync); expect(sync.state.doc.toString()).toBe("zero\none\ntwo\n"); expect(sync.baseVersion).toBe(engine.version); }); it("keeps the local cursor when a remote change lands before it", async () => { const engine = new FakeEngine("abc\n"); const sync = new BufferSync(engine.info(), [], engine); sync.dispatch({ selection: { anchor: 2 } }); engine.external("x\n", 0); await drain(engine, sync); expect(sync.state.selection.main.head).toBe(4); }); it("loses no keystroke in a burst with stale versions and remote edits", async () => { const random = rng(42); const engine = new FakeEngine(" { const random = rng(7); const engine = new FakeEngine("a\r\nbb\r\nccc\r\n", "crlf", random); const sync = new BufferSync(engine.info(), [], engine); for (let i = 0; i < 300; i += 1) { const len = sync.state.doc.length; const from = Math.floor(random() * (len + 1)); const to = Math.min(len, from + Math.floor(random() * 3)); const insert = random() < 0.3 ? "\n" : random() < 0.5 ? "é😀" : ""; sync.dispatch({ changes: { from, to, insert } }); if (random() < 0.1) { engine.external(`r${String(i)}\r\n`); } if (random() < 0.6) { engine.step(); } if (random() < 0.3) { for (const v of engine.events.splice(0)) { sync.notifyVersion(v); } } await tick(); } await drain(engine, sync); expect(sync.state.doc.toString()).toBe(normalised(engine.text)); expect(engine.text.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/); }); it("drops local changes and reports when the engine refuses them", async () => { const engine = new FakeEngine("keep\n"); const errors: string[] = []; const refusing: SyncTransport = { edit: () => Promise.resolve({ ok: false, error: { code: "invalid_params", message: "bad" } }), get: () => engine.get(), }; const sync = new BufferSync(engine.info(), [], refusing, (e) => errors.push(e.code)); sync.dispatch({ changes: { from: 0, insert: "lost " } }); await drain(engine, sync); expect(errors).toEqual(["invalid_params"]); expect(sync.state.doc.toString()).toBe("keep\n"); }); it("idle resolves after the engine confirmed every change", async () => { const engine = new FakeEngine(""); const sync = new BufferSync(engine.info(), [], engine); sync.dispatch({ changes: { from: 0, insert: "x" } }); let done = false; void sync.idle().then(() => { done = true; }); await tick(); expect(done).toBe(false); await drain(engine, sync); await tick(); expect(done).toBe(true); }); });