From d030c3f59f66309c2cdaf52c006b7fd41e57d8be Mon Sep 17 00:00:00 2001 From: Shinuwa Date: Wed, 11 Nov 2026 15:12:34 +0100 Subject: [PATCH] Stop orphan game links from blocking global imports A game link could outlive its toolbox when one tab linked a game while another tab, unaware of that link, deleted the toolbox. Auto-backups and manual exports then copied the orphan link, and the global import rejected the whole file. - Drop links to missing toolboxes inside the IndexedDB transaction. - Remove orphan links already stored when the page loads. - Ignore a link request to a toolbox that no longer exists. - Leave orphan links out of exports and skip them on global import, so older backups import again. Co-Authored-By: Claude Opus 5.5 --- .beads/interactions.jsonl | 2 + e2e/persistence.spec.js | 28 ++++++++++++++ tests/persistence-queue.test.mjs | 18 +++++++++ tests/toolbox-import-validation.test.mjs | 35 ++++++++++++++++-- .../storage/toolboxImportValidation.js | 3 +- .../toolboxes/storage/toolboxStorage.js | 10 ++++- .../toolboxes/storage/useIndexedToolboxes.js | 8 +++- .../features/toolboxes/useToolboxActions.js | 5 ++- website/src/utils/indexedDbStorage.js | 37 ++++++++++++++++++- 9 files changed, 137 insertions(+), 9 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index e8efc99..f8d8e3f 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -319,3 +319,5 @@ {"id":"int-2642091412a820a6521b354808de0b39","kind":"field_change","created_at":"2026-11-09T10:25:39.662355866Z","actor":"Shinuwa","issue_id":"sokko-g-t7nx","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Collection long-night ajoutée au catalogue (inactive) : 30 cartes, images webp, lore documenté"}} {"id":"int-a88b8e1a2c7f8a4d970921494533f421","kind":"field_change","created_at":"2026-11-09T10:51:47.512008767Z","actor":"Shinuwa","issue_id":"sokko-g-n3mf","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Descriptions de collection raccourcies (62/63 car.), tests e2e admin mis à jour (4 collections) ; test:e2e:cards 11/11, tests unitaires 251/251, lint OK"}} {"id":"int-c17c3702be7114f750b1f97592c4142c","kind":"field_change","created_at":"2026-11-09T12:23:33.595084433Z","actor":"Shinuwa","issue_id":"sokko-g-3ijw","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}} +{"id":"int-e910f5b4c041480fb8e708c515e62f6d","kind":"field_change","created_at":"2026-11-11T14:02:45.210027976Z","actor":"Shinuwa","issue_id":"sokko-g-0ku7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Associations orphelines écartées au chargement, à l'export et à l'import global ; le fichier .local/sokkog-global-2026-11-11.json s'importe (3 toolboxes, 24 outils)."}} +{"id":"int-f91a8b7bc318291bfa072ad6cff3b328","kind":"field_change","created_at":"2026-11-11T14:11:39.343142458Z","actor":"Shinuwa","issue_id":"sokko-g-ocss","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"mutateToolboxStorage retire dans la même transaction toute association vers une toolbox absente ; removeOrphanLinks nettoie la base au chargement ; linkToolboxToGame ignore une toolbox absente. Test e2e deux onglets : échoue sans la correction, passe avec."}} diff --git a/e2e/persistence.spec.js b/e2e/persistence.spec.js index aa66405..fda0f41 100644 --- a/e2e/persistence.spec.js +++ b/e2e/persistence.spec.js @@ -185,3 +185,31 @@ test("a stale toolbox replacement shows a conflict and reloads the confirmed ver expect(confirmed.toolboxes.find((toolbox) => toolbox.name === "Version distante")).toBeTruthy(); expect(confirmed.toolboxes.find((toolbox) => toolbox.name === "Version locale")).toBeFalsy(); }); + +test("deleting a toolbox also removes game links written by another tab", async ({ page, context }) => { + await resetSokkoStorage(page); + const otherPage = await context.newPage(); + await otherPage.goto("/"); + const toolbox = (id) => ({ id, name: id, modules: [] }); + const empty = { toolboxes: [], links: {}, moduleData: {} }; + const both = { toolboxes: [toolbox("a"), toolbox("b")], links: {}, moduleData: {} }; + expect(await runMutation(page, empty, both)).toEqual({ ok: true }); + + // L'autre onglet associe un jeu à « a » ; cet onglet supprime « a » sans avoir vu l'association. + expect(await runMutation(otherPage, both, { ...both, links: { game: "a", other: "b" } })).toEqual({ ok: true }); + expect(await runMutation(page, both, { ...both, toolboxes: [toolbox("b")] })).toEqual({ ok: true }); + + const links = await page.evaluate(async () => (await import("/src/utils/indexedDbStorage.js")).getLinks()); + expect(links).toEqual({ other: "b" }); +}); + +test("orphan game links already stored are removed from IndexedDB", async ({ page }) => { + await resetSokkoStorage(page); + const result = await page.evaluate(async () => { + const db = await import("/src/utils/indexedDbStorage.js"); + await db.setToolboxSnapshot([{ id: "kept", modules: [] }], { mhwilds: "deleted", diablo4: "kept" }, {}); + const removed = await db.removeOrphanLinks(); + return { removed, links: await db.getLinks(), again: await db.removeOrphanLinks() }; + }); + expect(result).toEqual({ removed: 1, links: { diablo4: "kept" }, again: 0 }); +}); diff --git a/tests/persistence-queue.test.mjs b/tests/persistence-queue.test.mjs index d9f4008..5466847 100644 --- a/tests/persistence-queue.test.mjs +++ b/tests/persistence-queue.test.mjs @@ -244,6 +244,24 @@ test("failed toolbox deletion preserves registry links and modules together", as assert.deepEqual(queue.getCurrent(), initial); }); +test("a game cannot be linked to a toolbox that no longer exists", async () => { + let state = { toolboxes: [{ id: "kept", modules: [] }], links: { game: "kept" }, moduleData: {} }; + const actions = useToolboxActions({ + store: { + ready: true, + ...state, + persistToolboxSnapshot: async (apply) => { + state = { ...state, ...apply(state) }; + return true; + } + } + }); + await actions.linkToolboxToGame("other", "deleted"); + assert.deepEqual(state.links, { game: "kept" }); + await actions.linkToolboxToGame("other", "kept"); + assert.deepEqual(state.links, { game: "kept", other: "kept" }); +}); + test("storage mutations target independent records and preserve deferred media deletions", () => { const expected = { toolboxes: [{ id: "a", modules: [{ id: "media", type: "images" }] }], diff --git a/tests/toolbox-import-validation.test.mjs b/tests/toolbox-import-validation.test.mjs index c8de9b5..d7aa4a4 100644 --- a/tests/toolbox-import-validation.test.mjs +++ b/tests/toolbox-import-validation.test.mjs @@ -171,7 +171,7 @@ test("orphan storage, space and business references are rejected", () => { assert.throws(() => validateToolboxImportPayload(memos), /identifiant dupliqué/); }); -test("global imports reject duplicate toolboxes, orphan module keys and orphan game links", () => { +test("global imports reject duplicate toolboxes and orphan module keys", () => { const toolbox = sourceToolbox(); const payload = createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData()); validateToolboxImportPayload(payload, "global"); @@ -185,8 +185,37 @@ test("global imports reject duplicate toolboxes, orphan module keys and orphan g assert.throws(() => validateToolboxImportPayload(moduleData, "global"), /ne correspond à aucun outil déclaré/); const link = clone(payload); - link.links.game = "missing"; - assert.throws(() => validateToolboxImportPayload(link, "global"), /links\.game référence l'identifiant absent/); + link.links.game = 3; + assert.throws(() => validateToolboxImportPayload(link, "global"), /links\.game doit être une chaîne non vide/); +}); + +test("a global export drops game links whose toolbox no longer exists", () => { + const toolbox = sourceToolbox(); + const payload = createGlobalExportPayload([toolbox], { game: toolbox.id, removed: "deleted-toolbox" }, sourceModuleData()); + assert.deepEqual(payload.links, { game: toolbox.id }); +}); + +test("a global import skips orphan game links from older backups instead of failing", async () => { + const toolbox = sourceToolbox(); + const payload = JSON.parse(JSON.stringify(createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData()))); + payload.links.removed = "deleted-toolbox"; + let state = { toolboxes: [], links: {}, moduleData: {} }; + const actions = useToolboxActions({ + store: { + ready: true, + links: { removed: "existing" }, + persistToolboxSnapshot: async (updater) => { + state = { ...state, ...updater(state) }; + return true; + } + }, + notify() {}, + setConfirmModal: (value) => assert.fail(value.message) + }); + + assert.equal(await actions.importAllToolboxes({ text: async () => JSON.stringify(payload) }), true); + assert.deepEqual(Object.keys(state.links), ["game"]); + assert.equal(state.links.game, state.toolboxes[0].id); }); test("a global import remaps toolbox, game and planner references together", async () => { diff --git a/website/src/features/toolboxes/storage/toolboxImportValidation.js b/website/src/features/toolboxes/storage/toolboxImportValidation.js index 991582e..8266b32 100644 --- a/website/src/features/toolboxes/storage/toolboxImportValidation.js +++ b/website/src/features/toolboxes/storage/toolboxImportValidation.js @@ -292,9 +292,10 @@ export function validateToolboxImportPayload(payload, mode = "single") { }); validateModuleData(validated, payload.modules, true); assertRecord(payload.links, "links"); + // Une association vers une toolbox absente vient d'une ancienne sauvegarde : elle est ignorée à l'import. for (const [gameId, toolboxId] of Object.entries(payload.links)) { assertString(gameId, "identifiant de jeu"); - assertReference(toolboxId, toolboxIds, `links.${gameId}`, { allowEmpty: false }); + assertString(toolboxId, `links.${gameId}`, { allowColon: false }); } return payload; } diff --git a/website/src/features/toolboxes/storage/toolboxStorage.js b/website/src/features/toolboxes/storage/toolboxStorage.js index 8e4199c..a9a9de6 100644 --- a/website/src/features/toolboxes/storage/toolboxStorage.js +++ b/website/src/features/toolboxes/storage/toolboxStorage.js @@ -510,6 +510,14 @@ export function createToolboxExportPayload(toolbox, moduleData) { return { version: 2, toolbox: exportedToolbox, modules }; } +// Ne garde que les associations de jeu dont la toolbox existe encore. +export function pruneGameLinks(links, toolboxes) { + if (!links || typeof links !== "object") return {}; + const toolboxIds = new Set((toolboxes || []).map((toolbox) => toolbox?.id)); + return Object.fromEntries(Object.entries(links) + .filter(([, toolboxId]) => typeof toolboxId === "string" && toolboxIds.has(toolboxId))); +} + export function createGlobalExportPayload(toolboxes, links, moduleData) { const modules = {}; toolboxes.forEach((toolbox) => { @@ -523,6 +531,6 @@ export function createGlobalExportPayload(toolboxes, links, moduleData) { exportedAt: new Date().toISOString(), toolboxes: compactToolboxesForStorage(toolboxes), modules, - links + links: pruneGameLinks(links, toolboxes) }; } diff --git a/website/src/features/toolboxes/storage/useIndexedToolboxes.js b/website/src/features/toolboxes/storage/useIndexedToolboxes.js index 7a5d2c7..4f49e64 100644 --- a/website/src/features/toolboxes/storage/useIndexedToolboxes.js +++ b/website/src/features/toolboxes/storage/useIndexedToolboxes.js @@ -8,13 +8,15 @@ import { getToolboxSnapshot as dbGetToolboxSnapshot, getToolboxes as dbGetToolboxes, mutateToolboxStorage as dbMutateToolboxStorage, + removeOrphanLinks as dbRemoveOrphanLinks, setSetting as dbSetSetting, } from "../../../utils/indexedDbStorage.js"; import { compactToolboxesForStorage, moduleStorageKey, normalizeToolbox, - prepareModuleDataForStorage + prepareModuleDataForStorage, + pruneGameLinks } from "./toolboxStorage.js"; import { applyModuleDataValue, removeModuleDataKeys } from "./optimisticModuleData.js"; import { createPersistenceQueue } from "./persistenceQueue.js"; @@ -62,7 +64,7 @@ async function readStoredState({ preservedModuleData = {}, refreshedModuleKeys = } return { toolboxes: normalizedToolboxes, - links: links && typeof links === "object" ? links : {}, + links: pruneGameLinks(links, normalizedToolboxes), moduleData, toastPosition: toastPosition === "left" ? "left" : "right" }; @@ -107,6 +109,8 @@ export function useIndexedToolboxes(onError) { let cancelled = false; async function loadStore() { try { + // Le nettoyage est accessoire : un échec ne doit pas empêcher le chargement. + await dbRemoveOrphanLinks().catch(() => 0); const storedState = await readStoredState(); if (cancelled) return; queue.initialize(storedState); diff --git a/website/src/features/toolboxes/useToolboxActions.js b/website/src/features/toolboxes/useToolboxActions.js index 4957d71..45bd300 100644 --- a/website/src/features/toolboxes/useToolboxActions.js +++ b/website/src/features/toolboxes/useToolboxActions.js @@ -7,6 +7,7 @@ import { globalModuleKey, labelFromFileName, normalizeToolbox, + pruneGameLinks, remapMemosPlannerLink, remapModuleOrderIds, uid @@ -198,6 +199,7 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte function linkToolboxToGame(gameId, toolboxId) { const updatedAt = new Date().toISOString(); return store.persistToolboxSnapshot((current) => { + if (toolboxId && !current.toolboxes.some((toolbox) => toolbox.id === toolboxId)) return current; const links = { ...current.links }; const touched = new Set([links[gameId], toolboxId].filter(Boolean)); if (toolboxId) links[gameId] = toolboxId; @@ -431,7 +433,8 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte importAllToolboxes: async (file) => { if (!store.ready) return false; try { - const payload = validateToolboxImportPayload(JSON.parse(await file.text()), "global"); + const validated = validateToolboxImportPayload(JSON.parse(await file.text()), "global"); + const payload = { ...validated, links: pruneGameLinks(validated.links, validated.toolboxes) }; const reassignedLinks = Object.keys(payload.links || {}).filter((gameId) => store.links?.[gameId]); const runImport = () => importAllToolboxesPayload(payload).then(() => true); const imported = reassignedLinks.length diff --git a/website/src/utils/indexedDbStorage.js b/website/src/utils/indexedDbStorage.js index bbd9dab..c7ceca6 100644 --- a/website/src/utils/indexedDbStorage.js +++ b/website/src/utils/indexedDbStorage.js @@ -232,6 +232,39 @@ function applyToolboxChanges(current, mutation, conflicts) { return [...remote, ...ordered]; } +function keepLinksToToolboxes(links, toolboxIds) { + return Object.fromEntries(Object.entries(links || {}) + .filter(([, toolboxId]) => typeof toolboxId === "string" && toolboxIds.has(toolboxId))); +} + +// Retire du stockage les associations de jeu dont la toolbox n'existe plus. +export async function removeOrphanLinks() { + const db = await openDatabase(); + let removed = 0; + await new Promise((resolve, reject) => { + const transaction = db.transaction(KV_STORE, "readwrite"); + const kv = transaction.objectStore(KV_STORE); + const toolboxRequest = kv.get("toolboxes"); + const linksRequest = kv.get("links"); + let remaining = 2; + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + transaction.onabort = () => reject(transaction.error); + function cleanWhenReady() { + remaining -= 1; + if (remaining) return; + const links = linksRequest.result && typeof linksRequest.result === "object" ? linksRequest.result : {}; + const toolboxIds = new Set((Array.isArray(toolboxRequest.result) ? toolboxRequest.result : []).map((toolbox) => toolbox?.id)); + const kept = keepLinksToToolboxes(links, toolboxIds); + removed = Object.keys(links).length - Object.keys(kept).length; + if (removed) kv.put(kept, "links"); + } + toolboxRequest.onsuccess = cleanWhenReady; + linksRequest.onsuccess = cleanWhenReady; + }); + return removed; +} + export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (value) => value } = {}) { if (!mutation?.changed) return; const db = await openDatabase(); @@ -291,7 +324,9 @@ export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (val } if (mutation.toolboxes.changes.length || mutation.toolboxes.order) kv.put(nextToolboxes, "toolboxes"); - if (mutation.links.length) kv.put(nextLinks, "links"); + // Une toolbox supprimée emporte aussi les associations écrites par un autre onglet. + const keptLinks = keepLinksToToolboxes(nextLinks, validToolboxIds); + if (mutation.links.length || !storageValuesEqual(keptLinks, currentLinks)) kv.put(keptLinks, "links"); for (const change of mutation.modules) { if (change.nextExists) modules.put({ key: change.key, data: change.nextValue }); else modules.delete(change.key);