droboticflow-new/src/hooks/useAnnotationWorkSession.ts
2026-10-15 20:26:49 +08:00

244 lines
9.0 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
export type AnnotationWorkSession = {
readonly scope: string;
readonly active: boolean;
};
type AcquisitionResult =
| { status: "acquired"; session: AnnotationWorkSession }
| { status: "unsupported" | "blocked" | "error" | "stale" };
type OwnedSession = AnnotationWorkSession & {
active: boolean;
continuous: boolean;
pauseReason: string;
epoch: number;
release: () => void;
};
// Document memory deliberately does not survive refresh. It only bridges the
// pool -> work route in this tab; possession cannot be copied by duplicating a URL.
let ownedSession: OwnedSession | null = null;
let disconnectTimer: ReturnType<typeof setTimeout> | undefined;
const subscribers = new Set<() => void>();
const notify = () => subscribers.forEach((listener) => listener());
function releaseSession(session: AnnotationWorkSession | null) {
if (!session || ownedSession !== session) return;
const previous = ownedSession;
ownedSession = null;
previous.active = false;
previous.release();
notify();
}
/** Browser-local ownership only; backend task assignment remains authoritative. */
export function useAnnotationWorkSession(userId: string, projectId: string, workPage: boolean) {
const scope = userId && projectId ? `droboticflow.annotation-work:${JSON.stringify([userId, projectId])}` : "";
const identityRef = useRef({ scope });
if (identityRef.current.scope !== scope) identityRef.current = { scope };
const [, render] = useState(0);
// A failed initial claim releases its inactive owner, but must not dismiss
// viewport recovery. The latch belongs to this page/scope, not the lock.
const viewportRef = useRef({ scope, suspended: false });
if (viewportRef.current.scope !== scope) viewportRef.current = { scope, suspended: false };
const supported = Boolean(navigator.locks);
const [observation, setObservation] = useState({ scope: "", blocked: false, error: false });
const channelRef = useRef<BroadcastChannel | null>(null);
const owns = useCallback((session?: AnnotationWorkSession | null) => {
return Boolean(
ownedSession && ownedSession.scope === identityRef.current.scope && (!session || session === ownedSession),
);
}, []);
useEffect(() => {
clearTimeout(disconnectTimer);
if (ownedSession && (ownedSession.scope !== scope || (!workPage && ownedSession.active))) {
releaseSession(ownedSession);
}
let disposed = false;
let queryVersion = 0;
const channel = scope && typeof BroadcastChannel !== "undefined" ? new BroadcastChannel(scope) : null;
channelRef.current = channel;
const refresh = async () => {
const version = ++queryVersion;
if (!scope || !navigator.locks) {
if (!disposed) setObservation({ scope, blocked: false, error: false });
return;
}
try {
const locks = await navigator.locks.query();
if (disposed || version !== queryVersion) return;
setObservation({
scope,
blocked: !owns() && Boolean(locks.held?.some((lock) => lock.name === scope)),
error: false,
});
} catch {
if (!disposed && version === queryVersion) setObservation({ scope, blocked: false, error: true });
}
};
const update = () => {
render((version) => version + 1);
void refresh();
};
subscribers.add(update);
if (channel) {
channel.onmessage = (event) => {
if (disposed) return;
if (event.data === "return" && owns()) window.focus();
void refresh();
};
}
const pageHidden = () => {
// A pending acquisition has no owner to release yet. It must not become
// an active session when this document later returns from BFCache.
identityRef.current = { scope: identityRef.current.scope };
if (owns()) releaseSession(ownedSession);
channel?.postMessage("changed");
};
window.addEventListener("pagehide", pageHidden);
window.addEventListener("pageshow", update);
window.addEventListener("focus", update);
// Querying does not acquire the lock. This also discovers a crashed/closed
// owner if no BroadcastChannel notification could be delivered.
const timer = window.setInterval(refresh, 2_000);
void refresh();
return () => {
disposed = true;
identityRef.current = { scope: identityRef.current.scope };
subscribers.delete(update);
window.clearInterval(timer);
window.removeEventListener("pagehide", pageHidden);
window.removeEventListener("pageshow", update);
window.removeEventListener("focus", update);
channel?.close();
if (channelRef.current === channel) channelRef.current = null;
const previous = ownedSession;
// Same-scope route remounts may adopt the in-memory owner in this turn.
// Leaving the coordinator, changing account/project, or closing the tab
// releases ownership without changing any server task assignment.
disconnectTimer = setTimeout(() => releaseSession(previous), 0);
};
}, [scope, workPage, owns]);
const acquire = useCallback(async (): Promise<AcquisitionResult> => {
const identity = identityRef.current;
if (!identity.scope) return { status: "stale" };
if (!navigator.locks) return { status: "unsupported" };
if (owns()) return { status: "acquired", session: ownedSession };
return new Promise((resolve) => {
void navigator.locks
.request(identity.scope, { ifAvailable: true }, async (lock) => {
if (identityRef.current !== identity) {
resolve({ status: "stale" });
return;
}
if (!lock) {
setObservation({ scope: identity.scope, blocked: true, error: false });
resolve({ status: "blocked" });
return;
}
let unlock: () => void;
const held = new Promise<void>((done) => (unlock = done));
const session: OwnedSession = {
scope: identity.scope,
active: false,
continuous: false,
pauseReason: "",
epoch: 0,
release: () => unlock(),
};
ownedSession = session;
notify();
channelRef.current?.postMessage("changed");
setObservation({ scope: identity.scope, blocked: false, error: false });
resolve({ status: "acquired", session });
await held;
})
.catch(() => {
if (identityRef.current === identity) {
setObservation({ scope: identity.scope, blocked: false, error: true });
}
resolve({ status: identityRef.current === identity ? "error" : "stale" });
});
});
}, [owns]);
const activate = useCallback(
(session: AnnotationWorkSession) => {
if (!owns(session)) return false;
ownedSession.active = true;
notify();
return true;
},
[owns],
);
const release = useCallback((session: AnnotationWorkSession) => {
releaseSession(session);
channelRef.current?.postMessage("changed");
}, []);
const setContinuous = useCallback(
(session: AnnotationWorkSession, enabled: boolean, reason = "") => {
if (!owns(session)) return false;
ownedSession.epoch++;
ownedSession.continuous = enabled;
ownedSession.pauseReason = reason;
notify();
return true;
},
[owns],
);
const pauseContinuous = useCallback(
(reason: string) => {
if (!owns() || !ownedSession.continuous) return;
ownedSession.epoch++;
ownedSession.continuous = false;
ownedSession.pauseReason = reason;
notify();
},
[owns],
);
// Viewport suspension never changes user intent or clears a hard pause reason.
const setViewportSuspended = useCallback((suspended: boolean) => {
if (viewportRef.current.suspended === suspended) return;
viewportRef.current.suspended = suspended;
render((version) => version + 1);
}, []);
const hasContinuousIntent = useCallback(
() => owns() && Boolean(ownedSession?.active && ownedSession.continuous),
[owns],
);
const isViewportSuspended = useCallback(() => viewportRef.current.suspended, []);
const isContinuous = useCallback(
() => hasContinuousIntent() && !isViewportSuspended(),
[hasContinuousIntent, isViewportSuspended],
);
return {
continuousEpoch: () => ownedSession?.epoch ?? -1,
viewportSuspended: isViewportSuspended(),
setViewportSuspended,
isViewportSuspended,
hasContinuousIntent,
continuous: owns() && Boolean(ownedSession?.continuous),
pauseReason: owns() ? ownedSession?.pauseReason || "" : "",
setContinuous,
pauseContinuous,
isContinuous,
active: owns() && Boolean(ownedSession?.active),
blocked: observation.scope === scope && observation.blocked && !owns(),
supported,
coordinationError: observation.scope === scope && observation.error,
unavailable: !supported || (observation.scope === scope && observation.error),
acquire,
owns,
activate,
release,
returnToActivePage: () => channelRef.current?.postMessage("return"),
};
}