Skip to content
Closed
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
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
// fallow-ignore-file code-duplication
// @vitest-environment happy-dom
import { IDBFactory } from "fake-indexeddb";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";
import {
deleteExternalConflictSnapshot,
loadExternalConflictSnapshot,
persistExternalConflictSnapshot,
} from "../utils/externalConflictStorage";
import { markStudioWriteToken, resetStudioWriteTokens } from "../utils/studioFileVersion";
import { markSelfWrite, resetSelfWriteRegistry } from "./sdkSelfWriteRegistry";
import {
Expand Down Expand Up @@ -837,6 +843,85 @@ describe("external file change coordinator", () => {
});
});

describe("recovery drafts in the shared origin store", () => {
beforeEach(() => {
vi.stubGlobal("indexedDB", new IDBFactory());
});

const plantRecord = (projectId: string, filePath: string, record: object) =>
new Promise<void>((resolve, reject) => {
const request = indexedDB.open("hyperframes-studio-external-conflicts", 1);
request.onupgradeneeded = () => request.result.createObjectStore("file-conflicts");
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const db = request.result;
const transaction = db.transaction("file-conflicts", "readwrite");
transaction.objectStore("file-conflicts").put(record, `${projectId}\0${filePath}`);
transaction.oncomplete = () => {
db.close();
resolve();
};
transaction.onerror = () => reject(transaction.error);
};
});

const mountWithStore = (overrides: Partial<CoordinatorOptions> = {}) =>
mountCoordinator({
projectId: "project-b",
recoveryFilePath: "index.html",
loadConflictSnapshot: loadExternalConflictSnapshot,
deleteConflictSnapshot: deleteExternalConflictSnapshot,
...overrides,
});

it.each([
["another project", { projectId: "project-a", filePath: "index.html" }],
["another file", { projectId: "project-b", filePath: "secrets.html" }],
])("ignores a planted record naming %s", async (_label, target) => {
await plantRecord("project-b", "index.html", {
kind: "failed",
...target,
externalVersion: null,
externalContent: null,
studioContent: "<script>planted()</script>",
failureMessage: "planted",
createdAt: Date.now(),
});
const overwriteConflict = vi.fn(async () => undefined);
const { captured, options } = await mountWithStore({ overwriteConflict });

await act(async () => handler?.({ path: "index.html", version: "v2", content: "external" }));
await act(async () => captured.handle?.keepStudioFile());

expect(captured.handle?.blocked).toBeNull();
expect(options.reloadPreview).toHaveBeenCalledOnce();
expect(overwriteConflict).not.toHaveBeenCalled();
await expect(loadExternalConflictSnapshot("project-b", "index.html")).resolves.toBeNull();
});

it("still recovers a draft Studio saved for this project and file", async () => {
await persistExternalConflictSnapshot(
"project-b",
new StudioFileConflictError({
filePath: "index.html",
currentVersion: "v2",
currentContent: "external",
attemptedContent: "studio draft",
}),
);
const { captured } = await mountWithStore();

await vi.waitFor(() => expect(captured.handle?.blocked?.status).toBe("conflict"));
expect(captured.handle?.blocked).toMatchObject({
error: {
filePath: "index.html",
currentContent: "external",
attemptedContent: "studio draft",
},
});
});
});

it("retains the final local candidate when a drain fails", async () => {
const failure = new Error("network unavailable");
const persistFailureSnapshot = vi.fn(async () => undefined);
Expand Down
90 changes: 90 additions & 0 deletions packages/studio/src/utils/externalConflictStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,48 @@ import {
} from "./externalConflictStorage";
import { StudioFileConflictError } from "./studioSaveDiagnostics";

const DAY_MS = 24 * 60 * 60 * 1000;

function rawStore<T>(
mode: IDBTransactionMode,
callback: (store: IDBObjectStore) => IDBRequest<T>,
): Promise<T> {
return new Promise((resolve, reject) => {
const request = indexedDB.open("hyperframes-studio-external-conflicts", 1);
request.onupgradeneeded = () => request.result.createObjectStore("file-conflicts");
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const db = request.result;
const transaction = db.transaction("file-conflicts", mode);
const result = callback(transaction.objectStore("file-conflicts"));
transaction.oncomplete = () => {
db.close();
resolve(result.result);
};
transaction.onerror = () => reject(transaction.error);
};
});
}

const plantRecord = (projectId: string, filePath: string, record: unknown) =>
rawStore("readwrite", (store) => store.put(record, `${projectId}\0${filePath}`));

const readRawRecord = (projectId: string, filePath: string) =>
rawStore<unknown>("readonly", (store) => store.get(`${projectId}\0${filePath}`));

function genuineRecord(overrides: Partial<ExternalConflictSnapshot> = {}) {
return {
kind: "conflict",
projectId: "project-b",
filePath: "index.html",
externalVersion: "v2",
externalContent: "external",
studioContent: "studio",
createdAt: Date.now(),
...overrides,
};
}

describe("external conflict snapshots", () => {
beforeEach(() => {
vi.stubGlobal("indexedDB", new IDBFactory());
Expand Down Expand Up @@ -79,6 +121,54 @@ describe("external conflict snapshots", () => {
).resolves.toBeNull();
});

it.each([
["another project's id", { projectId: "project-a" }],
["another file's path", { filePath: "other.html" }],
["a creation time over 30 days old", { createdAt: Date.now() - 31 * DAY_MS }],
["a creation time over 30 days ahead", { createdAt: Date.now() + 31 * DAY_MS }],
["no creation time", { createdAt: undefined }],
])("refuses and deletes a stored record with %s", async (_label, overrides) => {
await plantRecord("project-b", "index.html", { ...genuineRecord(), ...overrides });

await expect(loadExternalConflictSnapshot("project-b", "index.html")).resolves.toBeNull();
await expect(readRawRecord("project-b", "index.html")).resolves.toBeUndefined();
});

it("keeps a fresh draft another tab saves while an expired one is being cleared", async () => {
await plantRecord("project-b", "index.html", {
...genuineRecord(),
createdAt: Date.now() - 31 * DAY_MS,
});
const conflict = new StudioFileConflictError({
filePath: "index.html",
currentVersion: "v3",
currentContent: "external",
attemptedContent: "fresh draft",
});

const loading = loadExternalConflictSnapshot("project-b", "index.html");
const saving = persistExternalConflictSnapshot("project-b", conflict);
await Promise.all([loading, saving]);

await expect(readRawRecord("project-b", "index.html")).resolves.toMatchObject({
studioContent: "fresh draft",
});
});

it("refuses a creation time stored as a string", async () => {
await plantRecord("project-b", "index.html", {
...genuineRecord(),
createdAt: String(Date.now()),
});
await expect(loadExternalConflictSnapshot("project-b", "index.html")).resolves.toBeNull();
});

it("recovers a genuine draft up to 30 days old", async () => {
const record = genuineRecord({ createdAt: Date.now() - 29 * DAY_MS });
await plantRecord("project-b", "index.html", record);
await expect(loadExternalConflictSnapshot("project-b", "index.html")).resolves.toEqual(record);
});

it("rejects persistence when IndexedDB is unavailable", async () => {
vi.stubGlobal("indexedDB", undefined);
const conflict = new StudioFileConflictError({
Expand Down
15 changes: 14 additions & 1 deletion packages/studio/src/utils/externalConflictStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface ExternalConflictStorage {
const DB_NAME = "hyperframes-studio-external-conflicts";
const DB_VERSION = 1;
const STORE_NAME = "file-conflicts";
const UNRESOLVED_DRAFT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;

function key(projectId: string, filePath: string): string {
return `${projectId}\0${filePath}`;
Expand Down Expand Up @@ -161,7 +162,19 @@ export async function loadExternalConflictSnapshot(
projectId: string,
filePath: string,
): Promise<ExternalConflictSnapshot | null> {
return indexedDbStorage.get(projectId, filePath);
const isCurrent = (record?: ExternalConflictSnapshot): record is ExternalConflictSnapshot =>
record?.projectId === projectId &&
record.filePath === filePath &&
typeof record.createdAt === "number" &&
Math.abs(Date.now() - record.createdAt) <= UNRESOLVED_DRAFT_MAX_AGE_MS;
const record = await withStore<ExternalConflictSnapshot | undefined>("readwrite", (store) => {
const request = store.get(key(projectId, filePath));
request.addEventListener("success", () => {
if (request.result && !isCurrent(request.result)) store.delete(key(projectId, filePath));
});
return request;
});
return isCurrent(record) ? record : null;
}

export async function deleteExternalConflictSnapshot(
Expand Down
Loading