diff --git a/job-tracker-ui/src/attachment-action-lifetime.test.tsx b/job-tracker-ui/src/attachment-action-lifetime.test.tsx new file mode 100644 index 00000000..296af3f0 --- /dev/null +++ b/job-tracker-ui/src/attachment-action-lifetime.test.tsx @@ -0,0 +1,93 @@ +import React from "react"; +import "@testing-library/jest-dom"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import Attachments from "./components/Attachments"; +import { ConfirmProvider } from "./confirm"; +import { PromptProvider } from "./prompt"; +import { ToastProvider } from "./toast"; +import { I18nProvider } from "./i18n/I18nProvider"; +import { translations } from "./i18n/translations"; +import { api } from "./api"; + +let mockSessionActive = true; +jest.mock("./sessionBoundary", () => ({ + checkSessionCookie: jest.fn(), + getSessionContext: () => "attachment-owner", + isSessionInvalidated: () => !mockSessionActive, +})); +jest.mock("./api", () => ({ + getApiErrorMessage: (_error: unknown, fallback: string) => fallback, + api: { get: jest.fn(), post: jest.fn(), patch: jest.fn(), delete: jest.fn() }, +})); +const mockedApi = api as jest.Mocked; +const file = { id: 7, fileName: "Recorded.pdf", fileType: "application/pdf", fileSize: 42, uploadDate: "2026-11-03T10:00:00Z" }; +function page(jobId = 42, visible = true) { + return {visible ? :
Other workflow
}
; +} +function deferred() { + let resolve!: (value: any) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} +beforeEach(() => { + jest.resetAllMocks(); + mockSessionActive = true; + localStorage.removeItem("uiLanguage"); + mockedApi.get.mockResolvedValue({ data: [file] } as any); + mockedApi.patch.mockResolvedValue({ data: {} } as any); + mockedApi.delete.mockResolvedValue({ data: {} } as any); +}); +afterEach(() => localStorage.removeItem("uiLanguage")); +async function open(action: "rename" | "delete") { + const view = render(page()); + fireEvent.click(await screen.findByRole("button", { name: `${action === "rename" ? "Rename" : "Delete"}: ${file.fileName}` })); + const dialog = await screen.findByRole("dialog"); + if (action === "rename") fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "New name.pdf" } }); + return { view, dialog }; +} +test.each([ + ["rename", "unmount"], ["rename", "job change"], ["rename", "session"], + ["delete", "unmount"], ["delete", "job change"], ["delete", "session"], +] as const)("attachment %s decision after %s cannot mutate the previous context", async (action, boundary) => { + const { view, dialog } = await open(action); + if (boundary === "session") mockSessionActive = false; + else await act(async () => { view.rerender(page(77, boundary !== "unmount")); }); + const reads = mockedApi.get.mock.calls.length; + fireEvent.click(within(dialog).getByRole("button", { name: action === "rename" ? "Rename" : "Delete" })); + await act(async () => undefined); + expect(mockedApi.patch).not.toHaveBeenCalled(); + expect(mockedApi.delete).not.toHaveBeenCalled(); + expect(mockedApi.get).toHaveBeenCalledTimes(reads); +}); +test.each([ + ["rename", "resolve"], ["rename", "reject"], + ["delete", "resolve"], ["delete", "reject"], +] as const)("attachment %s delayed %s uses current language", async (action, outcome) => { + const pending = deferred(); + const write = action === "rename" ? mockedApi.patch : mockedApi.delete; + write.mockReturnValueOnce(pending.promise); + const { dialog } = await open(action); + fireEvent.click(within(dialog).getByRole("button", { name: action === "rename" ? "Rename" : "Delete" })); + await waitFor(() => expect(write).toHaveBeenCalledTimes(1)); + await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })); }); + await act(async () => { if (outcome === "resolve") pending.resolve({ data: {} }); else pending.reject(new Error("synthetic write failure")); }); + const key = action === "rename" ? outcome === "resolve" ? "attachmentsRenamed" : "attachmentsRenameFailed" : outcome === "resolve" ? "attachmentsDeleted" : "attachmentsDeleteFailed"; + expect(await screen.findByText(translations.nb[key])).toBeVisible(); + expect(screen.queryByText(translations.en[key])).not.toBeInTheDocument(); + expect(write).toHaveBeenCalledWith("/attachments/7", ...(action === "rename" ? [{ fileName: "New name.pdf" }] : [])); +}); + +test.each((['rename', 'delete'] as const).flatMap(action => (['unmount', 'job change'] as const).flatMap(boundary => (['resolve', 'reject'] as const).map(outcome => [action, boundary, outcome] as const))))('late attachment %s after %s / %s cannot reload or notify', async (action, boundary, outcome) => { + const pending = deferred(); + const write = action === 'rename' ? mockedApi.patch : mockedApi.delete; + write.mockReturnValueOnce(pending.promise); + const { view, dialog } = await open(action); + fireEvent.click(within(dialog).getByRole('button', { name: action === 'rename' ? 'Rename' : 'Delete' })); + await waitFor(() => expect(write).toHaveBeenCalledTimes(1)); + await act(async () => { view.rerender(page(77, boundary !== 'unmount')); }); + const reads = mockedApi.get.mock.calls.length; + await act(async () => { if (outcome === 'resolve') pending.resolve({ data: {} }); else pending.reject(new Error('obsolete write failure')); }); + expect(mockedApi.get).toHaveBeenCalledTimes(reads); + for (const key of ['attachmentsRenamed', 'attachmentsRenameFailed', 'attachmentsDeleted', 'attachmentsDeleteFailed'] as const) expect(screen.queryByText(translations.en[key])).not.toBeInTheDocument(); +}); diff --git a/job-tracker-ui/src/components/Attachments.tsx b/job-tracker-ui/src/components/Attachments.tsx index 82e51cd5..ed06827b 100644 --- a/job-tracker-ui/src/components/Attachments.tsx +++ b/job-tracker-ui/src/components/Attachments.tsx @@ -36,6 +36,7 @@ import { useToast } from "../toast"; import { useI18n } from "../i18n/I18nProvider"; import { useDialogActions } from "../dialogs"; import ViewStateNotice from "./ViewStateNotice"; +import { checkSessionCookie, getSessionContext, isSessionInvalidated } from "../sessionBoundary"; interface AttachmentItem { id: number; @@ -99,6 +100,27 @@ export default function Attachments({ jobId }: { jobId: number }) { const [dragActive, setDragActive] = useState(false); const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); + const actionOwner = useRef({ mounted: true, jobId, generation: 0 }); + + useEffect(() => { + const owner = actionOwner.current; + owner.mounted = true; + owner.jobId = jobId; + owner.generation += 1; + return () => { owner.mounted = false; owner.generation += 1; }; + }, [jobId]); + + const captureAction = () => { + checkSessionCookie(); + const owner = actionOwner.current; + if (!owner.mounted || owner.jobId !== jobId || isSessionInvalidated()) return null; + const generation = owner.generation; + const context = getSessionContext(); + return () => { + checkSessionCookie(); + return owner.mounted && owner.jobId === jobId && owner.generation === generation && !isSessionInvalidated() && getSessionContext() === context; + }; + }; const load = useCallback(async () => { setLoading(true); @@ -148,14 +170,17 @@ export default function Attachments({ jobId }: { jobId: number }) { ); const rename = async (a: AttachmentItem) => { + const active = captureAction(); + if (!active) return; const next = await promptForValue({ key: "attachmentsRenamePrompt" }, a.fileName, { title: { key: "attachmentsRenameTitle" }, confirmLabel: { key: "attachmentsRename" } }); - if (!next || next.trim() === a.fileName) return; + if (!active() || !next || next.trim() === a.fileName) return; try { await api.patch(`/attachments/${a.id}`, { fileName: next.trim() }); - toast(t("attachmentsRenamed"), "success"); + if (!active()) return; + toast(currentT.current("attachmentsRenamed"), "success"); await load(); } catch (error) { - toast(getApiErrorMessage(error, t("attachmentsRenameFailed")), "error"); + if (active()) toast(getApiErrorMessage(error, currentT.current("attachmentsRenameFailed")), "error"); } }; @@ -170,13 +195,17 @@ export default function Attachments({ jobId }: { jobId: number }) { }; const remove = async (a: AttachmentItem) => { + const active = captureAction(); + if (!active) return; if (!(await confirmAction({ key: "attachmentsDeleteConfirm", params: { name: a.fileName } }, { title: { key: "attachmentsDeleteTitle" }, confirmLabel: { key: "attachmentsDelete" }, destructive: true }))) return; + if (!active()) return; try { await api.delete(`/attachments/${a.id}`); - toast(t("attachmentsDeleted"), "success"); + if (!active()) return; + toast(currentT.current("attachmentsDeleted"), "success"); await load(); } catch (error) { - toast(getApiErrorMessage(error, t("attachmentsDeleteFailed")), "error"); + if (active()) toast(getApiErrorMessage(error, currentT.current("attachmentsDeleteFailed")), "error"); } };