From 428a14a63faa79e18869d1fcc6ce7c35ccebc11c Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:24:10 +0000 Subject: [PATCH 1/5] Add runtime.addStepListener for code that runs around each step The debugger and the packager pointer lock wrap runtime._step to run code after every frame. addStepListener takes before and after functions and returns a function that removes them. With no listeners _step only checks two null fields. --- src/engine/runtime.js | 35 +++++++++ test/unit/engine_runtime_step_listeners.js | 86 ++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 test/unit/engine_runtime_step_listeners.js diff --git a/src/engine/runtime.js b/src/engine/runtime.js index 2c3760db77..01b415e921 100644 --- a/src/engine/runtime.js +++ b/src/engine/runtime.js @@ -58,6 +58,21 @@ const defaultBlockPackages = { scratch3_assets: require('../blocks/scratch3_assets') }; +const withListener = (listeners, listener) => (listeners === null ? [listener] : listeners.concat(listener)); + +const withoutListener = (listeners, listener) => { + const index = listeners === null ? -1 : listeners.indexOf(listener); + if (index === -1) return listeners; + if (listeners.length === 1) return null; + return listeners.slice(0, index).concat(listeners.slice(index + 1)); +}; + +const callListeners = listeners => { + for (let i = 0; i < listeners.length; i++) { + listeners[i](); + } +}; + const interpolate = require('./tw-interpolate'); const FrameLoop = require('./tw-frame-loop'); const MonitorRecord = require('./monitor-record.js'); @@ -172,6 +187,9 @@ class Runtime extends EventEmitter { this._threadsKilled = false; + this._beforeStepListeners = null; + this._afterStepListeners = null; + /** * Live monitor threads by the block that started them. Saves a scan of every * thread for every monitored block, on every frame. @@ -1912,6 +1930,7 @@ class Runtime extends EventEmitter { */ _step () { if (this.sampler.enableBasic) this.sampler.pc[0] = Sampler.RUNTIME; + if (this._beforeStepListeners !== null) callListeners(this._beforeStepListeners); if (this.interpolationEnabled) { interpolate.setupInitialState(this); @@ -1998,9 +2017,25 @@ class Runtime extends EventEmitter { this.profiler.reportFrames(); } + if (this._afterStepListeners !== null) callListeners(this._afterStepListeners); if (this.sampler.enableBasic) this.sampler.pc[0] = Sampler.IDLE; } + addStepListener ({before, after}) { + if (typeof before !== 'function' && typeof after !== 'function') { + throw new TypeError('A step listener needs a before or after function'); + } + if (typeof before === 'function') this._beforeStepListeners = withListener(this._beforeStepListeners, before); + if (typeof after === 'function') this._afterStepListeners = withListener(this._afterStepListeners, after); + let removed = false; + return () => { + if (removed) return; + removed = true; + this._beforeStepListeners = withoutListener(this._beforeStepListeners, before); + this._afterStepListeners = withoutListener(this._afterStepListeners, after); + }; + } + /** * Get the number of threads in the given array that are monitor threads (threads * that update monitor values, and don't count as running a script). diff --git a/test/unit/engine_runtime_step_listeners.js b/test/unit/engine_runtime_step_listeners.js new file mode 100644 index 0000000000..0f85fb88bb --- /dev/null +++ b/test/unit/engine_runtime_step_listeners.js @@ -0,0 +1,86 @@ +const tap = require('tap'); +const Runtime = require('../../src/engine/runtime'); + +const test = tap.test; + +test('step listeners run before and after each step until removed', t => { + const rt = new Runtime(); + const calls = []; + rt.sequencer.stepThreads = () => { + calls.push('threads'); + return []; + }; + const remove = rt.addStepListener({ + before: () => calls.push('before'), + after: () => calls.push('after') + }); + rt._step(); + t.same(calls, ['before', 'threads', 'after']); + remove(); + remove(); + calls.length = 0; + rt._step(); + t.same(calls, ['threads']); + t.equal(rt._beforeStepListeners, null); + t.equal(rt._afterStepListeners, null); + t.end(); +}); + +test('step listeners can be added with only one side', t => { + const rt = new Runtime(); + const calls = []; + const removeAfter = rt.addStepListener({after: () => calls.push('after')}); + rt.addStepListener({before: () => calls.push('before')}); + rt._step(); + removeAfter(); + rt._step(); + t.same(calls, ['before', 'after', 'before']); + t.throws(() => rt.addStepListener({}), TypeError); + t.end(); +}); + +test('removing one step listener keeps another that uses the same function', t => { + const rt = new Runtime(); + let count = 0; + const after = () => { + count++; + }; + const removeFirst = rt.addStepListener({after}); + rt.addStepListener({after}); + removeFirst(); + rt._step(); + t.equal(count, 1); + t.end(); +}); + +test('a step listener that removes itself does not skip the others', t => { + const rt = new Runtime(); + const calls = []; + const removeFirst = rt.addStepListener({ + after: () => { + calls.push('first'); + removeFirst(); + } + }); + rt.addStepListener({after: () => calls.push('second')}); + rt._step(); + rt._step(); + t.same(calls, ['first', 'second', 'second']); + t.end(); +}); + +test('_step stays a writable prototype method that wrappers still reach', t => { + const descriptor = Object.getOwnPropertyDescriptor(Runtime.prototype, '_step'); + t.ok(descriptor.writable); + const rt = new Runtime(); + const calls = []; + rt.addStepListener({after: () => calls.push('listener')}); + const original = rt._step; + rt._step = function () { + original.call(this); + calls.push('wrapper'); + }; + rt._step(); + t.same(calls, ['listener', 'wrapper']); + t.end(); +}); From 70efc445a06165ee724181eafe4df78e0b7fa10c Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:25:22 +0000 Subject: [PATCH 2/5] Add a runtime pause that holds threads and stops hats from starting The debugger and the packager both pause projects by wrapping greenFlag, stopAll, startHats, sequencer.stepThreads and _getMonitorThreadCount. runtime.setPaused now does the shared part: it pauses the timer, holds every non-monitor thread until unpaused, moves their timers forward by the paused time, does not start hats other than broadcasts, clones and edge-activated hats called directly, skips edge-activated hats in the step, counts held threads as stopped, and emits RUNTIME_PAUSED and RUNTIME_UNPAUSED. stopAll and so the green flag unpause. pauseThread and getPausedThreadState let the debugger hold threads it starts while single stepping. --- src/engine/runtime-events.js | 4 + src/engine/runtime.js | 56 ++++++++++- src/engine/thread-pause.js | 50 ++++++++++ src/virtual-machine.js | 14 +++ test/unit/engine_runtime_pause.js | 148 ++++++++++++++++++++++++++++++ 5 files changed, 267 insertions(+), 5 deletions(-) create mode 100644 src/engine/thread-pause.js create mode 100644 test/unit/engine_runtime_pause.js diff --git a/src/engine/runtime-events.js b/src/engine/runtime-events.js index 5ed4e5417b..3c8e4d789f 100644 --- a/src/engine/runtime-events.js +++ b/src/engine/runtime-events.js @@ -83,6 +83,10 @@ const RuntimeEvents = { */ BEFORE_EXECUTE: 'BEFORE_EXECUTE', + RUNTIME_PAUSED: 'RUNTIME_PAUSED', + + RUNTIME_UNPAUSED: 'RUNTIME_UNPAUSED', + /** * Event called after every block in the project has been executed. */ diff --git a/src/engine/runtime.js b/src/engine/runtime.js index 01b415e921..190fbb8f4a 100644 --- a/src/engine/runtime.js +++ b/src/engine/runtime.js @@ -73,6 +73,7 @@ const callListeners = listeners => { } }; +const ThreadPause = require('./thread-pause'); const interpolate = require('./tw-interpolate'); const FrameLoop = require('./tw-frame-loop'); const MonitorRecord = require('./monitor-record.js'); @@ -190,6 +191,9 @@ class Runtime extends EventEmitter { this._beforeStepListeners = null; this._afterStepListeners = null; + this._paused = false; + this._pausedThreads = null; + /** * Live monitor threads by the block that started them. Saves a scan of every * thread for every monitored block, on every frame. @@ -1549,6 +1553,10 @@ class Runtime extends EventEmitter { const newThreads = []; // Look up metadata for the relevant hat. const hatMeta = instance._hats[requestedHatOpcode]; + if (this._paused && !hatMeta.edgeActivated && requestedHatOpcode !== 'event_whenbroadcastreceived' && + requestedHatOpcode !== 'control_start_as_clone') { + return newThreads; + } let matchFields = null; if (optMatchFields) { @@ -1879,6 +1887,40 @@ class Runtime extends EventEmitter { this._monitorThreads.clear(); this.resetRunId(); + this.setPaused(false); + } + + isPaused () { + return this._paused; + } + + setPaused (paused) { + paused = !!paused; + if (paused === this._paused) return; + this._paused = paused; + const clock = this.ioDevices.clock; + if (paused) { + if (!clock._paused) clock.pause(); + this._pausedThreads = new Map(); + for (let i = 0; i < this.threads.length; i++) { + this.pauseThread(this.threads[i]); + } + this.emit(Runtime.RUNTIME_PAUSED); + } else { + if (clock._paused) clock.resume(); + const pausedThreads = this._pausedThreads; + this._pausedThreads = null; + ThreadPause.releaseThreads(pausedThreads, this.threads, this.currentMSecs); + this.emit(Runtime.RUNTIME_UNPAUSED); + } + } + + pauseThread (thread) { + if (this._pausedThreads !== null) ThreadPause.holdThread(this._pausedThreads, thread, this.currentMSecs); + } + + getPausedThreadState (thread) { + return this._pausedThreads === null ? null : this._pausedThreads.get(thread) || null; } _renderInterpolatedPositions () { @@ -1965,11 +2007,13 @@ class Runtime extends EventEmitter { } // Find all edge-activated hats, and add them to threads to be evaluated. - for (const hatType in this._hats) { - if (!Object.prototype.hasOwnProperty.call(this._hats, hatType)) continue; - const hat = this._hats[hatType]; - if (hat.edgeActivated) { - this.startHats(hatType); + if (!this._paused) { + for (const hatType in this._hats) { + if (!Object.prototype.hasOwnProperty.call(this._hats, hatType)) continue; + const hat = this._hats[hatType]; + if (hat.edgeActivated) { + this.startHats(hatType); + } } } this.redrawRequested = false; @@ -1980,6 +2024,7 @@ class Runtime extends EventEmitter { } this.profiler.start(stepThreadsProfilerId); } + if (this._pausedThreads !== null) ThreadPause.keepThreadsHeld(this._pausedThreads, this.threads); this.emit(Runtime.BEFORE_EXECUTE); const doneThreads = this.sequencer.stepThreads(); if (this.profiler !== null) { @@ -2047,6 +2092,7 @@ class Runtime extends EventEmitter { for (let i = 0; i < threads.length; i++) { if (threads[i].updateMonitor) count++; } + if (this._pausedThreads !== null) count += ThreadPause.countHeldThreads(this._pausedThreads, threads); return count; } diff --git a/src/engine/thread-pause.js b/src/engine/thread-pause.js new file mode 100644 index 0000000000..ecc2206278 --- /dev/null +++ b/src/engine/thread-pause.js @@ -0,0 +1,50 @@ +const Thread = require('./thread'); + +const shiftTimer = (timer, elapsed) => { + if (timer) timer.startTime += elapsed; +}; + +const holdThread = (pausedThreads, thread, now) => { + if (thread.updateMonitor || pausedThreads.has(thread)) return; + pausedThreads.set(thread, {status: thread.status, time: now}); + thread.status = Thread.STATUS_PROMISE_WAIT; +}; + +const keepThreadsHeld = (pausedThreads, threads) => { + for (let i = 0; i < threads.length; i++) { + const thread = threads[i]; + const state = pausedThreads.get(thread); + if (!state || thread.status === Thread.STATUS_DONE || thread.status === Thread.STATUS_PROMISE_WAIT) continue; + state.status = thread.status; + thread.status = Thread.STATUS_PROMISE_WAIT; + } +}; + +const releaseThreads = (pausedThreads, threads, now) => { + for (let i = 0; i < threads.length; i++) { + const thread = threads[i]; + const state = pausedThreads.get(thread); + if (!state || thread.status === Thread.STATUS_DONE) continue; + const elapsed = now - state.time; + shiftTimer(thread.timer, elapsed); + if (thread.compatibilityStackFrame) shiftTimer(thread.compatibilityStackFrame.timer, elapsed); + const stackFrame = thread.peekStackFrame(); + if (stackFrame && stackFrame.executionContext) shiftTimer(stackFrame.executionContext.timer, elapsed); + thread.status = state.status; + } +}; + +const countHeldThreads = (pausedThreads, threads) => { + let count = 0; + for (let i = 0; i < threads.length; i++) { + if (pausedThreads.has(threads[i])) count++; + } + return count; +}; + +module.exports = { + holdThread, + keepThreadsHeld, + releaseThreads, + countHeldThreads +}; diff --git a/src/virtual-machine.js b/src/virtual-machine.js index 23345659f5..375a9b2c3a 100644 --- a/src/virtual-machine.js +++ b/src/virtual-machine.js @@ -210,6 +210,12 @@ class VirtualMachine extends EventEmitter { this.runtime.on(Runtime.RUNTIME_STOPPED, () => { this.emit(Runtime.RUNTIME_STOPPED); }); + this.runtime.on(Runtime.RUNTIME_PAUSED, () => { + this.emit(Runtime.RUNTIME_PAUSED); + }); + this.runtime.on(Runtime.RUNTIME_UNPAUSED, () => { + this.emit(Runtime.RUNTIME_UNPAUSED); + }); this.runtime.on(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData => { this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData); }); @@ -389,6 +395,14 @@ class VirtualMachine extends EventEmitter { this.runtime.setStageSize(width, height); } + setPaused (paused) { + this.runtime.setPaused(paused); + } + + isPaused () { + return this.runtime.isPaused(); + } + setProjectName (name) { this.runtime.setProjectName(name); } diff --git a/test/unit/engine_runtime_pause.js b/test/unit/engine_runtime_pause.js new file mode 100644 index 0000000000..82a935227b --- /dev/null +++ b/test/unit/engine_runtime_pause.js @@ -0,0 +1,148 @@ +const tap = require('tap'); +const Runtime = require('../../src/engine/runtime'); +const Thread = require('../../src/engine/thread'); +const VirtualMachine = require('../../src/virtual-machine'); + +const test = tap.test; + +const addThread = (rt, status, extra = {}) => { + const thread = new Thread('block'); + thread.status = status; + Object.assign(thread, extra); + thread.pushStack('block'); + rt.threads.push(thread); + return thread; +}; + +test('setPaused holds threads and restores their status', t => { + const rt = new Runtime(); + const events = []; + rt.on('RUNTIME_PAUSED', () => events.push('paused')); + rt.on('RUNTIME_UNPAUSED', () => events.push('unpaused')); + const running = addThread(rt, Thread.STATUS_RUNNING); + const yielded = addThread(rt, Thread.STATUS_YIELD_TICK); + const monitor = addThread(rt, Thread.STATUS_RUNNING, {updateMonitor: true}); + + rt.setPaused(true); + rt.setPaused(true); + t.equal(rt.isPaused(), true); + t.equal(running.status, Thread.STATUS_PROMISE_WAIT); + t.equal(yielded.status, Thread.STATUS_PROMISE_WAIT); + t.equal(monitor.status, Thread.STATUS_RUNNING); + t.same(rt.getPausedThreadState(running).status, Thread.STATUS_RUNNING); + t.equal(rt.getPausedThreadState(monitor), null); + t.equal(rt.ioDevices.clock._paused, true); + + rt.setPaused(false); + t.equal(rt.isPaused(), false); + t.equal(running.status, Thread.STATUS_RUNNING); + t.equal(yielded.status, Thread.STATUS_YIELD_TICK); + t.equal(rt.getPausedThreadState(running), null); + t.equal(rt.ioDevices.clock._paused, false); + t.same(events, ['paused', 'unpaused']); + t.end(); +}); + +test('a held thread whose promise settles stays held until unpaused', t => { + const rt = new Runtime(); + const waiting = addThread(rt, Thread.STATUS_PROMISE_WAIT); + rt.setPaused(true); + waiting.status = Thread.STATUS_RUNNING; + let stepped = null; + rt.sequencer.stepThreads = () => { + stepped = waiting.status; + return []; + }; + rt._step(); + t.equal(stepped, Thread.STATUS_PROMISE_WAIT); + rt.setPaused(false); + t.equal(waiting.status, Thread.STATUS_RUNNING); + t.end(); +}); + +test('unpausing moves thread timers forward by the paused time', t => { + const rt = new Runtime(); + const thread = addThread(rt, Thread.STATUS_RUNNING); + thread.timer = {startTime: 100}; + thread.peekStackFrame().executionContext = {timer: {startTime: 50}}; + rt.currentMSecs = 1000; + rt.setPaused(true); + rt.currentMSecs = 1600; + rt.setPaused(false); + t.equal(thread.timer.startTime, 700); + t.equal(thread.peekStackFrame().executionContext.timer.startTime, 650); + t.end(); +}); + +test('held threads do not count as running', t => { + const rt = new Runtime(); + const thread = addThread(rt, Thread.STATUS_RUNNING); + addThread(rt, Thread.STATUS_RUNNING, {updateMonitor: true}); + t.equal(rt._getMonitorThreadCount(rt.threads), 1); + rt.setPaused(true); + t.equal(rt._getMonitorThreadCount(rt.threads), 2); + const later = addThread(rt, Thread.STATUS_RUNNING); + t.equal(rt._getMonitorThreadCount(rt.threads), 2); + rt.pauseThread(later); + t.equal(rt._getMonitorThreadCount(rt.threads), 3); + t.equal(rt.getPausedThreadState(thread).status, Thread.STATUS_RUNNING); + t.end(); +}); + +test('while paused only broadcasts, clones and edge-activated hats start', t => { + const rt = new Runtime(); + const started = []; + rt._hats = { + event_whenkeypressed: {}, + event_whenbroadcastreceived: {}, + control_start_as_clone: {}, + test_whenEdge: {edgeActivated: true} + }; + rt.allScriptsByOpcodeDo = opcode => started.push(opcode); + rt.setPaused(true); + for (const opcode of Object.keys(rt._hats)) { + t.same(rt.startHats(opcode), [], opcode); + } + t.same(started, ['event_whenbroadcastreceived', 'control_start_as_clone', 'test_whenEdge']); + rt.setPaused(false); + rt.startHats('event_whenkeypressed'); + t.equal(started[started.length - 1], 'event_whenkeypressed'); + t.end(); +}); + +test('the step does not start edge-activated hats while paused', t => { + const rt = new Runtime(); + const started = []; + rt._hats = {test_whenEdge: {edgeActivated: true}}; + rt.startHats = opcode => started.push(opcode); + rt._step(); + rt.setPaused(true); + rt._step(); + t.same(started, ['test_whenEdge']); + t.end(); +}); + +test('stopping everything and the green flag unpause', t => { + const rt = new Runtime(); + rt.setPaused(true); + rt.stopAll(); + t.equal(rt.isPaused(), false); + rt.setPaused(true); + rt.greenFlag(); + t.equal(rt.isPaused(), false); + t.end(); +}); + +test('the VM exposes and forwards pausing', t => { + const vm = new VirtualMachine(); + const events = []; + vm.on('RUNTIME_PAUSED', () => events.push('paused')); + vm.on('RUNTIME_UNPAUSED', () => events.push('unpaused')); + vm.setPaused(true); + t.equal(vm.isPaused(), true); + t.equal(vm.runtime.isPaused(), true); + vm.setPaused(false); + t.equal(vm.isPaused(), false); + t.same(events, ['paused', 'unpaused']); + t.end(); +}); From 192c53ae14c9579d5adc682ff7840c0263d4c1a9 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:25:55 +0000 Subject: [PATCH 3/5] Add vm.addLoadProjectInterceptor for code that wraps project loads Project replacement, the project fetcher and collaboration replace vm.loadProject to check, schedule or follow loads. An interceptor gets the input, the options and a next function, can change either before calling next, and can refuse a load by throwing. The last one added runs first, and removing one does not depend on the order they were added in. Without interceptors loadProject loads directly. --- src/virtual-machine.js | 30 +++++++ .../unit/virtual-machine_load_interceptors.js | 90 +++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 test/unit/virtual-machine_load_interceptors.js diff --git a/src/virtual-machine.js b/src/virtual-machine.js index 375a9b2c3a..31e1b9f959 100644 --- a/src/virtual-machine.js +++ b/src/virtual-machine.js @@ -247,6 +247,8 @@ class VirtualMachine extends EventEmitter { this.emit(Runtime.TURBO_MODE_ON); }); + this._loadProjectInterceptors = []; + this.extensionManager = new ExtensionManager(this); this.securityManager = this.extensionManager.securityManager; this.runtime.extensionManager = this.extensionManager; @@ -583,6 +585,34 @@ class VirtualMachine extends EventEmitter { * @return {!Promise} Promise that resolves after targets are installed. */ loadProject (input, options = {}) { + if (this._loadProjectInterceptors.length === 0) return this._loadProjectDirectly(input, options); + const interceptors = this._loadProjectInterceptors.slice(); + const run = (index, currentInput, currentOptions) => { + if (index < 0) return this._loadProjectDirectly(currentInput, currentOptions); + const next = (nextInput = currentInput, nextOptions = currentOptions) => + run(index - 1, nextInput, nextOptions); + try { + return Promise.resolve(interceptors[index](currentInput, currentOptions, next)); + } catch (error) { + return Promise.reject(error); + } + }; + return run(interceptors.length - 1, input, options); + } + + addLoadProjectInterceptor (interceptor) { + if (typeof interceptor !== 'function') throw new TypeError('A load project interceptor must be a function'); + this._loadProjectInterceptors.push(interceptor); + let removed = false; + return () => { + if (removed) return; + removed = true; + const index = this._loadProjectInterceptors.indexOf(interceptor); + if (index !== -1) this._loadProjectInterceptors.splice(index, 1); + }; + } + + _loadProjectDirectly (input, options = {}) { const generation = (this._projectLoadGeneration || 0) + 1; this._projectLoadGeneration = generation; const active = () => this._projectLoadGeneration === generation && diff --git a/test/unit/virtual-machine_load_interceptors.js b/test/unit/virtual-machine_load_interceptors.js new file mode 100644 index 0000000000..95445b017f --- /dev/null +++ b/test/unit/virtual-machine_load_interceptors.js @@ -0,0 +1,90 @@ +const tap = require('tap'); +const VirtualMachine = require('../../src/virtual-machine'); + +const test = tap.test; + +const makeVM = () => { + const vm = new VirtualMachine(); + const loads = []; + vm._loadProjectDirectly = (input, options) => { + loads.push([input, options]); + return Promise.resolve('loaded'); + }; + return {vm, loads}; +}; + +test('loadProject without interceptors loads directly', async t => { + const {vm, loads} = makeVM(); + t.equal(await vm.loadProject('a'), 'loaded'); + t.same(loads, [['a', {}]]); + t.end(); +}); + +test('interceptors wrap the load, the last added outermost', async t => { + const {vm, loads} = makeVM(); + const calls = []; + vm.addLoadProjectInterceptor(async (input, options, next) => { + calls.push(`inner ${input}`); + const result = await next(); + calls.push('inner done'); + return result; + }); + vm.addLoadProjectInterceptor((input, options, next) => { + calls.push(`outer ${input} ${options.flag}`); + return next('b', {flag: 2}); + }); + t.equal(await vm.loadProject('a', {flag: 1}), 'loaded'); + t.same(calls, ['outer a 1', 'inner b', 'inner done']); + t.same(loads, [['b', {flag: 2}]]); + t.end(); +}); + +test('an interceptor can refuse a load by throwing', async t => { + const {vm, loads} = makeVM(); + vm.addLoadProjectInterceptor(() => { + throw new Error('no'); + }); + let returned = null; + t.doesNotThrow(() => { + returned = vm.loadProject('a'); + }); + await t.rejects(returned, /no/); + t.same(loads, []); + t.end(); +}); + +test('removing an interceptor leaves the others in any order', async t => { + const {vm} = makeVM(); + const calls = []; + const removeFirst = vm.addLoadProjectInterceptor((input, options, next) => { + calls.push('first'); + return next(); + }); + vm.addLoadProjectInterceptor((input, options, next) => { + calls.push('second'); + return next(); + }); + removeFirst(); + removeFirst(); + await vm.loadProject('a'); + t.same(calls, ['second']); + t.throws(() => vm.addLoadProjectInterceptor(null), TypeError); + t.end(); +}); + +test('patches of loadProject still wrap the interceptors', async t => { + const {vm} = makeVM(); + const calls = []; + vm.addLoadProjectInterceptor((input, options, next) => { + calls.push('interceptor'); + return next(); + }); + const original = vm.loadProject; + vm.loadProject = function (...args) { + calls.push('patch'); + return original.apply(this, args); + }; + await vm.loadProject('a'); + t.same(calls, ['patch', 'interceptor']); + t.end(); +}); From 0727a0db3a66ec2e3d4c7be972f19fc66bf263ab Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:26:58 +0000 Subject: [PATCH 4/5] Add vm.registerProjectMetadata for extra keys in the project meta The GUI wraps toJSON and deserializeProject to stamp authorship and dates into project.json, re-parsing the whole project on every save. A registered key's serialize runs when a whole project is saved and its result is written into meta before stringifying; deserialize runs on every project load with that key's loaded value, or undefined. The built-in keys semver, vm, origin and platform are reserved, and a handler that throws is logged without failing the save or load. --- src/virtual-machine.js | 47 +++++++++- test/unit/virtual-machine_project_metadata.js | 90 +++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 test/unit/virtual-machine_project_metadata.js diff --git a/src/virtual-machine.js b/src/virtual-machine.js index 31e1b9f959..7066dc4002 100644 --- a/src/virtual-machine.js +++ b/src/virtual-machine.js @@ -38,6 +38,8 @@ const {replaceTargetScripts} = require('./engine/replace-target-scripts'); const RESERVED_NAMES = ['_mouse_', '_stage_', '_edge_', '_myself_', '_random_']; +const RESERVED_METADATA_KEYS = ['semver', 'vm', 'origin', 'platform']; + if (typeof document === 'undefined') { global.document = { createElement: tagName => { @@ -248,6 +250,7 @@ class VirtualMachine extends EventEmitter { }); this._loadProjectInterceptors = []; + this._projectMetadata = new Map(); this.extensionManager = new ExtensionManager(this); this.securityManager = this.extensionManager.securityManager; @@ -895,7 +898,48 @@ class VirtualMachine extends EventEmitter { */ toJSON (optTargetId, serializationOptions) { const sb3 = require('./serialization/sb3'); - return StringUtil.stringify(sb3.serialize(this.runtime, optTargetId, serializationOptions)); + const json = sb3.serialize(this.runtime, optTargetId, serializationOptions); + if (!optTargetId && this._projectMetadata.size !== 0) this._serializeProjectMetadata(json.meta); + return StringUtil.stringify(json); + } + + registerProjectMetadata (key, {serialize, deserialize}) { + if (typeof key !== 'string' || key === '' || RESERVED_METADATA_KEYS.includes(key)) { + throw new TypeError(`Project metadata cannot use the key ${key}`); + } + if (this._projectMetadata.has(key)) throw new Error(`Project metadata ${key} is already registered`); + const handler = { + serialize: typeof serialize === 'function' ? serialize : null, + deserialize: typeof deserialize === 'function' ? deserialize : null + }; + this._projectMetadata.set(key, handler); + return () => { + if (this._projectMetadata.get(key) === handler) this._projectMetadata.delete(key); + }; + } + + _serializeProjectMetadata (meta) { + for (const [key, handler] of this._projectMetadata) { + if (!handler.serialize) continue; + try { + const value = handler.serialize(meta[key]); + if (typeof value !== 'undefined') meta[key] = value; + } catch (error) { + log.error(`Could not save project metadata ${key}`, error); + } + } + } + + _deserializeProjectMetadata (meta) { + const loaded = meta !== null && typeof meta === 'object' ? meta : {}; + for (const [key, handler] of this._projectMetadata) { + if (!handler.deserialize) continue; + try { + handler.deserialize(Object.prototype.hasOwnProperty.call(loaded, key) ? loaded[key] : void 0); + } catch (error) { + log.error(`Could not load project metadata ${key}`, error); + } + } } // TODO do we still need this function? Keeping it here so as not to introduce @@ -927,6 +971,7 @@ class VirtualMachine extends EventEmitter { * @returns {Promise} Promise that resolves after the project has loaded */ deserializeProject (projectJSON, zip, active = () => true) { + if (this._projectMetadata.size !== 0) this._deserializeProjectMetadata(projectJSON && projectJSON.meta); // Clear the current runtime this.clear(); diff --git a/test/unit/virtual-machine_project_metadata.js b/test/unit/virtual-machine_project_metadata.js new file mode 100644 index 0000000000..b8b5412e18 --- /dev/null +++ b/test/unit/virtual-machine_project_metadata.js @@ -0,0 +1,90 @@ +const tap = require('tap'); +const path = require('path'); +const fs = require('fs'); +const VirtualMachine = require('../../src/virtual-machine'); + +const test = tap.test; + +const projectPath = path.resolve(__dirname, '../fixtures/default.sb3'); + +test('registered metadata is written to the project meta and read back on load', async t => { + const vm = new VirtualMachine(); + let loaded = 'unset'; + let created = null; + vm.registerProjectMetadata('created', { + serialize: () => created, + deserialize: value => { + loaded = value; + } + }); + vm.registerProjectMetadata('agent', {serialize: builtIn => `${builtIn}custom`}); + + await vm.loadProject(fs.readFileSync(projectPath)); + t.equal(loaded, undefined); + + created = '2026-11-01'; + const meta = JSON.parse(vm.toJSON()).meta; + t.equal(meta.created, '2026-11-01'); + t.equal(meta.agent, 'custom'); + t.equal(meta.semver, '3.0.0'); + + await vm.loadProject(vm.toJSON()); + t.equal(loaded, '2026-11-01'); + t.end(); +}); + +test('a serializer that returns undefined writes nothing', t => { + const vm = new VirtualMachine(); + vm.registerProjectMetadata('author', {serialize: () => undefined}); + const meta = JSON.parse(vm.toJSON()).meta; + t.notOk(Object.prototype.hasOwnProperty.call(meta, 'author')); + t.end(); +}); + +test('sprite exports do not get project metadata', async t => { + const vm = new VirtualMachine(); + await vm.loadProject(fs.readFileSync(projectPath)); + let calls = 0; + vm.registerProjectMetadata('created', { + serialize: () => { + calls++; + return 'x'; + } + }); + const sprite = vm.runtime.targets.find(target => !target.isStage); + const json = JSON.parse(vm.toJSON(sprite.id)); + t.equal(calls, 0); + t.notOk(json.meta); + t.end(); +}); + +test('keys are unique, built-in keys are reserved and handlers can be removed', t => { + const vm = new VirtualMachine(); + const remove = vm.registerProjectMetadata('created', {serialize: () => 'a'}); + t.throws(() => vm.registerProjectMetadata('created', {})); + t.throws(() => vm.registerProjectMetadata('platform', {}), TypeError); + t.throws(() => vm.registerProjectMetadata('', {}), TypeError); + remove(); + t.notOk(Object.prototype.hasOwnProperty.call(JSON.parse(vm.toJSON()).meta, 'created')); + vm.registerProjectMetadata('created', {serialize: () => 'b'}); + remove(); + t.equal(JSON.parse(vm.toJSON()).meta.created, 'b'); + t.end(); +}); + +test('a failing handler does not break saving or loading', async t => { + const vm = new VirtualMachine(); + vm.registerProjectMetadata('broken', { + serialize: () => { + throw new Error('save'); + }, + deserialize: () => { + throw new Error('load'); + } + }); + const json = vm.toJSON(); + t.ok(JSON.parse(json).meta); + await vm.loadProject(fs.readFileSync(projectPath)); + t.ok(vm.runtime.targets.length > 0); + t.end(); +}); From 5a41b1a6aefc6fc1f5e158cc5c506d9a915663b8 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:54:38 +0000 Subject: [PATCH 5/5] Keep a held thread's status when its promise settles before unpausing A thread paused while waiting on a promise is held in PROMISE_WAIT. If the promise settled and unpausing came before the next step, its saved PROMISE_WAIT was restored over the RUNNING the promise had set, and nothing woke it again. Unpausing now restores the saved status only for threads still held in PROMISE_WAIT. --- src/engine/thread-pause.js | 2 +- test/unit/engine_runtime_pause.js | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/engine/thread-pause.js b/src/engine/thread-pause.js index ecc2206278..33face6fb5 100644 --- a/src/engine/thread-pause.js +++ b/src/engine/thread-pause.js @@ -30,7 +30,7 @@ const releaseThreads = (pausedThreads, threads, now) => { if (thread.compatibilityStackFrame) shiftTimer(thread.compatibilityStackFrame.timer, elapsed); const stackFrame = thread.peekStackFrame(); if (stackFrame && stackFrame.executionContext) shiftTimer(stackFrame.executionContext.timer, elapsed); - thread.status = state.status; + if (thread.status === Thread.STATUS_PROMISE_WAIT) thread.status = state.status; } }; diff --git a/test/unit/engine_runtime_pause.js b/test/unit/engine_runtime_pause.js index 82a935227b..006fee8a21 100644 --- a/test/unit/engine_runtime_pause.js +++ b/test/unit/engine_runtime_pause.js @@ -60,6 +60,16 @@ test('a held thread whose promise settles stays held until unpaused', t => { t.end(); }); +test('a held thread whose promise settles just before unpausing keeps running', t => { + const rt = new Runtime(); + const waiting = addThread(rt, Thread.STATUS_PROMISE_WAIT); + rt.setPaused(true); + waiting.status = Thread.STATUS_RUNNING; + rt.setPaused(false); + t.equal(waiting.status, Thread.STATUS_RUNNING); + t.end(); +}); + test('unpausing moves thread timers forward by the paused time', t => { const rt = new Runtime(); const thread = addThread(rt, Thread.STATUS_RUNNING);