fix(attachments): guard upload and metadata completion context

This commit is contained in:
cesnimda
2026-11-17 07:49:30 +01:00
parent 6c8a2f67f8
commit a877b97d1e
2 changed files with 65 additions and 7 deletions
@@ -160,3 +160,55 @@ test.each(['Download', 'Preview'] as const)('delayed attachment %s failure uses
expect(await screen.findByText(translations.nb[key])).toBeVisible();
expect(screen.queryByText(translations.en[key])).not.toBeInTheDocument();
});
async function beginMutation(action: 'upload' | 'metadata', pending: ReturnType<typeof deferred>) {
const write = action === 'upload' ? mockedApi.post : mockedApi.patch;
write.mockReturnValueOnce(pending.promise);
const view = render(page());
await screen.findByText(file.fileName);
if (action === 'upload') fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [new File(['synthetic upload'], 'New.pdf', { type: 'application/pdf' })] } });
else fireEvent.click(screen.getByRole('switch', { name: `Use for AI: ${file.fileName}` }));
await waitFor(() => expect(write).toHaveBeenCalledTimes(1));
return { view, write };
}
test.each((['upload', 'metadata'] as const).flatMap(action => (['unmount', 'job change', 'session'] as const).flatMap(boundary => (['resolve', 'reject'] as const).map(outcome => [action, boundary, outcome] as const))))('late attachment %s after %s / %s has no stale completion', async (action, boundary, outcome) => {
const pending = deferred();
const { view } = await beginMutation(action, pending);
if (boundary === 'session') mockSessionActive = false;
else 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 mutation failure')); });
expect(mockedApi.get).toHaveBeenCalledTimes(reads);
for (const key of ['attachmentsUploadedSingle', 'attachmentsUploadFailed', 'attachmentsUpdated', 'attachmentsUpdateFailed'] as const) expect(screen.queryByText(translations.en[key])).not.toBeInTheDocument();
});
test.each((['upload', 'metadata'] as const).flatMap(action => (['resolve', 'reject'] as const).map(outcome => [action, outcome] as const)))('delayed attachment %s / %s uses current-language mutation feedback', async (action, outcome) => {
const pending = deferred();
const { write } = await beginMutation(action, pending);
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 mutation failure')); });
const key = action === 'upload' ? outcome === 'resolve' ? 'attachmentsUploadedSingle' : 'attachmentsUploadFailed' : outcome === 'resolve' ? 'attachmentsUpdated' : 'attachmentsUpdateFailed';
expect(await screen.findByText(translations.nb[key])).toBeVisible();
expect(screen.queryByText(translations.en[key])).not.toBeInTheDocument();
expect(write).toHaveBeenCalledTimes(1);
});
test.each(['resolve', 'reject'] as const)('old upload %s cannot clear a new application upload busy state', async outcome => {
const previous = deferred();
const current = deferred();
const { view } = await beginMutation('upload', previous);
await act(async () => { view.rerender(page(77)); });
const upload = screen.getByRole('button', { name: translations.en.attachmentsUpload });
expect(upload).toBeEnabled();
mockedApi.post.mockReturnValueOnce(current.promise);
fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [new File(['new context'], 'Current.pdf')] } });
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledTimes(2));
expect(screen.getByRole('button', { name: translations.en.attachmentsUploading })).toBeDisabled();
const reads = mockedApi.get.mock.calls.length;
await act(async () => { if (outcome === 'resolve') previous.resolve({ data: {} }); else previous.reject(new Error('old upload failure')); });
expect(mockedApi.get).toHaveBeenCalledTimes(reads);
expect(screen.getByRole('button', { name: translations.en.attachmentsUploading })).toBeDisabled();
await act(async () => current.resolve({ data: {} }));
await waitFor(() => expect(screen.getByRole('button', { name: translations.en.attachmentsUpload })).toBeEnabled());
});
+13 -7
View File
@@ -107,6 +107,7 @@ export default function Attachments({ jobId }: { jobId: number }) {
owner.mounted = true;
owner.jobId = jobId;
owner.generation += 1;
setUploading(false);
return () => { owner.mounted = false; owner.generation += 1; };
}, [jobId]);
@@ -150,7 +151,8 @@ export default function Attachments({ jobId }: { jobId: number }) {
const uploadFiles = useCallback(
async (files: File[]) => {
if (!files.length) return;
const active = captureAction();
if (!active || !files.length) return;
const data = new FormData();
files.forEach((f) => data.append("files", f));
@@ -161,15 +163,16 @@ export default function Attachments({ jobId }: { jobId: number }) {
await api.post("/attachments", data, {
headers: { "Content-Type": "multipart/form-data" },
});
toast(files.length === 1 ? t("attachmentsUploadedSingle") : t("attachmentsUploadedMany", { count: files.length }), "success");
if (!active()) return;
toast(files.length === 1 ? currentT.current("attachmentsUploadedSingle") : currentT.current("attachmentsUploadedMany", { count: files.length }), "success");
await load();
} catch (error) {
toast(getApiErrorMessage(error, t("attachmentsUploadFailed")), "error");
if (active()) toast(getApiErrorMessage(error, currentT.current("attachmentsUploadFailed")), "error");
} finally {
setUploading(false);
if (active()) setUploading(false);
}
},
[jobId, load, t, toast],
[jobId, load, captureAction, toast],
);
const rename = async (a: AttachmentItem) => {
@@ -188,12 +191,15 @@ export default function Attachments({ jobId }: { jobId: number }) {
};
const updateMetadata = async (a: AttachmentItem, patch: Partial<Pick<AttachmentItem, "purpose" | "useForAi">>) => {
const active = captureAction();
if (!active) return;
try {
await api.patch(`/attachments/${a.id}`, { purpose: patch.purpose ?? a.purpose ?? guessKind(a.fileName), useForAi: patch.useForAi ?? a.useForAi });
if (!active()) return;
setItems((current) => current.map((item) => item.id === a.id ? { ...item, ...patch } : item));
toast(t("attachmentsUpdated"), "success");
toast(currentT.current("attachmentsUpdated"), "success");
} catch (error) {
toast(getApiErrorMessage(error, t("attachmentsUpdateFailed")), "error");
if (active()) toast(getApiErrorMessage(error, currentT.current("attachmentsUpdateFailed")), "error");
}
};