From 42a5b66bf052049fd77d78d92c98662f248f7608 Mon Sep 17 00:00:00 2001
From: Mistium <92952823+Mistium@users.noreply.github.com>
Date: Tue, 6 Oct 2026 19:26:28 +0100
Subject: [PATCH 1/9] Keep IndexedDB failures from leaking out of storage
modules
Fixes production errors from browsers without usable IndexedDB (PS4 and
iOS lockdown Safari, Firefox strict and private modes) and from flaky
connections:
- "indexedDB is not supported", "IDB Error UnknownError: Internal error.",
"Transaction error: UnknownError" and Firefox "IDBFactory.open: The
operation is insecure" from the render-interface chunk: the packager's
large-asset cache ran its cleanup at import, so every editor, player
and fullscreen load opened the database and left the result unhandled.
The cleanup now runs on first use of the cache and logs failures.
- "Can't find variable: indexedDB", "IDBFactory.open: The operation is
insecure", "Unable to open database file on disk" and QuotaExceededError
from project history (LightningFS): the open promise was already marked
handled, but a failed activation stayed cached and LightningFS
re-awaited it from its deactivation timer, and its debounced superblock
flush had no handler either. Failed activations are cleared so the next
operation retries, and the two timers log instead of rejecting.
- "The database connection is closing" from idb-keyval: a closing or
browser-closed connection is forgotten and reopened once. idb-keyval
also forgets a failed open, so storage that recovers works again, and
closing a store that never opened resolves.
- The packager cache and the local backpack reopen a closing connection
once, and the backpack rejects aborted transactions instead of hanging.
---
package.json | 3 +-
patches/@isomorphic-git__idb-keyval.patch | 142 ++++++++++++++++++++
patches/@isomorphic-git__lightning-fs.patch | 80 ++++++-----
pnpm-lock.yaml | 13 +-
src/lib/api/local-backpack.js | 40 ++++--
src/packager/common/idb.js | 12 +-
src/packager/packager/web/cache.js | 10 +-
test/unit/indexeddb-unavailable.test.js | 134 ++++++++++++++++++
8 files changed, 380 insertions(+), 54 deletions(-)
create mode 100644 patches/@isomorphic-git__idb-keyval.patch
create mode 100644 test/unit/indexeddb-unavailable.test.js
diff --git a/package.json b/package.json
index a2babc31c3f..5aba44a715c 100644
--- a/package.json
+++ b/package.json
@@ -172,7 +172,8 @@
"@isomorphic-git/lightning-fs": "patches/@isomorphic-git__lightning-fs.patch",
"scratch-parser": "patches/scratch-parser.patch",
"@turbowarp/scratch-svg-renderer": "patches/@turbowarp__scratch-svg-renderer.patch",
- "rotur-sdk@2.5.2": "patches/rotur-sdk@2.5.2.patch"
+ "rotur-sdk@2.5.2": "patches/rotur-sdk@2.5.2.patch",
+ "@isomorphic-git/idb-keyval": "patches/@isomorphic-git__idb-keyval.patch"
},
"allowUnusedPatches": true
},
diff --git a/patches/@isomorphic-git__idb-keyval.patch b/patches/@isomorphic-git__idb-keyval.patch
new file mode 100644
index 00000000000..489b2b97779
--- /dev/null
+++ b/patches/@isomorphic-git__idb-keyval.patch
@@ -0,0 +1,142 @@
+diff --git a/dist/idb-keyval-cjs.js b/dist/idb-keyval-cjs.js
+index d8b578d3e669600ab0dc84248d42609454de6abf..0f646c6cc6a25bf76691bbc83f856dfec930b7a1 100644
+--- a/dist/idb-keyval-cjs.js
++++ b/dist/idb-keyval-cjs.js
+@@ -13,32 +13,52 @@ class Store {
+ if (this._dbp) {
+ return;
+ }
+- this._dbp = new Promise((resolve, reject) => {
++ const dbp = this._dbp = new Promise((resolve, reject) => {
+ const openreq = indexedDB.open(this._dbName);
+ openreq.onerror = () => reject(openreq.error);
+- openreq.onsuccess = () => resolve(openreq.result);
++ openreq.onsuccess = () => {
++ openreq.result.onclose = () => this._forget(dbp);
++ resolve(openreq.result);
++ };
+ // First time setup: create an empty object store
+ openreq.onupgradeneeded = () => {
+ openreq.result.createObjectStore(this._storeName);
+ };
+ });
++ dbp.catch(() => this._forget(dbp));
+ }
+- _withIDBStore(type, callback) {
+- this._init();
+- return this._dbp.then(db => new Promise((resolve, reject) => {
+- const transaction = db.transaction(this.storeName, type);
+- transaction.oncomplete = () => resolve();
+- transaction.onabort = transaction.onerror = () => reject(transaction.error);
+- callback(transaction.objectStore(this.storeName));
+- }));
++ _forget(dbp) {
++ if (this._dbp === dbp) {
++ this._dbp = undefined;
++ }
+ }
+- _close() {
++ _withIDBStore(type, callback, reopened = false) {
+ this._init();
+- return this._dbp.then(db => {
+- db.close();
+- this._dbp = undefined;
++ const dbp = this._dbp;
++ return dbp.then(db => {
++ let transaction;
++ try {
++ transaction = db.transaction(this.storeName, type);
++ } catch (error) {
++ if (reopened || error.name !== 'InvalidStateError') throw error;
++ this._forget(dbp);
++ return this._withIDBStore(type, callback, true);
++ }
++ return new Promise((resolve, reject) => {
++ transaction.oncomplete = () => resolve();
++ transaction.onabort = transaction.onerror = () => reject(transaction.error);
++ callback(transaction.objectStore(this.storeName));
++ });
+ });
+ }
++ _close() {
++ const dbp = this._dbp;
++ this._dbp = undefined;
++ if (!dbp) {
++ return Promise.resolve();
++ }
++ return dbp.then(db => db.close(), () => {});
++ }
+ }
+ let store;
+ function getDefaultStore() {
+diff --git a/dist/idb-keyval.mjs b/dist/idb-keyval.mjs
+index 295ef23c5e1c0e6fc70232ef3da7277a2dc01b08..07c6e03c5b3344f89b38a4f06d53f74e650a23da 100644
+--- a/dist/idb-keyval.mjs
++++ b/dist/idb-keyval.mjs
+@@ -9,32 +9,52 @@ class Store {
+ if (this._dbp) {
+ return;
+ }
+- this._dbp = new Promise((resolve, reject) => {
++ const dbp = this._dbp = new Promise((resolve, reject) => {
+ const openreq = indexedDB.open(this._dbName);
+ openreq.onerror = () => reject(openreq.error);
+- openreq.onsuccess = () => resolve(openreq.result);
++ openreq.onsuccess = () => {
++ openreq.result.onclose = () => this._forget(dbp);
++ resolve(openreq.result);
++ };
+ // First time setup: create an empty object store
+ openreq.onupgradeneeded = () => {
+ openreq.result.createObjectStore(this._storeName);
+ };
+ });
++ dbp.catch(() => this._forget(dbp));
+ }
+- _withIDBStore(type, callback) {
+- this._init();
+- return this._dbp.then(db => new Promise((resolve, reject) => {
+- const transaction = db.transaction(this.storeName, type);
+- transaction.oncomplete = () => resolve();
+- transaction.onabort = transaction.onerror = () => reject(transaction.error);
+- callback(transaction.objectStore(this.storeName));
+- }));
++ _forget(dbp) {
++ if (this._dbp === dbp) {
++ this._dbp = undefined;
++ }
+ }
+- _close() {
++ _withIDBStore(type, callback, reopened = false) {
+ this._init();
+- return this._dbp.then(db => {
+- db.close();
+- this._dbp = undefined;
++ const dbp = this._dbp;
++ return dbp.then(db => {
++ let transaction;
++ try {
++ transaction = db.transaction(this.storeName, type);
++ } catch (error) {
++ if (reopened || error.name !== 'InvalidStateError') throw error;
++ this._forget(dbp);
++ return this._withIDBStore(type, callback, true);
++ }
++ return new Promise((resolve, reject) => {
++ transaction.oncomplete = () => resolve();
++ transaction.onabort = transaction.onerror = () => reject(transaction.error);
++ callback(transaction.objectStore(this.storeName));
++ });
+ });
+ }
++ _close() {
++ const dbp = this._dbp;
++ this._dbp = undefined;
++ if (!dbp) {
++ return Promise.resolve();
++ }
++ return dbp.then(db => db.close(), () => {});
++ }
+ }
+ let store;
+ function getDefaultStore() {
diff --git a/patches/@isomorphic-git__lightning-fs.patch b/patches/@isomorphic-git__lightning-fs.patch
index b21176a6d18..a735b432f51 100644
--- a/patches/@isomorphic-git__lightning-fs.patch
+++ b/patches/@isomorphic-git__lightning-fs.patch
@@ -1,8 +1,8 @@
diff --git a/src/DefaultBackend.js b/src/DefaultBackend.js
-index d0563618bc975277ee39193858534a294892e6ce..e3ff3efa6a0c9840875dd7c6834d5349edeb4394 100644
+index d0563618bc975277ee39193858534a294892e6ce..404899955f70bc35d7f3e0e6c51011cf8fc3d158 100644
--- a/src/DefaultBackend.js
+++ b/src/DefaultBackend.js
-@@ -6,7 +6,6 @@ const { ENOENT, ENOTEMPTY, ETIMEDOUT } = require("./errors.js");
+@@ -6,14 +6,13 @@ const { ENOENT, ENOTEMPTY, ETIMEDOUT } = require("./errors.js");
const IdbBackend = require("./IdbBackend.js");
const HttpBackend = require("./HttpBackend.js")
const Mutex = require("./Mutex.js");
@@ -10,6 +10,14 @@ index d0563618bc975277ee39193858534a294892e6ce..e3ff3efa6a0c9840875dd7c6834d5349
const path = require("./path.js");
+ module.exports = class DefaultBackend {
+ constructor() {
+ this.saveSuperblock = debounce(() => {
+- this.flush();
++ this.flush().catch(err => console.warn(err));
+ }, 500);
+ }
+ async init (name, {
@@ -28,7 +27,11 @@ module.exports = class DefaultBackend {
} = {}) {
this._name = name
@@ -23,32 +31,44 @@ index d0563618bc975277ee39193858534a294892e6ce..e3ff3efa6a0c9840875dd7c6834d5349
this._cache = new CacheFS(name);
this._opts = { wipe, url };
this._needsWipe = !!wipe;
-diff --git a/src/IdbBackend.js b/src/IdbBackend.js
-index c7af775e6e5e3a338256d7da872e05465b95b437..e51a3a36c7d785c7582a7a2c03189f0cb861bf45 100644
---- a/src/IdbBackend.js
-+++ b/src/IdbBackend.js
-@@ -5,6 +5,11 @@ module.exports = class IdbBackend {
- this._database = dbname;
- this._storename = storename;
- this._store = new idb.Store(this._database, this._storename);
-+ // idb-keyval opens the database in the constructor and leaves the promise
-+ // unhandled until the first operation. Safari private browsing and sandboxed
-+ // frames reject it, which surfaced as unhandled rejections. Operations still
-+ // chain from this promise and report the error to their callers.
-+ this._store._dbp.catch(() => {});
- }
- saveSuperblock(superblock) {
- return idb.set("!root", superblock, this._store);
-diff --git a/src/Mutex.js b/src/Mutex.js
-index d7df3579919eb4e3238fe0fdcbad73fb265b3c1b..75c9dd82763e672e3355c616936ab3c7c6d790ab 100644
---- a/src/Mutex.js
-+++ b/src/Mutex.js
-@@ -8,6 +8,8 @@ module.exports = class Mutex {
- this._database = dbname
- this._storename = storename
- this._store = new idb.Store(this._database, this._storename)
-+ // See IdbBackend: operations still receive the error.
-+ this._store._dbp.catch(() => {})
- this._lock = null
+diff --git a/src/PromisifiedFS.js b/src/PromisifiedFS.js
+index aaa6984556a2ecde5816efdd1ae280f318150312..04cc40ceaeaa47c7f5aa237375463f51906b68a4 100644
+--- a/src/PromisifiedFS.js
++++ b/src/PromisifiedFS.js
+@@ -121,7 +121,9 @@ module.exports = class PromisifiedFS {
+ if (mutating) this._backend.saveSuperblock() // this is debounced
+ if (this._operations.size === 0) {
+ if (!this._deactivationTimeout) clearTimeout(this._deactivationTimeout)
+- this._deactivationTimeout = setTimeout(this._deactivate.bind(this), 500)
++ this._deactivationTimeout = setTimeout(() => {
++ this._deactivate().catch(err => console.warn(err))
++ }, 500)
+ }
+ }
+ }
+@@ -136,7 +138,11 @@ module.exports = class PromisifiedFS {
+ if (this._deactivationPromise) await this._deactivationPromise
+ this._deactivationPromise = null
+ if (!this._activationPromise) {
+- this._activationPromise = this._backend.activate ? this._backend.activate() : Promise.resolve();
++ const activation = this._backend.activate ? this._backend.activate() : Promise.resolve();
++ this._activationPromise = activation
++ activation.catch(() => {
++ if (this._activationPromise === activation) this._activationPromise = null
++ })
+ }
+ await this._activationPromise
}
- async has ({ margin = 2000 } = {}) {
+@@ -144,7 +150,11 @@ module.exports = class PromisifiedFS {
+ if (this._activationPromise) await this._activationPromise
+
+ if (!this._deactivationPromise) {
+- this._deactivationPromise = this._backend.deactivate ? this._backend.deactivate() : Promise.resolve();
++ const deactivation = this._backend.deactivate ? this._backend.deactivate() : Promise.resolve();
++ this._deactivationPromise = deactivation
++ deactivation.catch(() => {
++ if (this._deactivationPromise === deactivation) this._deactivationPromise = null
++ })
+ }
+ this._activationPromise = null
+ if (this._gracefulShutdownResolve) this._gracefulShutdownResolve()
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 535659d5171..ff3f8fd2819 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,8 +8,11 @@ overrides:
cheerio: 1.0.0-rc.12
patchedDependencies:
+ '@isomorphic-git/idb-keyval':
+ hash: 15c74dd5ecbe503575c9e211bd71428ef95190ac599be6398519cb2a7cd2a255
+ path: patches/@isomorphic-git__idb-keyval.patch
'@isomorphic-git/lightning-fs':
- hash: 3918c5bc950ffdc268e7fa966eadf53e46df0c4efa8e3988911b315515322336
+ hash: 456a42c5e3dc06762bd6d34af7c52f1270b3dd2d1e77cc00c70642333cdd10bc
path: patches/@isomorphic-git__lightning-fs.patch
'@turbowarp/scratch-svg-renderer':
hash: 81a01d6d472570d53eec593be679e84867db1ba1410f5ef084d5c404068481b9
@@ -30,7 +33,7 @@ importers:
version: 0.0.7
'@isomorphic-git/lightning-fs':
specifier: ^4.6.2
- version: 4.6.2(patch_hash=3918c5bc950ffdc268e7fa966eadf53e46df0c4efa8e3988911b315515322336)
+ version: 4.6.2(patch_hash=456a42c5e3dc06762bd6d34af7c52f1270b3dd2d1e77cc00c70642333cdd10bc)
'@microbit/microbit-universal-hex':
specifier: 0.2.2
version: 0.2.2(tslib@2.8.1)
@@ -7373,11 +7376,11 @@ snapshots:
'@humanwhocodes/object-schema@2.0.3': {}
- '@isomorphic-git/idb-keyval@3.3.2': {}
+ '@isomorphic-git/idb-keyval@3.3.2(patch_hash=15c74dd5ecbe503575c9e211bd71428ef95190ac599be6398519cb2a7cd2a255)': {}
- '@isomorphic-git/lightning-fs@4.6.2(patch_hash=3918c5bc950ffdc268e7fa966eadf53e46df0c4efa8e3988911b315515322336)':
+ '@isomorphic-git/lightning-fs@4.6.2(patch_hash=456a42c5e3dc06762bd6d34af7c52f1270b3dd2d1e77cc00c70642333cdd10bc)':
dependencies:
- '@isomorphic-git/idb-keyval': 3.3.2
+ '@isomorphic-git/idb-keyval': 3.3.2(patch_hash=15c74dd5ecbe503575c9e211bd71428ef95190ac599be6398519cb2a7cd2a255)
isomorphic-textencoder: 1.0.1
just-debounce-it: 1.1.0
just-once: 1.1.0
diff --git a/src/lib/api/local-backpack.js b/src/lib/api/local-backpack.js
index e6f410c32f6..10ff67931e0 100644
--- a/src/lib/api/local-backpack.js
+++ b/src/lib/api/local-backpack.js
@@ -89,8 +89,12 @@ const openDB = () => new Promise((resolve, reject) => {
};
request.onsuccess = event => {
- _db = event.target.result;
- resolve(_db);
+ const db = event.target.result;
+ db.onclose = () => {
+ if (_db === db) _db = null;
+ };
+ _db = db;
+ resolve(db);
};
request.onerror = event => {
@@ -98,14 +102,25 @@ const openDB = () => new Promise((resolve, reject) => {
};
});
+const openTransaction = async mode => {
+ const db = await openDB();
+ try {
+ return db.transaction(STORE_NAME, mode);
+ } catch (error) {
+ if (error.name !== 'InvalidStateError') throw error;
+ if (_db === db) _db = null;
+ const reopened = await openDB();
+ return reopened.transaction(STORE_NAME, mode);
+ }
+};
+
const getBackpackContents = async ({
limit,
offset
}) => {
- const db = await openDB();
+ const transaction = await openTransaction('readonly');
return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, 'readonly');
- transaction.onerror = event => {
+ transaction.onerror = transaction.onabort = event => {
reject(new Error(`Getting contents: ${event.target.error}`));
};
const store = transaction.objectStore(STORE_NAME);
@@ -141,10 +156,9 @@ const saveBackpackObject = async ({
// User interaction -- fine to show a permission dialog
requestPersistentStorage();
- const db = await openDB();
+ const transaction = await openTransaction('readwrite');
return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, 'readwrite');
- transaction.onerror = event => {
+ transaction.onerror = transaction.onabort = event => {
reject(new Error(`Sving object: ${event.target.error}`));
};
const store = transaction.objectStore(STORE_NAME);
@@ -170,10 +184,9 @@ const deleteBackpackObject = async ({
id
}) => {
id = +id;
- const db = await openDB();
+ const transaction = await openTransaction('readwrite');
return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, 'readwrite');
- transaction.onerror = event => {
+ transaction.onerror = transaction.onabort = event => {
reject(new Error(`Deleting object: ${event.target.error}`));
};
const store = transaction.objectStore(STORE_NAME);
@@ -190,10 +203,9 @@ const updateBackpackObject = async ({
name
}) => {
id = +id;
- const db = await openDB();
+ const transaction = await openTransaction('readwrite');
return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, 'readwrite');
- transaction.onerror = event => {
+ transaction.onerror = transaction.onabort = event => {
reject(new Error(`Updating object: ${event.target.error}`));
};
const store = transaction.objectStore(STORE_NAME);
diff --git a/src/packager/common/idb.js b/src/packager/common/idb.js
index 2e6e78c017b..c55bdc0c5e1 100644
--- a/src/packager/common/idb.js
+++ b/src/packager/common/idb.js
@@ -83,8 +83,16 @@ class Database {
}
async createTransaction (readwrite) {
- const db = await this.open();
- const transaction = db.transaction(this.storeName, readwrite);
+ let db = await this.open();
+ let transaction;
+ try {
+ transaction = db.transaction(this.storeName, readwrite);
+ } catch (e) {
+ if (e.name !== 'InvalidStateError') throw e;
+ if (this.db === db) this.db = null;
+ db = await this.open();
+ transaction = db.transaction(this.storeName, readwrite);
+ }
const store = transaction.objectStore(this.storeName);
return {
db,
diff --git a/src/packager/packager/web/cache.js b/src/packager/packager/web/cache.js
index 333402c54b8..882923848e7 100644
--- a/src/packager/packager/web/cache.js
+++ b/src/packager/packager/web/cache.js
@@ -39,7 +39,15 @@ const removeExtraneous = async () => {
});
};
+let cleanupStarted = false;
+
const get = async (asset) => {
+ if (!cleanupStarted) {
+ cleanupStarted = true;
+ removeExtraneous().catch((err) => {
+ console.warn(err);
+ });
+ }
const {transaction, store} = await db.createTransaction('readonly');
return new Promise((resolve, reject) => {
Database.setTransactionErrorHandler(transaction, reject);
@@ -73,8 +81,6 @@ const set = async (asset, content) => {
const resetAll = () => db.deleteEverything();
-removeExtraneous();
-
export default {
get,
set,
diff --git a/test/unit/indexeddb-unavailable.test.js b/test/unit/indexeddb-unavailable.test.js
new file mode 100644
index 00000000000..71d1ee49c58
--- /dev/null
+++ b/test/unit/indexeddb-unavailable.test.js
@@ -0,0 +1,134 @@
+import v8 from 'v8';
+import {IDBDatabase, IDBFactory} from 'fake-indexeddb';
+
+jest.mock('virtual:packager-runtime', () => ({buildId: 'test', runtimeUrl: name => name}), {virtual: true});
+
+if (typeof global.structuredClone === 'undefined') {
+ global.structuredClone = value => v8.deserialize(v8.serialize(value));
+}
+
+const missing = () => {
+ delete global.indexedDB;
+ return null;
+};
+
+const insecure = () => {
+ const open = jest.fn(() => {
+ throw new DOMException('The operation is insecure.', 'SecurityError');
+ });
+ global.indexedDB = {open};
+ return open;
+};
+
+const working = () => {
+ global.indexedDB = new IDBFactory();
+ return global.indexedDB;
+};
+
+const load = path => {
+ let loaded;
+ jest.isolateModules(() => {
+ loaded = require(path);
+ });
+ return loaded.default || loaded;
+};
+
+const settle = ms => new Promise(resolve => setTimeout(resolve, ms));
+
+const closingOnce = () => jest.spyOn(IDBDatabase.prototype, 'transaction').mockImplementationOnce(() => {
+ throw new DOMException('The database connection is closing.', 'InvalidStateError');
+});
+
+let warn;
+
+
+beforeEach(() => {
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ jest.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ jest.restoreAllMocks();
+ delete global.indexedDB;
+});
+
+describe.each([
+ ['indexedDB is undefined', missing],
+ ['indexedDB.open throws', insecure]
+])('when %s', (name, block) => {
+ test('project history storage rejects only to its callers and recovers later', async () => {
+ block();
+ const LightningFS = load('@isomorphic-git/lightning-fs');
+ const fs = new LightningFS(`history-${name}`, {defer: true}).promises;
+ await expect(fs.stat('/repo')).rejects.toBeTruthy();
+ await expect(fs.mkdir('/repo')).rejects.toBeTruthy();
+ await settle(700);
+
+ working();
+ await fs.mkdir('/repo');
+ expect((await fs.stat('/repo')).isDirectory()).toBe(true);
+ await settle(700);
+ });
+
+ test('loading the packager does not touch storage, and using its cache fails softly', async () => {
+ const open = block();
+ const cache = load('../../src/packager/packager/web/cache');
+ if (open) expect(open).not.toHaveBeenCalled();
+ await expect(cache.get({src: 'asset.js', sha256: 'abc'})).rejects.toBeTruthy();
+ await settle(10);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ test('the local backpack reports that it is unavailable', async () => {
+ block();
+ const backpack = load('../../src/lib/api/local-backpack');
+ await expect(backpack.getBackpackContents({limit: 20, offset: 0})).rejects.toThrow();
+ });
+});
+
+describe('a connection that is closing is reopened once', () => {
+ test('project history storage', async () => {
+ working();
+ const idb = load('@isomorphic-git/idb-keyval');
+ const store = new idb.Store('reopen-history', 'keyval');
+ await idb.set('key', 'value', store);
+ (await store._dbp).close();
+ expect(await idb.get('key', store)).toBe('value');
+ await idb.close(store);
+ await idb.close(store);
+ });
+
+ test('packager asset cache', async () => {
+ const factory = working();
+ const open = jest.spyOn(factory, 'open');
+ const Database = load('../../src/packager/common/idb');
+ const db = new Database('reopen-packager', 1, 'assets');
+ await db.open();
+ closingOnce();
+ const {store} = await db.createTransaction('readonly');
+ expect(store.name).toBe('assets');
+ expect(open).toHaveBeenCalledTimes(2);
+ db.close();
+ });
+
+ test('local backpack', async () => {
+ const factory = working();
+ const open = jest.spyOn(factory, 'open');
+ const backpack = load('../../src/lib/api/local-backpack');
+ expect(await backpack.getBackpackContents({limit: 20, offset: 0})).toEqual([]);
+ closingOnce();
+ expect(await backpack.getBackpackContents({limit: 20, offset: 0})).toEqual([]);
+ expect(open).toHaveBeenCalledTimes(2);
+ });
+
+ test('a second failure still reaches the caller', async () => {
+ working();
+ const idb = load('@isomorphic-git/idb-keyval');
+ const store = new idb.Store('reopen-twice', 'keyval');
+ await idb.set('key', 'value', store);
+ closingOnce();
+ closingOnce();
+ await expect(idb.get('key', store)).rejects.toMatchObject({name: 'InvalidStateError'});
+ expect(await idb.get('key', store)).toBe('value');
+ });
+});
From 7f4565631b04c86f961b9bc9b0b6cb59c80ef132 Mon Sep 17 00:00:00 2001
From: Mistium <92952823+Mistium@users.noreply.github.com>
Date: Tue, 6 Oct 2026 19:26:58 +0100
Subject: [PATCH 2/9] Re-index spotlight blocks when variables change
The block index was reused for as long as the same sprite was being edited, so after a variable, list or broadcast was deleted spotlight could still offer it. Picking that block set the field to an id the workspace no longer had and Blockly threw "Variable id doesn't point to a real variable". The index is now also keyed on the workspace's variables.
---
src/components/spotlight/spotlight.jsx | 9 +++++-
src/lib/spotlight/BlockTypeInfo.js | 11 +++++++
test/unit/lib/spotlight-variables-key.test.js | 29 +++++++++++++++++++
3 files changed, 48 insertions(+), 1 deletion(-)
create mode 100644 test/unit/lib/spotlight-variables-key.test.js
diff --git a/src/components/spotlight/spotlight.jsx b/src/components/spotlight/spotlight.jsx
index 60150a46e6f..5255660d66a 100644
--- a/src/components/spotlight/spotlight.jsx
+++ b/src/components/spotlight/spotlight.jsx
@@ -258,6 +258,7 @@ export default function NativeSpotlight ({vm, locale, activeTabIndex, isPlayerOn
let selectedPreviewIdx = 0;
let blockTypes = null;
let indexedTargetId = null;
+ let indexedVariablesKey = null;
let limited = false;
let allowMenuClose = true;
@@ -337,7 +338,11 @@ export default function NativeSpotlight ({vm, locale, activeTabIndex, isPlayerOn
popupRoot.style.display = '';
popupInput.focus();
- if (blockTypes && indexedTargetId === (vm.editingTarget && vm.editingTarget.id)) {
+ if (
+ blockTypes &&
+ indexedTargetId === (vm.editingTarget && vm.editingTarget.id) &&
+ indexedVariablesKey === BlockTypeInfo.getVariablesKey(workspace)
+ ) {
doPerformSearch();
return;
}
@@ -361,6 +366,7 @@ export default function NativeSpotlight ({vm, locale, activeTabIndex, isPlayerOn
try {
blockTypes = BlockTypeInfo.getBlocks(Blockly, vm, workspace, msg);
indexedTargetId = vm.editingTarget && vm.editingTarget.id;
+ indexedVariablesKey = BlockTypeInfo.getVariablesKey(workspace);
if (!blockTypes || blockTypes.length === 0) {
console.warn('Spotlight: No block types available, showing empty search');
@@ -836,6 +842,7 @@ export default function NativeSpotlight ({vm, locale, activeTabIndex, isPlayerOn
const invalidateIndex = () => {
blockTypes = null;
indexedTargetId = null;
+ indexedVariablesKey = null;
querier.clearWorkspaceIndex();
};
vm.on('EXTENSION_ADDED', invalidateIndex);
diff --git a/src/lib/spotlight/BlockTypeInfo.js b/src/lib/spotlight/BlockTypeInfo.js
index f6ff194151b..5ec31ad2a54 100644
--- a/src/lib/spotlight/BlockTypeInfo.js
+++ b/src/lib/spotlight/BlockTypeInfo.js
@@ -368,6 +368,17 @@ export class BlockTypeInfo {
};
}
+ /**
+ * Identifies the variables, lists and broadcasts the enumerated dropdowns were built from.
+ * @param {*} workspace The workspace to describe
+ * @returns {string} A key that changes whenever one is created, deleted or renamed
+ */
+ static getVariablesKey (workspace) {
+ return workspace.getAllVariables()
+ .map(variable => `${variable.type}\u0000${variable.getId()}\u0000${variable.name}`)
+ .join('\u0000');
+ }
+
/**
* Enumerates all the different types of blocks, given a workspace.
* @param {Blockly} Blockly The Blockly instance
diff --git a/test/unit/lib/spotlight-variables-key.test.js b/test/unit/lib/spotlight-variables-key.test.js
new file mode 100644
index 00000000000..facc110ca7d
--- /dev/null
+++ b/test/unit/lib/spotlight-variables-key.test.js
@@ -0,0 +1,29 @@
+import {BlockTypeInfo} from '../../../src/lib/spotlight/BlockTypeInfo.js';
+
+const variable = (id, name, type = '') => ({id, name, type, getId: () => id});
+
+const workspaceWith = variables => ({getAllVariables: () => variables});
+
+describe('spotlight variables key', () => {
+ const score = variable('a', 'score');
+ const items = variable('b', 'items', 'list');
+ const message = variable('c', 'message1', 'broadcast_msg');
+ const key = BlockTypeInfo.getVariablesKey(workspaceWith([score, items, message]));
+
+ test('stays the same while the variables are unchanged', () => {
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([score, items, message]))).toBe(key);
+ });
+
+ test('changes when a variable, list or broadcast is deleted', () => {
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([items, message]))).not.toBe(key);
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([score, message]))).not.toBe(key);
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([score, items]))).not.toBe(key);
+ });
+
+ test('changes when a variable is created or renamed', () => {
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([score, items, message, variable('d', 'lives')])))
+ .not.toBe(key);
+ expect(BlockTypeInfo.getVariablesKey(workspaceWith([variable('a', 'points'), items, message])))
+ .not.toBe(key);
+ });
+});
From 661eddd44b04b4cb97f37283d60efd5cec240592 Mon Sep 17 00:00:00 2001
From: Mistium <92952823+Mistium@users.noreply.github.com>
Date: Tue, 6 Oct 2026 19:31:28 +0100
Subject: [PATCH 3/9] Find the backpack for folders before the sprite list has
rendered
The folders addon took React's internal key from the first sprite in the
sprite list. A stage-only project or the narrow layout has no sprite list
yet, so opening the backpack threw "cannot find Backpack". Read the key
from the backpack element, keep listening until the backpack exists, and
skip patching a backpack that is already patched.
---
src/addons/addons/folders/userscript.js | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/src/addons/addons/folders/userscript.js b/src/addons/addons/folders/userscript.js
index 196c2af3092..1564347d6a6 100644
--- a/src/addons/addons/folders/userscript.js
+++ b/src/addons/addons/folders/userscript.js
@@ -110,7 +110,7 @@ export default async function ({ addon, console, msg }) {
};
const getBackpackFromElement = (el) => {
- let fiber = el[reactInternalKey];
+ let fiber = el[addon.tab.traps.getInternalKey(el)];
while (fiber) {
const instance = fiber.stateNode;
if (instance && typeof instance.handleDrop === "function" && typeof instance.getContents === "function") {
@@ -118,7 +118,7 @@ export default async function ({ addon, console, msg }) {
}
fiber = fiber.return;
}
- throw new Error("cannot find Backpack");
+ return null;
};
const clamp = (n, min, max) => {
@@ -1305,8 +1305,14 @@ export default async function ({ addon, console, msg }) {
if (!backpackContainer) {
return;
}
- document.removeEventListener("click", clickListener, true);
const backpackInstance = getBackpackFromElement(backpackContainer);
+ if (!backpackInstance) {
+ return;
+ }
+ document.removeEventListener("click", clickListener, true);
+ if (typeof backpackInstance.constructor.prototype.sa_loadNextItem === "function") {
+ return;
+ }
verifyBackpack(backpackInstance);
patchBackpack(backpackInstance);
});
From c6d34f8795220af4fbfc23833bd02360d200262d Mon Sep 17 00:00:00 2001
From: Mistium <92952823+Mistium@users.noreply.github.com>
Date: Tue, 6 Oct 2026 19:31:28 +0100
Subject: [PATCH 4/9] Do not read a sound buffer for a sound that is no longer
there
The sound editor's mapStateToProps can run with a stale index after the
last sound is deleted or the editing target changes, and getSoundBuffer
then read soundId from undefined.
---
src/containers/sound-editor.jsx | 2 +-
test/unit/containers/sound-editor.test.jsx | 13 +++++++++++++
2 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/src/containers/sound-editor.jsx b/src/containers/sound-editor.jsx
index bb2726baf51..d7d3f4201be 100644
--- a/src/containers/sound-editor.jsx
+++ b/src/containers/sound-editor.jsx
@@ -547,7 +547,7 @@ const mapStateToProps = (state, {soundIndex}) => {
// A sound whose asset failed to load never gets a soundId, so the audio
// engine has no player for it and getSoundBuffer returns null. Render the
// editor with empty data instead of crashing.
- const audioBuffer = state.scratchGui.vm.getSoundBuffer(index);
+ const audioBuffer = sound ? state.scratchGui.vm.getSoundBuffer(index) : null;
return {
isStereo: audioBuffer ? audioBuffer.numberOfChannels !== 1 : false,
duration: sound && sound.rate ? sound.sampleCount / sound.rate : 0,
diff --git a/test/unit/containers/sound-editor.test.jsx b/test/unit/containers/sound-editor.test.jsx
index f7fa2814ada..24c12c7d43a 100644
--- a/test/unit/containers/sound-editor.test.jsx
+++ b/test/unit/containers/sound-editor.test.jsx
@@ -311,6 +311,19 @@ describe('Sound Editor Container', () => {
expect(editor.submitNewSamples).not.toHaveBeenCalled();
});
+ test('renders without a buffer when the sprite has no sound at its index', () => {
+ vm.editingTarget.sprite.sounds = [];
+ vm.getSoundBuffer = jest.fn(index => vm.editingTarget.sprite.sounds[index].soundId);
+ const wrapper = mountWithIntl(
+