forked from longtao.wu/droboticflow
🐛 Isolate annotation autosave responses by task and user session
This commit is contained in:
parent
e5e2ce60c2
commit
c09bcde097
@ -41,6 +41,7 @@ export type AnnotationAutosaveFlushReason =
|
||||
export type UseAnnotationAutosaveArgs = {
|
||||
enabled: boolean;
|
||||
taskId: string | undefined;
|
||||
userId: string | undefined;
|
||||
workspaceDirty: boolean;
|
||||
draftsFingerprint: string;
|
||||
/** 正式操作(确认/送检/退回等)在途或任务锁定时为 true:自动保存让路。 */
|
||||
@ -57,18 +58,43 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
const argsRef = useRef(args);
|
||||
argsRef.current = args;
|
||||
|
||||
const [lastSavedAt, setLastSavedAt] = useState<number | null>(null);
|
||||
const [errorNotice, setErrorNotice] = useState("");
|
||||
const inFlightRef = useRef(false);
|
||||
const sessionRef = useRef({ taskId: args.taskId, userId: args.userId, enabled: args.enabled });
|
||||
const inFlightRef = useRef<object | null>(null);
|
||||
const savedDraftsFingerprintRef = useRef(EMPTY_FINGERPRINT);
|
||||
const failedAttemptRef = useRef("");
|
||||
if (
|
||||
sessionRef.current.taskId !== args.taskId ||
|
||||
sessionRef.current.userId !== args.userId ||
|
||||
sessionRef.current.enabled !== args.enabled
|
||||
) {
|
||||
// Object identity also fences A → B → A, even when task/user IDs repeat.
|
||||
sessionRef.current = { taskId: args.taskId, userId: args.userId, enabled: args.enabled };
|
||||
inFlightRef.current = null;
|
||||
savedDraftsFingerprintRef.current = EMPTY_FINGERPRINT;
|
||||
failedAttemptRef.current = "";
|
||||
}
|
||||
const [status, setStatus] = useState<{ session: object; lastSavedAt: number | null; errorNotice: string }>({
|
||||
session: sessionRef.current,
|
||||
lastSavedAt: null,
|
||||
errorNotice: "",
|
||||
});
|
||||
|
||||
const dirty = args.enabled && (args.workspaceDirty || args.draftsFingerprint !== savedDraftsFingerprintRef.current);
|
||||
|
||||
const flushRef = useRef(
|
||||
async (reason: AnnotationAutosaveFlushReason, options: { versionOverride?: number } = {}): Promise<boolean> => {
|
||||
const current = argsRef.current;
|
||||
if (!current.enabled || !current.taskId || inFlightRef.current) return false;
|
||||
if (!current.enabled || !current.taskId || !current.userId || inFlightRef.current) return false;
|
||||
const session = sessionRef.current;
|
||||
const isCurrent = () => sessionRef.current === session;
|
||||
const notice = (errorNotice: string) => {
|
||||
if (isCurrent())
|
||||
setStatus((previous) => ({
|
||||
session,
|
||||
lastSavedAt: previous.session === session ? previous.lastSavedAt : null,
|
||||
errorNotice,
|
||||
}));
|
||||
};
|
||||
if (reason !== "conflict-overwrite" && current.isBlocked()) return false;
|
||||
const context = current.buildSaveContext();
|
||||
if (!context) return false;
|
||||
@ -81,7 +107,8 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
return false;
|
||||
}
|
||||
const version = options.versionOverride ?? context.version;
|
||||
inFlightRef.current = true;
|
||||
const request = {};
|
||||
inFlightRef.current = request;
|
||||
const keepalive = reason === "hidden" || reason === "pagehide";
|
||||
try {
|
||||
const response = await annotationOperationsApi.saveCombinedDraft(
|
||||
@ -95,16 +122,18 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
},
|
||||
{ keepalive },
|
||||
);
|
||||
if (!isCurrent()) return false;
|
||||
savedDraftsFingerprintRef.current = context.draftsFingerprint;
|
||||
failedAttemptRef.current = "";
|
||||
setErrorNotice("");
|
||||
setLastSavedAt(Date.now());
|
||||
setStatus({ session, errorNotice: "", lastSavedAt: Date.now() });
|
||||
current.onApplied({ item: response.item, workspace: response.draft, sentVersion: version });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return false;
|
||||
if (error instanceof APIError && error.status === 409) {
|
||||
try {
|
||||
const authoritative = await annotationOperationsApi.getTask(current.taskId);
|
||||
if (!isCurrent()) return false;
|
||||
const serverDraft = annotationDraftFromHumanItem(authoritative.humanItem);
|
||||
if (serverDraft) {
|
||||
current.onExternalConflict(authoritative);
|
||||
@ -113,21 +142,21 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
setErrorNotice("草稿自动保存遇到版本冲突,稍后将自动重试。");
|
||||
notice("草稿自动保存遇到版本冲突,稍后将自动重试。");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (error instanceof APIError && error.status >= 400 && error.status < 500) {
|
||||
// 校验拒绝:同一载荷不再重复尝试(避免错误循环),编辑变化后自动恢复。
|
||||
failedAttemptRef.current = attemptKey;
|
||||
setErrorNotice(`草稿自动保存未通过校验:${error.message}`);
|
||||
notice(`草稿自动保存未通过校验:${error.message}`);
|
||||
return false;
|
||||
}
|
||||
// 网络/服务端异常:不阻塞编辑,下一触发点重试(断网恢复后自动续上)。
|
||||
setErrorNotice("草稿自动保存暂未成功,编辑不受影响,稍后将自动重试。");
|
||||
notice("草稿自动保存暂未成功,编辑不受影响,稍后将自动重试。");
|
||||
return false;
|
||||
} finally {
|
||||
inFlightRef.current = false;
|
||||
if (inFlightRef.current === request) inFlightRef.current = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
@ -150,7 +179,7 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
return;
|
||||
}
|
||||
scheduler.notifyActivity();
|
||||
}, [args.enabled, args.taskId, dirty, args.draftsFingerprint, scheduler]);
|
||||
}, [args.enabled, args.taskId, args.userId, dirty, args.draftsFingerprint, scheduler]);
|
||||
|
||||
// 页面隐藏/关闭兜底:立即 keepalive flush(锁屏被回收、刷新、崩溃前抢救)。
|
||||
useEffect(() => {
|
||||
@ -167,13 +196,14 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
};
|
||||
}, [args.enabled, flush]);
|
||||
|
||||
// 换任务:清保存痕迹(新任务从服务器基线重新开始)。
|
||||
useEffect(() => {
|
||||
savedDraftsFingerprintRef.current = EMPTY_FINGERPRINT;
|
||||
failedAttemptRef.current = "";
|
||||
setErrorNotice("");
|
||||
setLastSavedAt(null);
|
||||
}, [args.taskId]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
sessionRef.current = { ...sessionRef.current };
|
||||
inFlightRef.current = null;
|
||||
scheduler.cancel();
|
||||
},
|
||||
[scheduler],
|
||||
);
|
||||
|
||||
const notifySliceSwitchRef = useRef(() => {
|
||||
const current = argsRef.current;
|
||||
@ -183,8 +213,8 @@ export function useAnnotationAutosave(args: UseAnnotationAutosaveArgs) {
|
||||
});
|
||||
|
||||
return {
|
||||
lastSavedAt,
|
||||
errorNotice,
|
||||
lastSavedAt: status.session === sessionRef.current ? status.lastSavedAt : null,
|
||||
errorNotice: status.session === sessionRef.current ? status.errorNotice : "",
|
||||
dirty,
|
||||
notifySliceSwitch: notifySliceSwitchRef.current,
|
||||
flushNow: (reason: AnnotationAutosaveFlushReason, options?: { versionOverride?: number }) => flush(reason, options),
|
||||
|
||||
@ -2684,6 +2684,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
const autosave = useAnnotationAutosave({
|
||||
enabled: autosaveEnabled,
|
||||
taskId: detail?.task.id,
|
||||
userId: currentUser?.id,
|
||||
workspaceDirty: autosaveWorkspaceDirty,
|
||||
draftsFingerprint: autosaveDraftsFingerprint,
|
||||
// 面板会话或任一冲突清单打开期间让路(验收修复 C):草稿留在工作台本地态,
|
||||
@ -2712,6 +2713,7 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
};
|
||||
},
|
||||
onApplied: ({ item, workspace }) => {
|
||||
if (item.id !== detailRef.current?.humanItem?.id || workspace.userId !== currentUser?.id) return;
|
||||
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
|
||||
if (!item || item.version < currentVersion) return;
|
||||
const savedItem = { ...item, display: item.display || detailRef.current?.humanItem?.display };
|
||||
@ -2727,8 +2729,11 @@ export default function AnnotationOperations({ workPage = false }: { workPage?:
|
||||
workspace.statuses,
|
||||
);
|
||||
},
|
||||
onExternalConflict: (authoritative) => setDraftConflictAuthoritative(authoritative),
|
||||
onExternalConflict: (authoritative) => {
|
||||
if (authoritative.task.id === detailRef.current?.task.id) setDraftConflictAuthoritative(authoritative);
|
||||
},
|
||||
onVersionResync: (item) => {
|
||||
if (item.id !== detailRef.current?.humanItem?.id) return;
|
||||
const currentVersion = detailRef.current?.humanItem?.version ?? 0;
|
||||
if (!item || item.version < currentVersion) return;
|
||||
const savedItem = { ...item, display: item.display || detailRef.current?.humanItem?.display };
|
||||
|
||||
230
tests/browser/annotation-autosave-session.mjs
Normal file
230
tests/browser/annotation-autosave-session.mjs
Normal file
@ -0,0 +1,230 @@
|
||||
// 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.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("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();
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user