Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions pkgs/id/web/src/auto-save.test.ts
Original file line number Diff line number Diff line change
@@ -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<SaveResult>((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);
});
});
239 changes: 239 additions & 0 deletions pkgs/id/web/src/auto-save.ts
Original file line number Diff line number Diff line change
@@ -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<typeof setTimeout> | null = null;
private retryTimer: ReturnType<typeof setTimeout> | null = null;
private savedResetTimer: ReturnType<typeof setTimeout> | null = null;
private saveFn: () => Promise<SaveResult>;
/** 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<SaveResult>) {
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<void> {
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();
Comment on lines +162 to +166

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Invalidate pending follow-ups when the editor closes

If an edit arrives during an in-flight save and the editor then closes, cancel() clears followUpRequested but leaves the generation mismatch intact. When that save succeeds, this branch invokes saveFn() again despite cancellation. In main.ts, the callback is () => this.saveFile(), which reads the currently open editor rather than the original one, so navigating to another document before the response arrives lets the old manager save the new document and interfere with its save indicator and retries. Invalidate the pending completion on cancellation before allowing it to launch a follow-up.

Useful? React with 👍 / 👎.

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();
Comment on lines +191 to +194

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve queued save requests when an earlier save fails

If a newer edit's debounce fires while a save is in flight, triggerSave() consumes that timer and records followUpRequested. When the earlier request returns a generic error, this branch never services the queued request, leaving the newer edit unsaved indefinitely unless the user edits again or manually saves. Previously, that edit's debounce issued its own request. Honor an explicitly queued follow-up after failure while still avoiding automatic retries when no newer save was requested.

Useful? React with 👍 / 👎.


// 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;
}
}
}
Loading
Loading