forked from longtao.wu/droboticflow
249 lines
9.4 KiB
JavaScript
249 lines
9.4 KiB
JavaScript
// Real React hook with deferred API-boundary responses; no database writes.
|
|
import assert from "node:assert/strict";
|
|
import { chromium } from "playwright";
|
|
|
|
const base = process.env.AUTOSAVE_TEST_URL || "http://localhost:5173";
|
|
assert.ok(["localhost", "127.0.0.1", "[::1]"].includes(new URL(base).hostname), "local replica only");
|
|
const browser = await chromium.launch({
|
|
executablePath: process.env.BROWSER_EXECUTABLE || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
headless: true,
|
|
args: ["--no-proxy-server"],
|
|
});
|
|
try {
|
|
const page = await browser.newPage();
|
|
await page.route(`${base}/api/**`, (route) => route.fulfill({ status: 401, json: { error: "synthetic test" } }));
|
|
await page.goto(base, { waitUntil: "domcontentloaded" });
|
|
await page.evaluate(async () => {
|
|
const source = await (await fetch("/src/main.tsx")).text();
|
|
const reactURL = source.match(/from "([^"]*\/react\.js\?[^"]*)"/)[1];
|
|
const domURL = source.match(/from "([^"]*\/react-dom_client\.js\?[^"]*)"/)[1];
|
|
const React = (await import(reactURL)).default;
|
|
const { createRoot } = (await import(domURL)).default;
|
|
const { useAnnotationAutosave } = await import("/src/hooks/useAnnotationAutosave.ts");
|
|
const { annotationOperationsApi: api } = await import("/src/services/api/annotation-operations.ts");
|
|
const { APIError } = await import("/src/services/api/client.ts");
|
|
const deferred = () => {
|
|
const value = {};
|
|
value.promise = new Promise((resolve, reject) => Object.assign(value, { resolve, reject }));
|
|
return value;
|
|
};
|
|
document.getElementById("root").style.display = "none";
|
|
const mount = document.createElement("div");
|
|
document.body.append(mount);
|
|
let root;
|
|
const h = (window.autosaveTest = {});
|
|
h.unmount = () => {
|
|
root?.unmount();
|
|
root = null;
|
|
};
|
|
h.reset = () => {
|
|
root?.unmount();
|
|
h.writes = [];
|
|
h.reads = [];
|
|
h.events = [];
|
|
h.results = [];
|
|
api.saveCombinedDraft = (task, payload) => {
|
|
const request = { ...deferred(), task, payload };
|
|
h.writes.push(request);
|
|
return request.promise;
|
|
};
|
|
api.getTask = (task) => {
|
|
const request = { ...deferred(), task };
|
|
h.reads.push(request);
|
|
return request.promise;
|
|
};
|
|
function Harness() {
|
|
const [identity, setIdentity] = React.useState({ taskId: "A", userId: "user-1", enabled: true });
|
|
const [view, setView] = React.useState({ task: "A", item: "item-A", baseline: "A" });
|
|
const autosave = useAnnotationAutosave({
|
|
...identity,
|
|
workspaceDirty: true,
|
|
draftsFingerprint: `draft-${identity.taskId}-${identity.userId}`,
|
|
isBlocked: () => false,
|
|
buildSaveContext: () => ({
|
|
version: 1,
|
|
sliceSegments: [],
|
|
operations: [],
|
|
segments: [],
|
|
statuses: {},
|
|
draftsFingerprint: `draft-${identity.taskId}-${identity.userId}`,
|
|
workspaceFingerprint: identity.taskId,
|
|
}),
|
|
onApplied: ({ item }) => {
|
|
h.events.push("applied");
|
|
setView((v) => ({ ...v, item: item.id, baseline: item.id }));
|
|
},
|
|
onExternalConflict: () => h.events.push("conflict"),
|
|
onVersionResync: () => h.events.push("resync"),
|
|
});
|
|
h.switchTo = (taskId, userId = "user-1", enabled = true) => {
|
|
setIdentity({ taskId, userId, enabled });
|
|
setView({ task: taskId, item: `item-${taskId}`, baseline: taskId });
|
|
};
|
|
h.snapshot = () => ({
|
|
...view,
|
|
lastSavedAt: autosave.lastSavedAt,
|
|
error: autosave.errorNotice,
|
|
events: [...h.events],
|
|
writes: h.writes.length,
|
|
reads: h.reads.length,
|
|
});
|
|
h.start = () => {
|
|
const index = h.results.length;
|
|
h.results.push(null);
|
|
autosave.flushNow("idle").then((value) => (h.results[index] = value));
|
|
return index;
|
|
};
|
|
return React.createElement("output", null, JSON.stringify(h.snapshot()));
|
|
}
|
|
root = createRoot(mount);
|
|
root.render(React.createElement(React.StrictMode, null, React.createElement(Harness)));
|
|
};
|
|
h.completeWrite = (index, status = 200) => {
|
|
const request = h.writes[index];
|
|
if (status !== 200) return request.reject(new APIError("synthetic failure", status));
|
|
request.resolve({
|
|
item: { id: `item-${request.task}`, version: 20 },
|
|
draft: { sliceSegments: [], operations: [], segments: [], statuses: {}, userId: "user-1", savedAt: "now" },
|
|
});
|
|
};
|
|
h.completeRead = (draft) => {
|
|
const request = h.reads[0];
|
|
request.resolve({
|
|
task: { id: request.task },
|
|
humanItem: {
|
|
id: `item-${request.task}`,
|
|
version: 20,
|
|
subject: {
|
|
payload: draft
|
|
? { annotationWorkspace: { sliceSegments: [], operations: [], segments: [], statuses: {} } }
|
|
: {},
|
|
},
|
|
},
|
|
});
|
|
};
|
|
h.reset();
|
|
});
|
|
const reset = async () => {
|
|
await page.evaluate(() => window.autosaveTest.reset());
|
|
await page.waitForFunction(() => window.autosaveTest.snapshot().task === "A");
|
|
};
|
|
const switchTo = async (task, user = "user-1", enabled = true) => {
|
|
await page.evaluate(([t, u, e]) => window.autosaveTest.switchTo(t, u, e), [task, user, enabled]);
|
|
await page.waitForTimeout(20);
|
|
};
|
|
const start = () => page.evaluate(() => window.autosaveTest.start());
|
|
const settle = async (index, status = 200) => {
|
|
await page.evaluate(([i, s]) => window.autosaveTest.completeWrite(i, s), [index, status]);
|
|
await page.waitForTimeout(30);
|
|
};
|
|
const snapshot = () => page.evaluate(() => window.autosaveTest.snapshot());
|
|
const results = [];
|
|
const check = async (name, run) => {
|
|
await reset();
|
|
try {
|
|
await run();
|
|
results.push({ name, passed: true });
|
|
} catch (error) {
|
|
results.push({ name, passed: false, error: error.message });
|
|
}
|
|
};
|
|
await check("current session still applies a successful save", async () => {
|
|
await start();
|
|
await settle(0);
|
|
const state = await snapshot();
|
|
assert.deepEqual(state.events, ["applied"]);
|
|
assert.equal(state.item, "item-A");
|
|
assert.ok(state.lastSavedAt);
|
|
});
|
|
for (const draft of [true, false]) {
|
|
await check(`current 409 readback still reports ${draft ? "conflict" : "resync"}`, async () => {
|
|
await start();
|
|
await settle(0, 409);
|
|
await page.evaluate((d) => window.autosaveTest.completeRead(d), draft);
|
|
await page.waitForTimeout(30);
|
|
assert.deepEqual((await snapshot()).events, [draft ? "conflict" : "resync"]);
|
|
});
|
|
}
|
|
for (const status of [200, 409, 400, 500]) {
|
|
await check(`late ${status} response cannot change task B`, async () => {
|
|
await start();
|
|
await switchTo("B");
|
|
await settle(0, status);
|
|
assert.deepEqual(await snapshot(), {
|
|
task: "B",
|
|
item: "item-B",
|
|
baseline: "B",
|
|
lastSavedAt: null,
|
|
error: "",
|
|
events: [],
|
|
writes: 1,
|
|
reads: 0,
|
|
});
|
|
});
|
|
}
|
|
for (const draft of [true, false]) {
|
|
await check(`late 409 readback (${draft ? "conflict" : "resync"}) cannot change task B`, async () => {
|
|
await start();
|
|
await settle(0, 409);
|
|
assert.equal((await snapshot()).reads, 1);
|
|
await switchTo("B");
|
|
await page.evaluate((d) => window.autosaveTest.completeRead(d), draft);
|
|
await page.waitForTimeout(30);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
}
|
|
await check("A to B to A rejects the first A generation", async () => {
|
|
await start();
|
|
await switchTo("B");
|
|
await switchTo("A");
|
|
await settle(0);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
await check("same task with another user rejects the old user response", async () => {
|
|
await start();
|
|
await switchTo("A", "user-2");
|
|
await settle(0);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
await check("disabled session rejects its pending response", async () => {
|
|
await start();
|
|
await switchTo("A", "user-1", false);
|
|
await settle(0);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
await check("unmounted hook rejects a late successful response", async () => {
|
|
await start();
|
|
await page.evaluate(() => window.autosaveTest.unmount());
|
|
await settle(0);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
await check("unmounted hook rejects a late conflict readback", async () => {
|
|
await start();
|
|
await settle(0, 409);
|
|
await page.evaluate(() => window.autosaveTest.unmount());
|
|
await page.evaluate(() => window.autosaveTest.completeRead(true));
|
|
await page.waitForTimeout(30);
|
|
assert.deepEqual((await snapshot()).events, []);
|
|
});
|
|
await check("old finally cannot clear the new session's in-flight save", async () => {
|
|
await start();
|
|
await switchTo("B");
|
|
await start();
|
|
assert.equal((await snapshot()).writes, 2, "B can save independently of the old session");
|
|
await settle(0);
|
|
await start();
|
|
assert.equal((await snapshot()).writes, 2, "B remains single-flight");
|
|
await settle(1);
|
|
assert.equal((await snapshot()).item, "item-B");
|
|
assert.deepEqual((await snapshot()).events, ["applied"]);
|
|
});
|
|
console.log(JSON.stringify(results, null, 2));
|
|
assert.ok(
|
|
results.every((r) => r.passed),
|
|
"autosave session isolation regressions",
|
|
);
|
|
} finally {
|
|
await browser.close();
|
|
}
|