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( + + ); + expect(vm.getSoundBuffer).not.toHaveBeenCalled(); + expect(wrapper.find(SoundEditorComponent).props().name).toEqual(''); + }); + test('isStereo numberOfChannels=1', () => { soundBuffer.numberOfChannels = 1; const wrapper = mountWithIntl( From 1bab4a5eb5784e47c43c9dec6491626c098f9e4e 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 5/9] Do not report a stale page chunk while the page reloads lazyWithReload rethrew the chunk error after starting the reload, so the error boundary reported every recovered stale deploy. Wait for the reload instead, and allow another reload a minute later rather than once per tab, so a tab that reloaded into the same build during a deploy can still recover. --- src/lib/lazy-with-retry.js | 10 ++++-- test/unit/util/retryable-lazy.test.jsx | 33 ++++++++++++++++++- .../util/runtime-error-regressions.test.js | 18 +++++++--- 3 files changed, 52 insertions(+), 9 deletions(-) diff --git a/src/lib/lazy-with-retry.js b/src/lib/lazy-with-retry.js index 3c77d5234f1..57dc2520f30 100644 --- a/src/lib/lazy-with-retry.js +++ b/src/lib/lazy-with-retry.js @@ -41,12 +41,16 @@ export const retryableLazy = load => { // Community page navigation can recover from assets removed by a deployment. // Do not use this for editor imports, where a reload could discard project edits. +const RELOAD_COOLDOWN = 60 * 1000; + export const reloadStalePage = (error, browser = window) => { if (!isChunkLoadError(error)) return false; try { const key = `mw:chunk-reload:${BUILD_ID}`; - if (browser.sessionStorage.getItem(key)) return false; - browser.sessionStorage.setItem(key, '1'); + const now = Date.now(); + const last = Number(browser.sessionStorage.getItem(key)); + if (last && now - last < RELOAD_COOLDOWN) return false; + browser.sessionStorage.setItem(key, String(now)); browser.location.reload(); return true; } catch (e) { @@ -56,6 +60,6 @@ export const reloadStalePage = (error, browser = window) => { }; export const lazyWithReload = load => lazy(() => importWithRetry(load).catch(error => { - reloadStalePage(error); + if (reloadStalePage(error)) return new Promise(() => {}); throw error; })); diff --git a/test/unit/util/retryable-lazy.test.jsx b/test/unit/util/retryable-lazy.test.jsx index 45a8efd15e1..8abf79b24e3 100644 --- a/test/unit/util/retryable-lazy.test.jsx +++ b/test/unit/util/retryable-lazy.test.jsx @@ -1,7 +1,7 @@ import React from 'react'; import ReactDOM from 'react-dom'; import {act} from 'react-dom/test-utils'; -import {retryableLazy} from '../../../src/lib/lazy-with-retry'; +import {lazyWithReload, retryableLazy} from '../../../src/lib/lazy-with-retry'; class Boundary extends React.Component { static getDerivedStateFromError (error) { @@ -70,3 +70,34 @@ test('preload starts the import without rendering', async () => { await LazyPanel.preload(); expect(load).toHaveBeenCalledTimes(1); }); + +test('a stale page that reloads does not reach the error boundary', async () => { + window.sessionStorage.clear(); + const load = jest.fn().mockRejectedValue(new TypeError('Failed to fetch dynamically imported module: /assets/Old.js')); + const LazyPage = lazyWithReload(load); + const container = document.createElement('div'); + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); + try { + act(() => { + ReactDOM.render( + + {'loading'}

}> + +
+
, + container + ); + }); + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 1100)); + }); + await flush(); + expect(load).toHaveBeenCalledTimes(2); + expect(window.sessionStorage.length).toBe(1); + expect(container.textContent).toBe('loading'); + } finally { + consoleError.mockRestore(); + ReactDOM.unmountComponentAtNode(container); + window.sessionStorage.clear(); + } +}); diff --git a/test/unit/util/runtime-error-regressions.test.js b/test/unit/util/runtime-error-regressions.test.js index 9c29743a07e..bef2f1c8a40 100644 --- a/test/unit/util/runtime-error-regressions.test.js +++ b/test/unit/util/runtime-error-regressions.test.js @@ -87,17 +87,25 @@ test.each([ expect(isChunkLoadError(new TypeError(message))).toBe(true); }); -test('stale community pages reload once per build without a reload loop', () => { +test('stale community pages reload without a reload loop', () => { const entries = new Map(); const browser = { sessionStorage: {getItem: key => entries.get(key), setItem: (key, value) => entries.set(key, value)}, location: {reload: jest.fn()} }; const error = new Error('Failed to fetch dynamically imported module: /assets/old.js'); - expect(reloadStalePage(error, browser)).toBe(true); - expect(reloadStalePage(error, browser)).toBe(false); - expect(browser.location.reload).toHaveBeenCalledTimes(1); - expect(reloadStalePage(new Error('Module execution failed'), browser)).toBe(false); + const now = jest.spyOn(Date, 'now').mockReturnValue(1000000); + try { + expect(reloadStalePage(error, browser)).toBe(true); + expect(reloadStalePage(error, browser)).toBe(false); + expect(browser.location.reload).toHaveBeenCalledTimes(1); + now.mockReturnValue(1000000 + (61 * 1000)); + expect(reloadStalePage(error, browser)).toBe(true); + expect(browser.location.reload).toHaveBeenCalledTimes(2); + expect(reloadStalePage(new Error('Module execution failed'), browser)).toBe(false); + } finally { + now.mockRestore(); + } }); test('blocked session storage leaves chunk recovery to the manual reload button', () => { From 78339a0ff2d2aaa1d00b56cd83c5bc0b0b8bdc4a 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 6/9] Close collaboration channels no MistWarp client opens MistWarp clients dial with raw serialization, and older ones with PeerJS binary. A channel opened with JSON serialization made PeerJS 1.3 call JSON.parse on binary data and throw from the data channel handler. --- src/lib/collaboration/links.js | 2 ++ src/lib/collaboration/transport.js | 5 +++-- test/unit/collaboration/transport.test.js | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/lib/collaboration/links.js b/src/lib/collaboration/links.js index fe161d3bd13..46aace52fb5 100644 --- a/src/lib/collaboration/links.js +++ b/src/lib/collaboration/links.js @@ -2,6 +2,7 @@ import Emitter from './emitter.js'; import {encodeFrames, FrameDecoder, bytesToBase64, base64ToBytes} from './wire.js'; const RAW_SERIALIZATION = 'raw'; +const LEGACY_SERIALIZATION = 'binary'; const RELAY_MARK = 'mw-relay-1'; // Used when the browser does not report the SCTP message limit. const DEFAULT_FRAME_LIMIT = 16 * 1024; @@ -227,6 +228,7 @@ class RelayLink extends Link { } export { + LEGACY_SERIALIZATION, RAW_SERIALIZATION, RELAY_MARK, DEFAULT_FRAME_LIMIT, diff --git a/src/lib/collaboration/transport.js b/src/lib/collaboration/transport.js index cfb045244d9..8cbaf4a977e 100644 --- a/src/lib/collaboration/transport.js +++ b/src/lib/collaboration/transport.js @@ -2,7 +2,7 @@ import PeerModule from 'peerjs'; import {resolvePeerConstructor} from './peer-constructor.js'; import Emitter from './emitter.js'; import {validateEnvelope, makeCtrl, KIND, CTRL, PROTOCOL_VERSION} from './protocol.js'; -import {DirectLink, RelayLink, RAW_SERIALIZATION, RELAY_MARK} from './links.js'; +import {DirectLink, RelayLink, LEGACY_SERIALIZATION, RAW_SERIALIZATION, RELAY_MARK} from './links.js'; import {APP_NAME} from '../constants/brand.js'; const DEFAULT_PEER_CONFIG = { @@ -827,7 +827,8 @@ class Transport extends Emitter { } _wireConnection (conn) { - if (this.destroyed) { + if (this.destroyed || + (conn.serialization !== RAW_SERIALIZATION && conn.serialization !== LEGACY_SERIALIZATION)) { conn.close(); return; } diff --git a/test/unit/collaboration/transport.test.js b/test/unit/collaboration/transport.test.js index 77332670970..e8866b4649f 100644 --- a/test/unit/collaboration/transport.test.js +++ b/test/unit/collaboration/transport.test.js @@ -809,6 +809,20 @@ describe('older clients', () => { expect(conn.frames).toEqual([]); transport.destroy(); }); + + test('a channel no MistWarp client opens is closed before it can deliver data', async () => { + const {transport, peers} = makeTransport(); + const hosted = transport.host('room1'); + peers[0].simulateOpen(); + await hosted; + const connected = jest.fn(); + transport.on('peer-connected', connected); + const conn = peers[0].simulateIncomingConnection('stranger', {serialization: 'json'}); + expect(conn.closed).toBe(true); + conn.simulateOpen(); + expect(connected).not.toHaveBeenCalled(); + transport.destroy(); + }); }); describe('connection lifecycle regressions', () => { From 7a1a3b1a803a06ba06b2ba0270e7ad27d703de72 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 7/9] Treat closing the Rotur window as declining chat signing Turn on signing called ensureScopes without handling a closed sign-in popup, so closing it became an unhandled rejection. --- src/lib/originchats/signing.js | 7 ++++++- src/lib/rotur/oauth.js | 3 +++ test/unit/originchats-signing.test.js | 13 +++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/lib/originchats/signing.js b/src/lib/originchats/signing.js index 8f9137017dc..72a1639cbd4 100644 --- a/src/lib/originchats/signing.js +++ b/src/lib/originchats/signing.js @@ -1,4 +1,5 @@ import {ensureScopes, getRotur} from '../rotur/client.js'; +import {isCancelled} from '../rotur/oauth.js'; import {signContent} from './device-key.js'; const SIGNING_SCOPE = 'signing:keys'; @@ -28,7 +29,11 @@ const signingStatus = async capabilities => { }; const requestSigningPermission = async () => { - await ensureScopes([SIGNING_SCOPE], {prompt: true}); + try { + await ensureScopes([SIGNING_SCOPE], {prompt: true}); + } catch (error) { + if (!isCancelled(error)) throw error; + } return scopeGranted(); }; diff --git a/src/lib/rotur/oauth.js b/src/lib/rotur/oauth.js index cbf20e47e4e..21f9d306355 100644 --- a/src/lib/rotur/oauth.js +++ b/src/lib/rotur/oauth.js @@ -39,6 +39,8 @@ const configure = options => Object.assign(config, options); const oauthError = (code, message, extra) => Object.assign(new Error(message), {code}, extra); +const isCancelled = error => Boolean(error) && (error.code === 'closed' || error.code === 'access_denied'); + const base64url = bytes => btoa(String.fromCharCode(...bytes)) .replace(/\+/g, '-') .replace(/\//g, '_') @@ -374,6 +376,7 @@ export { completeRedirect, configure, getAccessToken, + isCancelled, onSessionChange, readSession, signIn, diff --git a/test/unit/originchats-signing.test.js b/test/unit/originchats-signing.test.js index 918f6509771..126e0b05893 100644 --- a/test/unit/originchats-signing.test.js +++ b/test/unit/originchats-signing.test.js @@ -144,3 +144,16 @@ test('checks signing:keys without prompting and requests it only on a click', as await expect(signingStatus(['message_signatures_v1'])).resolves.toBe('needs_permission'); await expect(signingStatus([])).resolves.toBe('off'); }); + +test('closing the Rotur sign-in window leaves signing off without an error', async () => { + const {requestSigningPermission} = loadSigning(); + mockClient.allowed = false; + mockEnsureScopes.mockImplementationOnce(() => Promise.reject( + Object.assign(new Error('The Rotur sign-in window was closed'), {code: 'closed'}) + )); + await expect(requestSigningPermission()).resolves.toBe(false); + mockEnsureScopes.mockImplementationOnce(() => Promise.reject( + Object.assign(new Error('Rotur sign-in failed (500)'), {code: 'token_failed'}) + )); + await expect(requestSigningPermission()).rejects.toThrow('Rotur sign-in failed (500)'); +}); From fa135462a5cc924fe85b51b657c778e3f604bf87 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 8/9] Skip error reports raised outside MistWarp code Drop aborted operations, pointer lock refusals, wallet extension scripts, Safari media control internals, rejections with no reason, and React losing track of nodes on a machine translated page. --- src/lib/error-reporter.js | 19 +++++++++++++++++ test/unit/util/error-reporter.test.js | 30 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/lib/error-reporter.js b/src/lib/error-reporter.js index 1baf310fb9e..ca0a95219dc 100644 --- a/src/lib/error-reporter.js +++ b/src/lib/error-reporter.js @@ -101,6 +101,24 @@ const isProjectScriptError = (name, stack) => ( // NetworkError is a transport failure with no stack, so nothing in it can be acted on. const BROWSER_REFUSAL = /^(NotAllowedError|NetworkError)$/; +const BROWSER_NOISE = /window\.ethereum|^Can't find variable: EmptyRanges$|lock the pointer|pointer lock/i; +const DETACHED_NODE = /(?:removeChild|insertBefore).*not a child of this node/; + +const isMachineTranslated = () => { + try { + return /\btranslated-(?:ltr|rtl)\b/.test(document.documentElement.className); + } catch (e) { + return false; + } +}; + +const isOutsideMistWarp = (message, name, stack, kind) => ( + BROWSER_NOISE.test(message) || + name === 'AbortError' || + (kind === 'rejection' && message === 'Unhandled promise rejection' && !stack) || + (DETACHED_NODE.test(message) && isMachineTranslated()) +); + export const reportSiteError = ({message, stack = '', kind = 'uncaught', url = '', projectId = '', componentStack = '', name = ''}) => { try { const text = String(message || '').trim(); @@ -108,6 +126,7 @@ export const reportSiteError = ({message, stack = '', kind = 'uncaught', url = ' if (isBenignResizeObserverLoop(text, stack)) return; if (isUnactionable(text, stack) || isCrawler() || isRehostedCopy()) return; if (isProjectScriptError(name, stack) || BROWSER_REFUSAL.test(String(name || ''))) return; + if (isOutsideMistWarp(text, name, stack, kind)) return; const href = String(url || window.location.href || '').slice(0, 2000); if (href.includes('/errors')) return; const signature = `${text.slice(0, 200)}|${href.slice(0, 200)}|${String(stack).slice(0, 200)}`; diff --git a/test/unit/util/error-reporter.test.js b/test/unit/util/error-reporter.test.js index 8edee299bc0..e0f5c524420 100644 --- a/test/unit/util/error-reporter.test.js +++ b/test/unit/util/error-reporter.test.js @@ -108,3 +108,33 @@ test.each([ reportSiteError({message, name, stack: `${name}: ${message}`, kind: 'rejection'}); expect(request).not.toHaveBeenCalled(); }); + +test.each([ + ['AbortError', 'The operation was aborted.', 'rejection', ''], + ['NotSupportedError', 'The browser failed to lock the pointer.', 'rejection', ''], + ['TypeError', 'undefined is not an object (evaluating \'window.ethereum.selectedAddress = undefined\')', 'uncaught', + 'global code@https://mistwarp.org/editor:1:16'], + ['ReferenceError', 'Can\'t find variable: EmptyRanges', 'uncaught', 'played@\nsyncControl@\nhandleEvent@'], + [undefined, 'Unhandled promise rejection', 'rejection', ''] +])('skips errors raised outside MistWarp: %s %s', (name, message, kind, stack) => { + const {reportSiteError, request} = load(); + reportSiteError({message, name, kind, stack}); + expect(request).not.toHaveBeenCalled(); +}); + +test('skips React losing track of nodes only on a machine translated page', () => { + const message = 'Failed to execute \'removeChild\' on \'Node\': The node to be removed is not a child of this node.'; + const stack = `NotFoundError: ${message}\n at mf (https://mistwarp.org/assets/app-target.js:42:79383)`; + let loaded = load(); + loaded.reportSiteError({message, name: 'NotFoundError', stack, kind: 'rejection'}); + expect(loaded.request).toHaveBeenCalledTimes(1); + document.documentElement.classList.add('translated-ltr'); + try { + jest.clearAllMocks(); + loaded = load(); + loaded.reportSiteError({message, name: 'NotFoundError', stack, kind: 'rejection'}); + expect(loaded.request).not.toHaveBeenCalled(); + } finally { + document.documentElement.classList.remove('translated-ltr'); + } +}); From 12b65550ba5db51251061c04b477944830817dda Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:38:53 +0100 Subject: [PATCH 9/9] Keep the editor running when a project extension fails to load --- src/lib/components/tw-state-manager-hoc.jsx | 9 ++++++- src/lib/components/vm-listener-hoc.jsx | 7 ++++- src/lib/error-reporter.js | 18 +++++++++++-- src/lib/utils/tw-polyfill.js | 8 ++++++ src/playground/embed-storage-shim.js | 1 + test/unit/util/error-reporter.test.js | 29 +++++++++++++++++++++ test/unit/util/tw-polyfill.test.js | 15 +++++++++++ test/unit/util/vm-listener-hoc.test.jsx | 16 ++++++++++++ 8 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 test/unit/util/tw-polyfill.test.js diff --git a/src/lib/components/tw-state-manager-hoc.jsx b/src/lib/components/tw-state-manager-hoc.jsx index 2997917ad17..882b77d2195 100644 --- a/src/lib/components/tw-state-manager-hoc.jsx +++ b/src/lib/components/tw-state-manager-hoc.jsx @@ -32,6 +32,7 @@ import CollaborationService from '../collaboration/index.js'; import {setSearchParams} from '../utils/navigation'; import {defaultStageSize} from '../../reducers/custom-stage-size'; import {openSimpleDialog} from '../../reducers/modals'; +import {showStandardAlert} from '../../reducers/alerts'; const USERNAME_KEY = 'tw:username'; @@ -403,7 +404,10 @@ const TWStateManager = function (WrappedComponent) { } for (const extension of urlParams.getAll('extension')) { - this.props.vm.extensionManager.loadExtensionURL(extension); + Promise.resolve(this.props.vm.extensionManager.loadExtensionURL(extension)).catch(error => { + log.error(`Could not load extension from URL parameter: ${extension}`, error); + this.props.onExtensionLoadError(); + }); } // Handle room codes for automatic collaboration @@ -699,6 +703,7 @@ const TWStateManager = function (WrappedComponent) { onSetCollaborationRoomId, onSetCollaborationInvite, onOpenCollaborationModal, + onExtensionLoadError, reduxProjectId, routingStyle, username, @@ -748,6 +753,7 @@ const TWStateManager = function (WrappedComponent) { onSetCollaborationRoomId: PropTypes.func, onSetCollaborationInvite: PropTypes.func, onOpenCollaborationModal: PropTypes.func, + onExtensionLoadError: PropTypes.func, openSimpleDialog: PropTypes.func.isRequired, confirmWithMessage: PropTypes.func, reduxProjectId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), @@ -785,6 +791,7 @@ const TWStateManager = function (WrappedComponent) { onSetCollaborationRoomId: roomId => dispatch(setCollaborationRoomId(roomId)), onSetCollaborationInvite: invite => dispatch(setCollaborationInvite(invite)), onOpenCollaborationModal: () => dispatch(openCollaborationModal()), + onExtensionLoadError: () => dispatch(showStandardAlert('extensionLoadError')), openSimpleDialog: config => dispatch(openSimpleDialog(config)) }); return connect( diff --git a/src/lib/components/vm-listener-hoc.jsx b/src/lib/components/vm-listener-hoc.jsx index dac9a5aa139..4d99f800253 100644 --- a/src/lib/components/vm-listener-hoc.jsx +++ b/src/lib/components/vm-listener-hoc.jsx @@ -10,7 +10,7 @@ import {updateBlockDrag} from '../../reducers/block-drag'; import {updateMonitors} from '../../reducers/monitors'; import {setProjectChanged, setProjectUnchanged} from '../../reducers/project-changed'; import {setRunningState, setTurboState, setStartedState} from '../../reducers/vm-status'; -import {showExtensionAlert} from '../../reducers/alerts'; +import {showExtensionAlert, showStandardAlert} from '../../reducers/alerts'; import {updateMicIndicator} from '../../reducers/mic-indicator'; import { setFramerateState, @@ -118,6 +118,7 @@ const vmListenerHOC = function (WrappedComponent) { this.props.vm.on('RUNTIME_STOPPED', this.props.onRuntimeStopped); this.props.vm.on('PROJECT_START', this.props.onGreenFlag); this.props.vm.on('PERIPHERAL_CONNECTION_LOST_ERROR', this.props.onShowExtensionAlert); + this.props.vm.on('EXTENSION_LOAD_ERROR', this.props.onExtensionLoadError); this.props.vm.on('MIC_LISTENING', this.props.onMicListeningUpdate); this.props.vm.on('MIC_LISTENING', this.props.onMicListeningUpdate); // tw: add handlers for our events @@ -169,6 +170,7 @@ const vmListenerHOC = function (WrappedComponent) { this.props.vm.off('RUNTIME_STOPPED', this.props.onRuntimeStopped); this.props.vm.off('PROJECT_START', this.props.onGreenFlag); this.props.vm.off('PERIPHERAL_CONNECTION_LOST_ERROR', this.props.onShowExtensionAlert); + this.props.vm.off('EXTENSION_LOAD_ERROR', this.props.onExtensionLoadError); this.props.vm.off('MIC_LISTENING', this.props.onMicListeningUpdate); this.props.vm.off('MIC_LISTENING', this.props.onMicListeningUpdate); this.props.vm.off('HAS_CLOUD_DATA_UPDATE', this.handleCloudDataUpdate); @@ -330,6 +332,7 @@ const vmListenerHOC = function (WrappedComponent) { onCompileError, onClearCompileErrors, onShowExtensionAlert, + onExtensionLoadError, /* eslint-enable no-unused-vars */ ...props } = this.props; @@ -353,6 +356,7 @@ const vmListenerHOC = function (WrappedComponent) { onRuntimeStarted: PropTypes.func.isRequired, onRuntimeStopped: PropTypes.func.isRequired, onShowExtensionAlert: PropTypes.func.isRequired, + onExtensionLoadError: PropTypes.func.isRequired, onTargetsUpdate: PropTypes.func.isRequired, onTurboModeOff: PropTypes.func.isRequired, onTurboModeOn: PropTypes.func.isRequired, @@ -447,6 +451,7 @@ const vmListenerHOC = function (WrappedComponent) { onShowExtensionAlert: data => { dispatch(showExtensionAlert(data)); }, + onExtensionLoadError: () => dispatch(showStandardAlert('extensionLoadError')), onMicListeningUpdate: listening => { dispatch(updateMicIndicator(listening)); } diff --git a/src/lib/error-reporter.js b/src/lib/error-reporter.js index ca0a95219dc..c128e8cc337 100644 --- a/src/lib/error-reporter.js +++ b/src/lib/error-reporter.js @@ -59,9 +59,23 @@ const isCrawler = () => { const BROWSER_EXTENSION_FRAME = /(?:chrome|moz|safari|safari-web)-extension:\/\//; +const ERROR_PREFIX = /^(?:Uncaught\s+)?(?:[A-Za-z]*Error:\s*)?/; + +const withoutErrorPrefixes = message => { + let text = message; + let previous; + do { + previous = text; + text = text.replace(ERROR_PREFIX, ''); + } while (text !== previous); + return text; +}; + +const SANDBOXED_EXTENSION_ERROR = /^(?:[A-Za-z]*Error:\s*)+Uncaught\s/; + const isUnactionable = (message, stack) => { - if (message === 'Script error.') return true; - if (/^(?:(?:ReferenceError:\s*)?unsandboxed is not defined|Can't find variable: unsandboxed)$/i.test(message)) return true; + if (withoutErrorPrefixes(message) === 'Script error.') return true; + if (/unsandboxed/i.test(message) || SANDBOXED_EXTENSION_ERROR.test(message)) return true; const frames = String(stack || '') .split('\n') .filter(line => /:\d+:\d+\)?\s*$/.test(line)); diff --git a/src/lib/utils/tw-polyfill.js b/src/lib/utils/tw-polyfill.js index e82a6dcd701..f244dd5a57b 100644 --- a/src/lib/utils/tw-polyfill.js +++ b/src/lib/utils/tw-polyfill.js @@ -52,3 +52,11 @@ if (!Object.fromEntries) { return object; }; } + +if (typeof Object.hasOwn !== 'function') { + Object.defineProperty(Object, 'hasOwn', { + value: (object, property) => Object.prototype.hasOwnProperty.call(object, property), + configurable: true, + writable: true + }); +} diff --git a/src/playground/embed-storage-shim.js b/src/playground/embed-storage-shim.js index b175e636b08..6ad8021bab9 100644 --- a/src/playground/embed-storage-shim.js +++ b/src/playground/embed-storage-shim.js @@ -1,3 +1,4 @@ +import '../lib/utils/tw-polyfill'; import * as fakeIndexedDB from 'fake-indexeddb'; const originOf = url => { diff --git a/test/unit/util/error-reporter.test.js b/test/unit/util/error-reporter.test.js index e0f5c524420..dd56c47fa72 100644 --- a/test/unit/util/error-reporter.test.js +++ b/test/unit/util/error-reporter.test.js @@ -43,6 +43,35 @@ test.each(['unsandboxed is not defined', 'ReferenceError: unsandboxed is not def } ); +test.each(['Error: Script error.', 'Uncaught Error: Script error.', 'Error: Error: Script error.'])( + 'skips wrapped cross-origin script errors: %s', message => { + const {reportSiteError, request} = load(); + reportSiteError({message, stack: message, kind: 'react'}); + expect(request).not.toHaveBeenCalled(); + } +); + +test.each([ + 'Error: Uncaught Error: This extension must run unsandboxed.', + 'Error: Error: Popup Phoenix must run unsandboxed!', + 'Error: Uncaught Error: AKL requires an unsandboxed extension environment.', + 'Error: Uncaught Error: La extensión s32 necesita ejecutarse sin sandbox (unsandboxed) para poder recibir mensajes.', + 'Error: Uncaught TypeError: Cannot read properties of undefined (reading \'runtime\')' +])('skips errors relayed from sandboxed extensions: %s', message => { + const {reportSiteError, request} = load(); + reportSiteError({message, stack: message, kind: 'rejection'}); + expect(request).not.toHaveBeenCalled(); +}); + +test.each([ + 'Script error in the project player', + 'Error: Could not load the project script.' +])('still reports MistWarp errors that mention scripts: %s', message => { + const {reportSiteError, request} = load(); + reportSiteError({message, stack: `Error: ${message}\n at run (https://mistwarp.org/assets/api.js:1:10)`}); + expect(request).toHaveBeenCalledTimes(1); +}); + test('skips errors thrown by browser extensions', () => { const {reportSiteError, request} = load(); reportSiteError({ diff --git a/test/unit/util/tw-polyfill.test.js b/test/unit/util/tw-polyfill.test.js new file mode 100644 index 00000000000..49d7bfca01b --- /dev/null +++ b/test/unit/util/tw-polyfill.test.js @@ -0,0 +1,15 @@ +test('provides Object.hasOwn for browsers without it', () => { + const original = Object.hasOwn; + delete Object.hasOwn; + try { + jest.isolateModules(() => { + require('../../../src/lib/utils/tw-polyfill'); + }); + expect(Object.hasOwn({request: null}, 'request')).toBe(true); + expect(Object.hasOwn(Object.create({request: 1}), 'request')).toBe(false); + expect(Object.hasOwn('text', 'length')).toBe(true); + expect(() => Object.hasOwn(null, 'request')).toThrow(TypeError); + } finally { + Object.defineProperty(Object, 'hasOwn', {value: original, configurable: true, writable: true}); + } +}); diff --git a/test/unit/util/vm-listener-hoc.test.jsx b/test/unit/util/vm-listener-hoc.test.jsx index 11f6f30a147..3b598e639b6 100644 --- a/test/unit/util/vm-listener-hoc.test.jsx +++ b/test/unit/util/vm-listener-hoc.test.jsx @@ -53,6 +53,22 @@ describe('VMListenerHOC', () => { expect(child.props().onGreenFlag).toBeUndefined(); }); + test('an extension that fails to load shows the extension load alert', () => { + const Component = () => (
); + const WrappedComponent = vmListenerHOC(Component); + mount( + + ); + vm.emit('EXTENSION_LOAD_ERROR', {extensionID: 'fetch', url: 'https://example.com/fetch.js', error: 'failed'}); + expect(store.getActions()).toContainEqual(expect.objectContaining({ + type: 'scratch-gui/alerts/SHOW_ALERT', + alertId: 'extensionLoadError' + })); + }); + test('targetsUpdate event from vm triggers targets update action', () => { const Component = () => (
); const WrappedComponent = vmListenerHOC(Component);