From c011c036574fc11258db8283ad162f264c020aad Mon Sep 17 00:00:00 2001 From: "HomePC\\Kevin" Date: Wed, 7 Oct 2026 21:02:03 +0200 Subject: [PATCH] fix(import): explain unconfirmed upload outcomes without raw error keys --- .../Migration/Hooks/useMigrationLogic.ts | 12 +- .../NpmImport/Hooks/useNpmImportLogic.ts | 12 +- .../Admin/Migration/importRequestErrors.ts | 24 +++ web/src/lib/Language/Locales/de.json | 6 +- web/src/lib/Language/Locales/en.json | 6 +- web/src/lib/Language/Locales/es.json | 6 +- web/src/lib/Language/Locales/fr.json | 6 +- web/src/lib/Language/Locales/it.json | 6 +- web/src/lib/Language/Locales/nl.json | 6 +- web/src/lib/Language/Locales/pl.json | 6 +- web/src/lib/Language/Locales/pt.json | 6 +- .../import-request-errors-ui.test.tsx | 173 ++++++++++++++++++ 12 files changed, 241 insertions(+), 28 deletions(-) create mode 100644 web/src/lib/Admin/Migration/importRequestErrors.ts create mode 100644 web/src/tests/features/Admin/Migration/import-request-errors-ui.test.tsx diff --git a/web/src/features/Admin/Migration/Hooks/useMigrationLogic.ts b/web/src/features/Admin/Migration/Hooks/useMigrationLogic.ts index 6b6c5ee42..865c17437 100644 --- a/web/src/features/Admin/Migration/Hooks/useMigrationLogic.ts +++ b/web/src/features/Admin/Migration/Hooks/useMigrationLogic.ts @@ -3,6 +3,10 @@ import { useEffect, useState } from 'react' import { toast } from '@rentnerkev/toasts/toast' import useTranslationStore from '@/shared/Language/Hooks/useTranslationStore.ts' +import { + ImportResponseError, + getImportRequestErrorCode, +} from '@/lib/Admin/Migration/importRequestErrors.ts' import type { NpmImportPreview, NpmImportResult, @@ -36,11 +40,7 @@ async function upload( }) const data: unknown = await response.json() if (!response.ok) { - const code = - data && typeof data === 'object' && 'error' in data - ? String(data.error) - : 'import_failed' - throw new Error(code) + throw new ImportResponseError(data, 'migration') } return data } @@ -137,7 +137,7 @@ export function useMigrationLogic(): MigrationLogicResult { } } } catch (caught) { - const code = caught instanceof Error ? caught.message : 'import_failed' + const code = getImportRequestErrorCode(caught) setError(code) toast.error(t(`admin.migration.errors.${code}`), { title: t('toast.titles.error'), diff --git a/web/src/features/Admin/NpmImport/Hooks/useNpmImportLogic.ts b/web/src/features/Admin/NpmImport/Hooks/useNpmImportLogic.ts index 4c507e4d4..f6a782372 100644 --- a/web/src/features/Admin/NpmImport/Hooks/useNpmImportLogic.ts +++ b/web/src/features/Admin/NpmImport/Hooks/useNpmImportLogic.ts @@ -1,5 +1,9 @@ import type { NpmImportLogicResult } from '../Types/npm-import-logic.types.ts' import { useEffect, useState } from 'react' +import { + ImportResponseError, + getImportRequestErrorCode, +} from '@/lib/Admin/Migration/importRequestErrors.ts' import type { NpmImportPreview, NpmImportResult } from '../Types/npm-import.types.ts' @@ -27,11 +31,7 @@ async function upload( }) const data: unknown = await response.json() if (!response.ok) { - const code = - data && typeof data === 'object' && 'error' in data - ? String(data.error) - : 'import_failed' - throw new Error(code) + throw new ImportResponseError(data, 'npmImport') } return data } @@ -77,7 +77,7 @@ export function useNpmImportLogic(): NpmImportLogicResult { setHistory((current) => [next, ...current].slice(0, 20)) } } catch (caught) { - setError(caught instanceof Error ? caught.message : 'import_failed') + setError(getImportRequestErrorCode(caught)) if (mode === 'apply') { setPreview(null) void loadHistory() diff --git a/web/src/lib/Admin/Migration/importRequestErrors.ts b/web/src/lib/Admin/Migration/importRequestErrors.ts new file mode 100644 index 000000000..1285908ff --- /dev/null +++ b/web/src/lib/Admin/Migration/importRequestErrors.ts @@ -0,0 +1,24 @@ +export class ImportResponseError extends Error { + constructor(data: unknown, source: 'migration' | 'npmImport') { + const code = + data && typeof data === 'object' && 'error' in data && typeof data.error === 'string' + ? data.error + : '' + const recognized = [ + 'authentication_required', + 'permission_denied', + 'source_limit', + 'invalid_source', + 'unsupported_schema', + 'fingerprint_mismatch', + 'preview_changed', + 'import_failed', + ...(source === 'npmImport' ? ['nothing_to_import'] : []), + ].includes(code) + super(recognized ? code : 'request_failed') + } +} + +export function getImportRequestErrorCode(error: unknown): string { + return error instanceof ImportResponseError ? error.message : 'request_failed' +} diff --git a/web/src/lib/Language/Locales/de.json b/web/src/lib/Language/Locales/de.json index 3296f4a53..d351d8e74 100644 --- a/web/src/lib/Language/Locales/de.json +++ b/web/src/lib/Language/Locales/de.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "Die Datei hat sich seit der Vorschau geändert. Erneut analysieren.", "preview_changed": "Der RentnerProxy-Stand hat sich seit der Vorschau geändert. Erneut analysieren.", "import_failed": "Import fehlgeschlagen; Änderungen wurden zurückgerollt. Audit-Log prüfen.", - "export_failed": "Export fehlgeschlagen. Erneut versuchen oder Audit-Log prüfen." + "export_failed": "Export fehlgeschlagen. Erneut versuchen oder Audit-Log prüfen.", + "request_failed": "Die Importanfrage konnte nicht bestätigt werden. Prüfe deine Verbindung und sieh im Importverlauf nach, bevor du es erneut versuchst." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "Die Quelle hat sich seit der Vorschau geändert. Erneut analysieren.", "preview_changed": "Der RentnerProxy-Stand hat sich seit der Vorschau geändert. Vor dem Import erneut analysieren.", "nothing_to_import": "Keine geeigneten Objekte mehr vorhanden. Den aktuellen Stand erneut analysieren.", - "import_failed": "Import fehlgeschlagen; die Datenbanktransaktion wurde zurückgerollt. Audit-Log prüfen." + "import_failed": "Import fehlgeschlagen; die Datenbanktransaktion wurde zurückgerollt. Audit-Log prüfen.", + "request_failed": "Die Importanfrage konnte nicht bestätigt werden. Prüfe deine Verbindung und sieh im Importverlauf nach, bevor du es erneut versuchst." } }, "users": { diff --git a/web/src/lib/Language/Locales/en.json b/web/src/lib/Language/Locales/en.json index a44a5c07e..85f49340f 100644 --- a/web/src/lib/Language/Locales/en.json +++ b/web/src/lib/Language/Locales/en.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "The file changed since preview. Analyze it again.", "preview_changed": "RentnerProxy changed since preview. Analyze it again.", "import_failed": "Import failed; changes were rolled back. Check the audit log.", - "export_failed": "Export failed. Try again or check the audit log." + "export_failed": "Export failed. Try again or check the audit log.", + "request_failed": "Could not confirm the import request. Check your connection and review import history before trying again." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "The source changed after preview. Analyze it again.", "preview_changed": "RentnerProxy state changed after preview. Analyze again before importing.", "nothing_to_import": "Nothing remains eligible to import. Analyze the latest state again.", - "import_failed": "Import failed and its database transaction was rolled back. Check the audit log." + "import_failed": "Import failed and its database transaction was rolled back. Check the audit log.", + "request_failed": "Could not confirm the import request. Check your connection and review import history before trying again." } }, "users": { diff --git a/web/src/lib/Language/Locales/es.json b/web/src/lib/Language/Locales/es.json index 2426c248f..5f028fbd5 100644 --- a/web/src/lib/Language/Locales/es.json +++ b/web/src/lib/Language/Locales/es.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "El archivo cambió desde la vista previa. Analízalo otra vez.", "preview_changed": "RentnerProxy cambió desde la vista previa. Analízalo otra vez.", "import_failed": "La importación falló; se revirtieron los cambios. Revisa la auditoría.", - "export_failed": "La exportación falló. Inténtalo otra vez o revisa la auditoría." + "export_failed": "La exportación falló. Inténtalo otra vez o revisa la auditoría.", + "request_failed": "No se pudo confirmar la solicitud de importación. Comprueba tu conexión y revisa el historial de importaciones antes de volver a intentarlo." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "La fuente cambió desde la vista previa. Analízala de nuevo.", "preview_changed": "El estado de RentnerProxy cambió desde la vista previa. Analiza de nuevo.", "nothing_to_import": "No quedan objetos aptos para importar. Analiza de nuevo.", - "import_failed": "La importación falló y la transacción se revirtió. Consulta el registro de auditoría." + "import_failed": "La importación falló y la transacción se revirtió. Consulta el registro de auditoría.", + "request_failed": "No se pudo confirmar la solicitud de importación. Comprueba tu conexión y revisa el historial de importaciones antes de volver a intentarlo." } }, "users": { diff --git a/web/src/lib/Language/Locales/fr.json b/web/src/lib/Language/Locales/fr.json index 7ef7e8cfe..6c658512d 100644 --- a/web/src/lib/Language/Locales/fr.json +++ b/web/src/lib/Language/Locales/fr.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "Le fichier a changé depuis l'aperçu. Analysez-le à nouveau.", "preview_changed": "RentnerProxy a changé depuis l'aperçu. Analysez à nouveau.", "import_failed": "L'import a échoué ; les modifications ont été annulées. Consultez l'audit.", - "export_failed": "L'export a échoué. Réessayez ou consultez l'audit." + "export_failed": "L'export a échoué. Réessayez ou consultez l'audit.", + "request_failed": "Impossible de confirmer la demande d’importation. Vérifiez votre connexion et consultez l’historique des imports avant de réessayer." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "La source a changé depuis l’aperçu. Analysez-la de nouveau.", "preview_changed": "L’état de RentnerProxy a changé depuis l’aperçu. Analysez de nouveau.", "nothing_to_import": "Aucun objet admissible ne reste à importer. Analysez de nouveau.", - "import_failed": "Import échoué ; la transaction a été annulée. Consultez le journal d’audit." + "import_failed": "Import échoué ; la transaction a été annulée. Consultez le journal d’audit.", + "request_failed": "Impossible de confirmer la demande d’importation. Vérifiez votre connexion et consultez l’historique des imports avant de réessayer." } }, "users": { diff --git a/web/src/lib/Language/Locales/it.json b/web/src/lib/Language/Locales/it.json index 66ba848cf..a55cedb8a 100644 --- a/web/src/lib/Language/Locales/it.json +++ b/web/src/lib/Language/Locales/it.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "Il file è cambiato dopo l’anteprima. Analizzalo di nuovo.", "preview_changed": "RentnerProxy è cambiato dopo l’anteprima. Analizzalo di nuovo.", "import_failed": "Importazione non riuscita; le modifiche sono state annullate. Controlla il registro di audit.", - "export_failed": "Esportazione non riuscita. Riprova o controlla il registro di audit." + "export_failed": "Esportazione non riuscita. Riprova o controlla il registro di audit.", + "request_failed": "Impossibile confermare la richiesta di importazione. Controlla la connessione e consulta la cronologia delle importazioni prima di riprovare." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "L’origine è cambiata dopo l’anteprima. Analizzala di nuovo.", "preview_changed": "Lo stato di RentnerProxy è cambiato dopo l’anteprima. Analizzalo di nuovo prima di importare.", "nothing_to_import": "Non resta nulla di idoneo per l’importazione. Analizza di nuovo lo stato più recente.", - "import_failed": "Importazione non riuscita e transazione del database annullata. Controlla il registro di audit." + "import_failed": "Importazione non riuscita e transazione del database annullata. Controlla il registro di audit.", + "request_failed": "Impossibile confermare la richiesta di importazione. Controlla la connessione e consulta la cronologia delle importazioni prima di riprovare." } }, "users": { diff --git a/web/src/lib/Language/Locales/nl.json b/web/src/lib/Language/Locales/nl.json index 9eab66a9d..30ae695ee 100644 --- a/web/src/lib/Language/Locales/nl.json +++ b/web/src/lib/Language/Locales/nl.json @@ -524,7 +524,8 @@ "fingerprint_mismatch": "Het bestand is gewijzigd sinds de preview. Analyseer het opnieuw.", "preview_changed": "RentnerProxy is gewijzigd sinds de preview. Analyseer het opnieuw.", "import_failed": "Importeren is mislukt; de wijzigingen zijn teruggedraaid. Controleer het auditlogboek.", - "export_failed": "Exporteren is mislukt. Probeer het opnieuw of controleer het auditlogboek." + "export_failed": "Exporteren is mislukt. Probeer het opnieuw of controleer het auditlogboek.", + "request_failed": "Het importverzoek kon niet worden bevestigd. Controleer je verbinding en bekijk de importgeschiedenis voordat je het opnieuw probeert." } }, "npmImport": { @@ -619,7 +620,8 @@ "fingerprint_mismatch": "De bron is gewijzigd na de preview. Analyseer deze opnieuw.", "preview_changed": "De RentnerProxy-status is gewijzigd na de preview. Analyseer opnieuw voordat je importeert.", "nothing_to_import": "Er is niets meer dat kan worden geïmporteerd. Analyseer de nieuwste status opnieuw.", - "import_failed": "Importeren is mislukt en de databasetransactie is teruggedraaid. Controleer het auditlogboek." + "import_failed": "Importeren is mislukt en de databasetransactie is teruggedraaid. Controleer het auditlogboek.", + "request_failed": "Het importverzoek kon niet worden bevestigd. Controleer je verbinding en bekijk de importgeschiedenis voordat je het opnieuw probeert." } }, "users": { diff --git a/web/src/lib/Language/Locales/pl.json b/web/src/lib/Language/Locales/pl.json index 9bb5c14a6..ef6b486de 100644 --- a/web/src/lib/Language/Locales/pl.json +++ b/web/src/lib/Language/Locales/pl.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "Plik uległ zmianie od czasu podglądu. Przeanalizuj go ponownie.", "preview_changed": "Stan RentnerProxy uległ zmianie od czasu podglądu. Przeanalizuj go ponownie.", "import_failed": "Import nie powiódł się; zmiany zostały wycofane. Sprawdź dziennik audytu.", - "export_failed": "Eksport nie powiódł się. Spróbuj ponownie lub sprawdź dziennik audytu." + "export_failed": "Eksport nie powiódł się. Spróbuj ponownie lub sprawdź dziennik audytu.", + "request_failed": "Nie udało się potwierdzić żądania importu. Sprawdź połączenie i przejrzyj historię importów przed ponowną próbą." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "Źródło uległo zmianie po wyświetleniu podglądu. Przeanalizuj je ponownie.", "preview_changed": "Stan RentnerProxy uległ zmianie po wyświetleniu podglądu. Przeanalizuj go ponownie przed importem.", "nothing_to_import": "Nie ma już niczego, co można zaimportować. Ponownie przeanalizuj bieżący stan.", - "import_failed": "Import nie powiódł się, a transakcja bazy danych została wycofana. Sprawdź dziennik audytu." + "import_failed": "Import nie powiódł się, a transakcja bazy danych została wycofana. Sprawdź dziennik audytu.", + "request_failed": "Nie udało się potwierdzić żądania importu. Sprawdź połączenie i przejrzyj historię importów przed ponowną próbą." } }, "users": { diff --git a/web/src/lib/Language/Locales/pt.json b/web/src/lib/Language/Locales/pt.json index e5f0bfa72..c39664638 100644 --- a/web/src/lib/Language/Locales/pt.json +++ b/web/src/lib/Language/Locales/pt.json @@ -543,7 +543,8 @@ "fingerprint_mismatch": "O ficheiro foi alterado desde a pré-visualização. Analise-o novamente.", "preview_changed": "O RentnerProxy foi alterado desde a pré-visualização. Analise novamente.", "import_failed": "A importação falhou; as alterações foram revertidas. Consulte o registo de auditoria.", - "export_failed": "A exportação falhou. Tente novamente ou consulte o registo de auditoria." + "export_failed": "A exportação falhou. Tente novamente ou consulte o registo de auditoria.", + "request_failed": "Não foi possível confirmar o pedido de importação. Verifique a ligação e consulte o histórico de importações antes de tentar novamente." } }, "npmImport": { @@ -638,7 +639,8 @@ "fingerprint_mismatch": "A origem foi alterada depois da pré-visualização. Analise-a novamente.", "preview_changed": "O estado do RentnerProxy foi alterado depois da pré-visualização. Analise novamente antes de importar.", "nothing_to_import": "Não há mais nada elegível para importar. Analise novamente o estado mais recente.", - "import_failed": "A importação falhou e a transação da base de dados foi revertida. Consulte o registo de auditoria." + "import_failed": "A importação falhou e a transação da base de dados foi revertida. Consulte o registo de auditoria.", + "request_failed": "Não foi possível confirmar o pedido de importação. Verifique a ligação e consulte o histórico de importações antes de tentar novamente." } }, "users": { diff --git a/web/src/tests/features/Admin/Migration/import-request-errors-ui.test.tsx b/web/src/tests/features/Admin/Migration/import-request-errors-ui.test.tsx new file mode 100644 index 000000000..c307e638a --- /dev/null +++ b/web/src/tests/features/Admin/Migration/import-request-errors-ui.test.tsx @@ -0,0 +1,173 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' +import { GlobalRegistrator } from '@happy-dom/global-registrator' +import type { Root } from 'react-dom/client' + +import { INPUT_PROVIDER_PROPS } from '@/config/input.config.ts' +import { TOAST_PROVIDER_PROPS } from '@/config/toast.config.ts' +import disableMotionAnimations from '@/tests/Helpers/disableMotionAnimations.ts' +import withTestLanguage from '@/tests/Helpers/withTestLanguage.tsx' + +if (!GlobalRegistrator.isRegistered) GlobalRegistrator.register() +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) +disableMotionAnimations() + +const { InputProvider } = await import('@rentnerkev/inputs') +const { SelectProvider } = await import('@rentnerkev/select') +const { ToastProvider } = await import('@rentnerkev/toasts') +const { toast } = await import('@rentnerkev/toasts/toast') +const { TooltipProvider } = await import('@rentnerkev/tooltips/tooltip') +const { act } = await import('react') +const { createRoot } = await import('react-dom/client') +const { default: MigrationPage } = await import('@/features/Admin/Migration/MigrationPage.tsx') +const { default: NpmImportPage } = await import('@/features/Admin/NpmImport/NpmImportPage.tsx') + +const uncertainty = + 'Could not confirm the import request. Check your connection and review import history before trying again.' +let root: Root | null = null +const fetchMock = spyOn(globalThis, 'fetch') + +beforeEach(() => fetchMock.mockResolvedValue(Response.json([]))) +afterEach(async () => { + await act(async () => root?.unmount()) + root = null + toast.dismissAll() + fetchMock.mockClear() + document.body.replaceChildren() +}) + +async function render(kind: 'migration' | 'npmImport'): Promise { + const container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => { + root?.render( + withTestLanguage( + + + + + {kind === 'migration' ? : } + + + + , + ), + ) + }) + const input = container.querySelector('input[type="file"]')! + Object.defineProperty(input, 'files', { + configurable: true, + value: [new File(['fixture'], 'config.db')], + }) + await act(async () => input.dispatchEvent(new Event('change', { bubbles: true }))) + return container +} + +async function clickPreview(container: HTMLElement): Promise { + const button = [...container.querySelectorAll('button')].find( + (candidate) => candidate.textContent?.trim() === 'Analyze and preview', + )! + await act(async () => button.click()) +} + +for (const kind of ['migration', 'npmImport'] as const) { + describe(`${kind} import request feedback`, () => { + test('explains rejected fetch without claiming rollback or printing an error key', async () => { + const container = await render(kind) + fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch')) + await clickPreview(container) + expect(container.querySelector('[role="alert"]')?.textContent).toContain(uncertainty) + expect(container.textContent).not.toContain('rolled back') + expect(container.textContent).not.toContain('errors.Failed to fetch') + if (kind === 'migration') + expect(document.querySelector('.rentnerproxy-toast-error')?.textContent).toContain( + uncertainty, + ) + }) + + test('explains HTML gateway failures as an unconfirmed request', async () => { + const container = await render(kind) + fetchMock.mockResolvedValueOnce( + new Response('Bad gateway', { status: 502 }), + ) + await clickPreview(container) + expect(container.querySelector('[role="alert"]')?.textContent).toContain(uncertainty) + expect(container.textContent).not.toContain('Unexpected token') + }) + + test('preserves localized explanations for recognized backend errors', async () => { + const container = await render(kind) + fetchMock.mockResolvedValueOnce( + Response.json({ error: 'fingerprint_mismatch' }, { status: 409 }), + ) + await clickPreview(container) + expect(container.querySelector('[role="alert"]')?.textContent).toContain('changed') + expect(container.querySelector('[role="alert"]')?.textContent).toContain('Analyze') + expect(container.textContent).not.toContain(uncertainty) + }) + + test('maps unknown backend errors to the uncertainty explanation', async () => { + const container = await render(kind) + fetchMock.mockResolvedValueOnce( + Response.json({ error: 'internal_stack_details' }, { status: 500 }), + ) + await clickPreview(container) + expect(container.querySelector('[role="alert"]')?.textContent).toContain(uncertainty) + expect(container.textContent).not.toContain('internal_stack_details') + }) + + test('reloads history after a lost apply response without retrying the mutation', async () => { + const container = await render(kind) + const item = { + kind: 'proxy-host', + sourceId: 1, + label: 'Imported after response loss', + domains: ['edge.example.com'], + status: 'ready', + reasons: [], + } + fetchMock.mockResolvedValueOnce( + Response.json({ + fingerprint: 'source', + planFingerprint: 'plan', + sourceSchema: 'fixture', + items: [item], + counts: { ready: 1, partial: 0, manual: 0, conflict: 0 }, + }), + ) + await clickPreview(container) + const apply = [...container.querySelectorAll('button')].find( + (button) => button.textContent?.trim() === 'Confirm import', + )! + expect(apply).toBeDefined() + const result = { + runId: 'completed-run', + status: 'completed', + fingerprint: 'source', + sourceSchema: 'fixture', + items: [{ ...item, outcome: 'imported' }], + imported: 1, + skipped: 0, + failed: 0, + runtimeStatus: 'applied', + } + fetchMock.mockRejectedValueOnce(new TypeError('response lost')) + fetchMock.mockResolvedValueOnce(Response.json([result])) + await act(async () => { + apply.click() + await new Promise((resolve) => setTimeout(resolve, 20)) + }) + expect(container.querySelector('[role="alert"]')?.textContent).toContain(uncertainty) + expect(container.textContent).toContain('Imported after response loss') + expect( + container.querySelector( + 'section[aria-labelledby="npm-preview-title"], section[aria-labelledby="migration-preview-title"]', + ), + ).toBeNull() + expect(fetchMock.mock.calls.filter((call) => call[1]?.method === 'POST')).toHaveLength( + 2, + ) + expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBeUndefined() + }) + }) +}