fix(career): bind history restore to its mounted session

This commit is contained in:
cesnimda
2026-11-16 22:41:55 +01:00
parent 2043f99259
commit fb3936cb1d
2 changed files with 89 additions and 7 deletions
@@ -7,12 +7,17 @@ import { translations } from "./i18n/translations";
import { emptyStructuredCv } from "./profileCv";
import { ToastProvider } from "./toast";
import CareerProfilePage from "./views/CareerProfilePage";
import { getSessionContext, isSessionInvalidated } from "./sessionBoundary";
jest.mock("./api", () => ({
getApiErrorMessage: jest.requireActual("./api").getApiErrorMessage,
api: { get: jest.fn(), post: jest.fn(), put: jest.fn(), patch: jest.fn(), delete: jest.fn() },
}));
jest.mock("./components/CropImageDialog", () => () => null);
jest.mock("./sessionBoundary", () => ({
...jest.requireActual("./sessionBoundary"),
checkSessionCookie: jest.fn(), getSessionContext: jest.fn(), isSessionInvalidated: jest.fn(),
}));
const mockedApi = api as jest.Mocked<typeof api>;
const en = translations.en;
@@ -61,6 +66,8 @@ function editDraft() {
beforeEach(() => {
jest.resetAllMocks();
jest.mocked(getSessionContext).mockReturnValue("owner-session");
jest.mocked(isSessionInvalidated).mockReturnValue(false);
window.localStorage.clear();
window.history.replaceState({}, "", "/career?section=import");
runs = [run];
@@ -233,6 +240,56 @@ test("a failed restore keeps the original source and known history with an expli
expect(mockedApi.post.mock.calls[1]).toEqual(mockedApi.post.mock.calls[0]);
});
test("a pending history restore reports success in the current language", async () => {
const held = deferred<any>(); mockedApi.post.mockReturnValueOnce(held.promise);
renderPage(); await importReady(); navigate(en.careerWorkspaceProfileTab);
fireEvent.click(screen.getByRole("button", { name: /Version history/ }));
fireEvent.click(screen.getByRole("button", { name: "Restore v1" }));
expect(mockedApi.post).toHaveBeenCalledWith("/career/profile/versions/1/restore", { expectedVersion: 7 });
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })));
await act(async () => held.resolve(source));
expect(screen.getByText(nb.profileUpdated)).toBeVisible();
expect(screen.queryByText(en.profileUpdated)).not.toBeInTheDocument();
expect(readCount("/career/profile/versions")).toBe(2);
});
test.each(["resolve", "reject"] as const)("an unmounted restore ignores a late POST %s with a surviving toast provider", async outcome => {
const held = deferred<any>(); mockedApi.post.mockReturnValueOnce(held.promise);
const view = renderPage(); await importReady(); navigate(en.careerWorkspaceProfileTab);
fireEvent.click(screen.getByRole("button", { name: /Version history/ }));
fireEvent.click(screen.getByRole("button", { name: "Restore v1" }));
view.rerender(<ToastProvider><I18nProvider><div>Other page</div></I18nProvider></ToastProvider>);
await act(async () => outcome === "resolve" ? held.resolve(source) : held.reject(new Error("Late restore failure")));
expect(readCount("/career/profile/versions")).toBe(1);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
test.each(["invalidated", "changed"] as const)("a restore cannot continue after its session is %s", async outcome => {
const held = deferred<any>(); mockedApi.post.mockReturnValueOnce(held.promise);
renderPage(); await importReady(); navigate(en.careerWorkspaceProfileTab);
fireEvent.click(screen.getByRole("button", { name: /Version history/ }));
fireEvent.click(screen.getByRole("button", { name: "Restore v1" }));
if (outcome === "invalidated") jest.mocked(isSessionInvalidated).mockReturnValue(true);
else jest.mocked(getSessionContext).mockReturnValue("another-session");
await act(async () => held.resolve(source));
expect(readCount("/career/profile/versions")).toBe(1);
expect(screen.queryByText(en.profileUpdated)).not.toBeInTheDocument();
expect(screen.queryByText(en.careerRestoreFailed)).not.toBeInTheDocument();
});
test.each(["resolve", "reject"] as const)("a restore history refresh ignores a late %s after unmount", async outcome => {
const history = deferred<any>();
const read = mockedApi.get.getMockImplementation()!;
const view = renderPage(); await importReady(); navigate(en.careerWorkspaceProfileTab);
mockedApi.get.mockImplementation((url: string) => url === "/career/profile/versions" ? history.promise : read(url));
fireEvent.click(screen.getByRole("button", { name: /Version history/ }));
fireEvent.click(screen.getByRole("button", { name: "Restore v1" }));
await waitFor(() => expect(readCount("/career/profile/versions")).toBe(2));
view.rerender(<ToastProvider><I18nProvider><div>Other page</div></I18nProvider></ToastProvider>);
await act(async () => outcome === "resolve" ? history.resolve({ data: versions }) : history.reject(new Error("Late history failure")));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
test("an operation cancellation is guarded while pending and leaves an unsaved source draft intact", async () => {
runs = [{ ...run, status: "queued", operation: { id: "op-81", status: "queued", canCancel: true, canRetry: false } }];
const held = deferred<any>(); mockedApi.post.mockReturnValue(held.promise);
+32 -7
View File
@@ -29,6 +29,7 @@ import {
} from "./career/CareerProfileSections";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import { checkSessionCookie, getSessionContext, isSessionInvalidated } from "../sessionBoundary";
import { useAccountPlan } from "../accountPlan";
import type { TranslationKey } from "../i18n/translations";
import ProFeatureNotice from "../components/ProFeatureNotice";
@@ -171,6 +172,24 @@ export default function CareerProfilePage() {
const { language, t } = useI18n();
const translationRef = useRef(t);
useEffect(() => { translationRef.current = t; }, [t]);
const session = useRef({ mounted: true, generation: 0 });
useEffect(() => {
const owner = session.current;
owner.mounted = true;
owner.generation += 1;
return () => { owner.mounted = false; owner.generation += 1; };
}, []);
const captureSession = useCallback(() => {
checkSessionCookie();
const owner = session.current;
if (!owner.mounted || isSessionInvalidated()) return null;
const context = getSessionContext();
const generation = owner.generation;
return () => {
checkSessionCookie();
return owner.mounted && owner.generation === generation && !isSessionInvalidated() && getSessionContext() === context;
};
}, []);
const cvInputRef = useRef<HTMLInputElement | null>(null);
const avatarInputRef = useRef<HTMLInputElement | null>(null);
const [me, setMe] = useState<MeResponse | null>(null);
@@ -218,28 +237,33 @@ export default function CareerProfilePage() {
}, []);
const loadVersions = useCallback(async () => {
const active = captureSession();
if (!active) return;
const readId = ++versionsReadId.current;
setVersionsLoading(true);
try {
const r = await api.get<CareerVersion[]>("/career/profile/versions");
if (readId === versionsReadId.current) {
if (active() && readId === versionsReadId.current) {
setVersions(r.data ?? []);
setVersionsError(null);
}
} catch (error) {
if (readId === versionsReadId.current) setVersionsError(getApiErrorMessage(error, ""));
if (active() && readId === versionsReadId.current) setVersionsError(getApiErrorMessage(error, ""));
} finally {
if (readId === versionsReadId.current) setVersionsLoading(false);
if (active() && readId === versionsReadId.current) setVersionsLoading(false);
}
}, []);
}, [captureSession]);
const restoreVersion = useCallback(async (version: number) => {
if (profileMutationPending.current || me?.provider !== "local" || loading || profileDirty) return;
const active = captureSession();
if (!active) return;
profileMutationPending.current = true;
setLoading(true);
setRestoreError(null);
try {
const r = await api.post<CareerProfileResponse>(`/career/profile/versions/${version}/restore`, { expectedVersion: profileRevision });
if (!active()) return;
setProfileRevision(r.data.revision);
setProfileCvText(r.data.cvText ?? "");
setStructuredCv(normalizeStructuredCv(r.data?.profile ?? emptyStructuredCv()));
@@ -247,16 +271,17 @@ export default function CareerProfilePage() {
setProfileDirty(false);
invalidateImportComparisons();
await loadVersions();
toast(t("profileUpdated"), "success");
if (active()) toast(translationRef.current("profileUpdated"), "success");
} catch (error) {
if (!active()) return;
const message = (error as { response?: { status?: number } }).response?.status === 409 ? "revision_conflict" : getApiErrorMessage(error, "");
setRestoreError(message);
toast(message === "revision_conflict" ? translationRef.current("revisionConflict") : message || translationRef.current("careerRestoreFailed"), "error");
} finally {
profileMutationPending.current = false;
setLoading(false);
if (active()) setLoading(false);
}
}, [loadVersions, loading, me?.provider, profileDirty, profileRevision, t, toast]);
}, [captureSession, loadVersions, loading, me?.provider, profileDirty, profileRevision, toast]);
const [extractionRuns, setExtractionRuns] = useState<ExtractionRun[]>([]);
const [runsLoading, setRunsLoading] = useState(true);
const [runsLoadError, setRunsLoadError] = useState<string | null>(null);