From 52ac7bf7b0feaf8ee99ec32c1678b99fbdddee3c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 27 Oct 2026 20:03:27 -0500 Subject: [PATCH 1/3] fix(id-web): serialize AutoSaveManager saves + stale-completion guard (#1440) Extract AutoSaveManager from main.ts into src/auto-save.ts (identity-refresh precedent) and serialize its saves: - saveInFlight latch: at most one saveFn() call in flight; a save requested during a flight coalesces into exactly one follow-up on settle. - Edit-generation guard: a completion only marks the document saved when no edit arrived after that save started; otherwise one follow-up runs. - 429 retry participates in the same serialization: requests during the backoff coalesce into the scheduled retry instead of saving early or cancelling it. - A throwing saveFn becomes a generic error result instead of wedging the latch / state at saving forever. Regression tests (src/auto-save.test.ts) drive the manager with a deferred saveFn: edit-during-flight follow-up + max-in-flight, stale completion, 429 retry serialization, saveNow behaviour. --- pkgs/id/web/src/auto-save.test.ts | 153 +++++++++++++++++++ pkgs/id/web/src/auto-save.ts | 239 ++++++++++++++++++++++++++++++ pkgs/id/web/src/main.ts | 187 +---------------------- 3 files changed, 393 insertions(+), 186 deletions(-) create mode 100644 pkgs/id/web/src/auto-save.test.ts create mode 100644 pkgs/id/web/src/auto-save.ts diff --git a/pkgs/id/web/src/auto-save.test.ts b/pkgs/id/web/src/auto-save.test.ts new file mode 100644 index 0000000000..38dea5ea16 --- /dev/null +++ b/pkgs/id/web/src/auto-save.test.ts @@ -0,0 +1,153 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AUTOSAVE_DEBOUNCE_MS, AutoSaveManager, type SaveResult } from "./auto-save"; + +/** A saveFn whose promises resolve only when the test says so. */ +function deferredSaveFn() { + const resolvers: Array<(result: SaveResult) => void> = []; + let calls = 0; + let inFlight = 0; + let maxInFlight = 0; + const fn = () => { + calls++; + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + return new Promise((resolve) => { + resolvers.push((result) => { + inFlight--; + resolve(result); + }); + }); + }; + return { + fn, + get calls() { + return calls; + }, + get maxInFlight() { + return maxInFlight; + }, + /** Resolve the oldest outstanding save with the given result. */ + resolveNext(result: SaveResult) { + const resolve = resolvers.shift(); + if (!resolve) throw new Error("no save in flight to resolve"); + resolve(result); + }, + }; +} + +/** Flush pending microtasks (save completions, follow-up scheduling). */ +async function flush() { + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); +} + +describe("AutoSaveManager serialization (#1440)", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("runs exactly one coalesced follow-up when edits arrive during a save", async () => { + const save = deferredSaveFn(); + const mgr = new AutoSaveManager(save.fn); + + mgr.onContentChange(); + await vi.advanceTimersByTimeAsync(AUTOSAVE_DEBOUNCE_MS); + expect(save.calls).toBe(1); + expect(mgr.state).toBe("saving"); + + // Two edits during the flight; their debounce fires mid-flight too. + mgr.onContentChange(); + mgr.onContentChange(); + await vi.advanceTimersByTimeAsync(AUTOSAVE_DEBOUNCE_MS); + expect(save.calls).toBe(1); // still serialized — no concurrent save + + save.resolveNext({ ok: true }); + await flush(); + expect(save.calls).toBe(2); // exactly one follow-up + expect(save.maxInFlight).toBe(1); + + save.resolveNext({ ok: true }); + await flush(); + expect(mgr.state).toBe("saved"); + await vi.advanceTimersByTimeAsync(10_000); + expect(save.calls).toBe(2); // no further saves — the follow-up coalesced both edits + }); + + it("never marks newer edits saved when a stale save completes", async () => { + const save = deferredSaveFn(); + const mgr = new AutoSaveManager(save.fn); + + mgr.onContentChange(); + await vi.advanceTimersByTimeAsync(AUTOSAVE_DEBOUNCE_MS); + expect(save.calls).toBe(1); + + // Edit arrives while save #1 is in flight; its debounce is still pending + // when the stale save resolves (the #1440 scenario B shape). + mgr.onContentChange(); + save.resolveNext({ ok: true }); + await flush(); + expect(mgr.state).not.toBe("saved"); + + // The follow-up save covers the newer edit; only its completion may + // move the indicator to "saved". + expect(save.calls).toBe(2); + save.resolveNext({ ok: true }); + await flush(); + expect(mgr.state).toBe("saved"); + }); + + it("serializes the 429 retry: edits during backoff coalesce into the retry", async () => { + const save = deferredSaveFn(); + const mgr = new AutoSaveManager(save.fn); + + mgr.onContentChange(); + await vi.advanceTimersByTimeAsync(AUTOSAVE_DEBOUNCE_MS); + expect(save.calls).toBe(1); + + save.resolveNext({ ok: false, retryAfterMs: 5000 }); + await flush(); + expect(mgr.state).toBe("rate-limited"); + + // Edit during the backoff: its debounce must not start an early save, + // and must not cancel the pending retry either. + mgr.onContentChange(); + await vi.advanceTimersByTimeAsync(AUTOSAVE_DEBOUNCE_MS); + expect(save.calls).toBe(1); + + // The retry fires on schedule and captures the latest document. + await vi.advanceTimersByTimeAsync(3000); + expect(save.calls).toBe(2); + expect(save.maxInFlight).toBe(1); + + save.resolveNext({ ok: true }); + await flush(); + expect(mgr.state).toBe("saved"); + await vi.advanceTimersByTimeAsync(10_000); + expect(save.calls).toBe(2); + }); + + it("saveNow saves immediately when idle and is a no-op while saving", async () => { + const save = deferredSaveFn(); + const mgr = new AutoSaveManager(save.fn); + + mgr.onContentChange(); + mgr.saveNow(); // immediate — no debounce wait + await flush(); + expect(save.calls).toBe(1); + expect(mgr.state).toBe("saving"); + + mgr.saveNow(); // already saving — unchanged no-op behaviour + await flush(); + expect(save.calls).toBe(1); + + save.resolveNext({ ok: true }); + await flush(); + expect(mgr.state).toBe("saved"); + await vi.advanceTimersByTimeAsync(10_000); + expect(save.calls).toBe(1); + }); +}); diff --git a/pkgs/id/web/src/auto-save.ts b/pkgs/id/web/src/auto-save.ts new file mode 100644 index 0000000000..240b78d2d8 --- /dev/null +++ b/pkgs/id/web/src/auto-save.ts @@ -0,0 +1,239 @@ +/** + * Auto-save manager for the id web editor. + * + * Serializes saves: at most one saveFn() call is ever in flight. A save + * requested while one is in flight (or while a rate-limit retry is pending) + * is coalesced into exactly one follow-up attempt, and a save completion + * only marks the document "saved" when no edit arrived after that save + * started (tracked with a monotonic edit generation). + */ + +/** Result from saveFile() for AutoSaveManager to process */ +export type SaveResult = { ok: true } | { ok: false; retryAfterMs?: number }; + +export const AUTOSAVE_DEBOUNCE_MS = 2000; + +export type SaveState = "idle" | "unsaved" | "saving" | "saved" | "rate-limited" | "error"; + +export class AutoSaveManager { + state: SaveState = "idle"; + private debounceTimer: ReturnType | null = null; + private retryTimer: ReturnType | null = null; + private savedResetTimer: ReturnType | null = null; + private saveFn: () => Promise; + /** Bumped on every local edit; a save covers edits up to the generation it started at. */ + private editGeneration = 0; + /** Serialization latch: true while a saveFn() call is unresolved. */ + private saveInFlight = false; + /** A save was requested while one was in flight or a retry was pending; run one follow-up. */ + private followUpRequested = false; + + constructor(saveFn: () => Promise) { + this.saveFn = saveFn; + } + + /** Called when user makes a local edit (editor:change event) */ + onContentChange(): void { + this.editGeneration++; + + // Clear any pending timers + if (this.debounceTimer !== null) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + if (this.savedResetTimer !== null) { + clearTimeout(this.savedResetTimer); + this.savedResetTimer = null; + } + + this.state = "unsaved"; + this.updateIndicator(); + + // Start debounce — save after 2s of no edits + this.debounceTimer = setTimeout(() => { + this.debounceTimer = null; + this.triggerSave(); + }, AUTOSAVE_DEBOUNCE_MS); + } + + /** Called when another client saves (NewVersion received) */ + onNewVersion(): void { + // Cancel any pending save — their version is newer + if (this.debounceTimer !== null) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + if (this.retryTimer !== null) { + clearTimeout(this.retryTimer); + this.retryTimer = null; + } + if (this.savedResetTimer !== null) { + clearTimeout(this.savedResetTimer); + this.savedResetTimer = null; + } + this.followUpRequested = false; + + this.state = "saved"; + this.updateIndicator(); + + // Reset indicator after 2s + this.savedResetTimer = setTimeout(() => { + this.savedResetTimer = null; + if (this.state === "saved") { + this.state = "idle"; + this.updateIndicator(); + } + }, 2000); + } + + /** Manual save — Ctrl+S or button click. Cancels debounce and saves immediately. */ + saveNow(): void { + // Cancel debounce timer — we're saving right now + if (this.debounceTimer !== null) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + // Don't save if already saving (button is disabled anyway) + if (this.state === "saving" || this.state === "rate-limited") { + return; + } + this.triggerSave(); + } + + /** Clean up all timers (called when editor closes) */ + cancel(): void { + if (this.debounceTimer !== null) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + if (this.retryTimer !== null) { + clearTimeout(this.retryTimer); + this.retryTimer = null; + } + if (this.savedResetTimer !== null) { + clearTimeout(this.savedResetTimer); + this.savedResetTimer = null; + } + this.followUpRequested = false; + this.state = "idle"; + this.updateIndicator(); + } + + /** Execute the save and handle the result, serialized against other saves */ + private async triggerSave(): Promise { + if (this.saveInFlight) { + // Coalesce into exactly one follow-up once the in-flight save settles. + this.followUpRequested = true; + return; + } + if (this.retryTimer !== null) { + // A rate-limit retry is already scheduled and will capture the current + // document when it fires — coalesce into it instead of saving early + // (which would defeat the backoff) or cancelling it outright. + this.followUpRequested = true; + return; + } + // This save captures the current document, so a pending debounce is moot. + if (this.debounceTimer !== null) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + + this.saveInFlight = true; + this.followUpRequested = false; + const startGeneration = this.editGeneration; + this.state = "saving"; + this.updateIndicator(); + + let result: SaveResult; + try { + result = await this.saveFn(); + } catch { + // A throwing saveFn is a generic save error; never wedge the latch. + result = { ok: false }; + } + this.saveInFlight = false; + this.onSaveResult(result, startGeneration); + } + + /** Transition state based on save outcome */ + private onSaveResult(result: SaveResult, startGeneration: number): void { + if (result.ok) { + if (this.followUpRequested || this.editGeneration !== startGeneration) { + // Edits arrived after this save started (or a save was requested + // during it): this completion does NOT cover them, so the document + // must not read "saved". Run exactly one follow-up save. + void this.triggerSave(); + return; + } + this.state = "saved"; + this.updateIndicator(); + + // Reset to idle after 2s + this.savedResetTimer = setTimeout(() => { + this.savedResetTimer = null; + if (this.state === "saved") { + this.state = "idle"; + this.updateIndicator(); + } + }, 2000); + } else if (result.retryAfterMs) { + // Rate limited — schedule retry. The retry captures the document when + // it fires, so it also serves as the follow-up for any edits that + // arrived during the failed save. + this.state = "rate-limited"; + this.updateIndicator(); + + this.retryTimer = setTimeout(() => { + this.retryTimer = null; + this.triggerSave(); + }, result.retryAfterMs); + } else { + // Generic error — don't auto-retry (prevents infinite loops on network outage) + this.state = "error"; + this.updateIndicator(); + + // Show error for 2s, then revert to "save •" (content is still unsaved) + this.savedResetTimer = setTimeout(() => { + this.savedResetTimer = null; + if (this.state === "error") { + this.state = "unsaved"; + this.updateIndicator(); + } + }, 2000); + } + } + + /** Update the save button text/state to reflect current state */ + updateIndicator(): void { + const saveBtn = document.getElementById("save-btn") as HTMLButtonElement | null; + if (!saveBtn) return; + + switch (this.state) { + case "idle": + saveBtn.textContent = "save"; + saveBtn.disabled = false; + break; + case "unsaved": + saveBtn.textContent = "save •"; + saveBtn.disabled = false; + break; + case "saving": + saveBtn.textContent = "saving…"; + saveBtn.disabled = true; + break; + case "saved": + saveBtn.textContent = "saved ✓"; + saveBtn.disabled = false; + break; + case "rate-limited": + saveBtn.textContent = "retry…"; + saveBtn.disabled = true; + break; + case "error": + saveBtn.textContent = "error!"; + saveBtn.disabled = false; + break; + } + } +} diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index a994f606ff..42d12c578a 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -12,193 +12,8 @@ import { type EditorInstance, getEditorState } from "./editor"; import { identityNeedsRefresh } from "./identity-refresh"; import { updateHeaderSubtitle } from "./header-subtitle"; import { cycleTheme, initTheme, setTheme, type Theme } from "./theme"; +import { AutoSaveManager, type SaveResult } from "./auto-save"; -/** Result from saveFile() for AutoSaveManager to process */ -type SaveResult = { ok: true } | { ok: false; retryAfterMs?: number }; - -// ============================================================================= -// Auto-save Manager -// ============================================================================= - -const AUTOSAVE_DEBOUNCE_MS = 2000; - -type SaveState = "idle" | "unsaved" | "saving" | "saved" | "rate-limited" | "error"; - -class AutoSaveManager { - state: SaveState = "idle"; - private debounceTimer: ReturnType | null = null; - private retryTimer: ReturnType | null = null; - private savedResetTimer: ReturnType | null = null; - private saveFn: () => Promise; - - constructor(saveFn: () => Promise) { - this.saveFn = saveFn; - } - - /** Called when user makes a local edit (editor:change event) */ - onContentChange(): void { - // Clear any pending timers - if (this.debounceTimer !== null) { - clearTimeout(this.debounceTimer); - this.debounceTimer = null; - } - if (this.savedResetTimer !== null) { - clearTimeout(this.savedResetTimer); - this.savedResetTimer = null; - } - - this.state = "unsaved"; - this.updateIndicator(); - - // Start debounce — save after 2s of no edits - this.debounceTimer = setTimeout(() => { - this.debounceTimer = null; - this.triggerSave(); - }, AUTOSAVE_DEBOUNCE_MS); - } - - /** Called when another client saves (NewVersion received) */ - onNewVersion(): void { - // Cancel any pending save — their version is newer - if (this.debounceTimer !== null) { - clearTimeout(this.debounceTimer); - this.debounceTimer = null; - } - if (this.retryTimer !== null) { - clearTimeout(this.retryTimer); - this.retryTimer = null; - } - if (this.savedResetTimer !== null) { - clearTimeout(this.savedResetTimer); - this.savedResetTimer = null; - } - - this.state = "saved"; - this.updateIndicator(); - - // Reset indicator after 2s - this.savedResetTimer = setTimeout(() => { - this.savedResetTimer = null; - if (this.state === "saved") { - this.state = "idle"; - this.updateIndicator(); - } - }, 2000); - } - - /** Manual save — Ctrl+S or button click. Cancels debounce and saves immediately. */ - saveNow(): void { - // Cancel debounce timer — we're saving right now - if (this.debounceTimer !== null) { - clearTimeout(this.debounceTimer); - this.debounceTimer = null; - } - // Don't save if already saving (button is disabled anyway) - if (this.state === "saving" || this.state === "rate-limited") { - return; - } - this.triggerSave(); - } - - /** Clean up all timers (called when editor closes) */ - cancel(): void { - if (this.debounceTimer !== null) { - clearTimeout(this.debounceTimer); - this.debounceTimer = null; - } - if (this.retryTimer !== null) { - clearTimeout(this.retryTimer); - this.retryTimer = null; - } - if (this.savedResetTimer !== null) { - clearTimeout(this.savedResetTimer); - this.savedResetTimer = null; - } - this.state = "idle"; - this.updateIndicator(); - } - - /** Execute the save and handle the result */ - private async triggerSave(): Promise { - this.state = "saving"; - this.updateIndicator(); - - const result = await this.saveFn(); - this.onSaveResult(result); - } - - /** Transition state based on save outcome */ - private onSaveResult(result: SaveResult): void { - if (result.ok) { - this.state = "saved"; - this.updateIndicator(); - - // Reset to idle after 2s - this.savedResetTimer = setTimeout(() => { - this.savedResetTimer = null; - if (this.state === "saved") { - this.state = "idle"; - this.updateIndicator(); - } - }, 2000); - } else if (result.retryAfterMs) { - // Rate limited — schedule retry - this.state = "rate-limited"; - this.updateIndicator(); - - this.retryTimer = setTimeout(() => { - this.retryTimer = null; - this.triggerSave(); - }, result.retryAfterMs); - } else { - // Generic error — don't auto-retry (prevents infinite loops on network outage) - this.state = "error"; - this.updateIndicator(); - - // Show error for 2s, then revert to "save •" (content is still unsaved) - this.savedResetTimer = setTimeout(() => { - this.savedResetTimer = null; - if (this.state === "error") { - this.state = "unsaved"; - this.updateIndicator(); - } - }, 2000); - } - } - - /** Update the save button text/state to reflect current state */ - updateIndicator(): void { - const saveBtn = document.getElementById("save-btn") as HTMLButtonElement | null; - if (!saveBtn) return; - - switch (this.state) { - case "idle": - saveBtn.textContent = "save"; - saveBtn.disabled = false; - break; - case "unsaved": - saveBtn.textContent = "save \u2022"; - saveBtn.disabled = false; - break; - case "saving": - saveBtn.textContent = "saving\u2026"; - saveBtn.disabled = true; - break; - case "saved": - saveBtn.textContent = "saved \u2713"; - saveBtn.disabled = false; - break; - case "rate-limited": - saveBtn.textContent = "retry\u2026"; - saveBtn.disabled = true; - break; - case "error": - saveBtn.textContent = "error!"; - saveBtn.disabled = false; - break; - } - } -} declare global { interface Window { From 3ff72384f7441928cc6dccd4161723f651364b1a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 27 Oct 2026 21:00:31 -0500 Subject: [PATCH 2/3] id(web): biome format main.ts (drop double blank line) --- pkgs/id/web/src/main.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index 42d12c578a..aacd54daf2 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -14,7 +14,6 @@ import { updateHeaderSubtitle } from "./header-subtitle"; import { cycleTheme, initTheme, setTheme, type Theme } from "./theme"; import { AutoSaveManager, type SaveResult } from "./auto-save"; - declare global { interface Window { idApp: IdApp; From 26d4a24202132537bd26c7509249d335e68bae0a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 27 Oct 2026 23:05:00 -0500 Subject: [PATCH 3/3] =?UTF-8?q?style(id-web):=20organize=20main.ts=20impor?= =?UTF-8?q?ts=20(biome=20assist)=20=E2=80=94=20auto-save=20import=20in=20s?= =?UTF-8?q?orted=20position?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/id/web/src/main.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index aacd54daf2..fc8a02c957 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -7,12 +7,12 @@ import "@starfederation/datastar"; import { initHome } from "./home"; import "./world"; import "./world"; +import { AutoSaveManager, type SaveResult } from "./auto-save"; import { type CollabConnection, initCollab } from "./collab"; import { type EditorInstance, getEditorState } from "./editor"; -import { identityNeedsRefresh } from "./identity-refresh"; import { updateHeaderSubtitle } from "./header-subtitle"; +import { identityNeedsRefresh } from "./identity-refresh"; import { cycleTheme, initTheme, setTheme, type Theme } from "./theme"; -import { AutoSaveManager, type SaveResult } from "./auto-save"; declare global { interface Window {