diff --git a/.github/scripts/align_android_beta_toolchain.py b/.github/scripts/align_android_beta_toolchain.py new file mode 100644 index 0000000..0faf1a9 --- /dev/null +++ b/.github/scripts/align_android_beta_toolchain.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Align beta-only Android CI with the selected Flutter SDK's Android templates. + +Stable Flutter jobs keep the repository's checked-in Android configuration. +Flutter beta can move its minimum AGP/Gradle versions ahead of stable releases. +""" +import os +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sdk_root = os.environ.get("FLUTTER_ROOT") +if not sdk_root: + raise SystemExit("FLUTTER_ROOT is required after setting up Flutter beta") +defaults_path = Path(sdk_root) / "packages/flutter_tools/lib/src/android/gradle_utils.dart" +defaults = defaults_path.read_text(encoding="utf-8") + + +def sdk_version(constant: str) -> str: + match = re.search(rf"^const {re.escape(constant)} = '([0-9.]+)';$", defaults, re.MULTILINE) + if not match: + raise RuntimeError(f"Cannot determine Flutter SDK {constant}") + return match.group(1) + + +def rewrite_one(path: Path, pattern: str, replacement: str) -> None: + source = path.read_text(encoding="utf-8") + updated, changes = re.subn(pattern, replacement, source, count=1, flags=re.MULTILINE) + if changes != 1: + raise RuntimeError(f"Expected one match for {pattern!r} in {path}") + path.write_text(updated, encoding="utf-8") + + +agp = sdk_version("templateAndroidGradlePluginVersion") +gradle = sdk_version("templateDefaultGradleVersion") +kotlin = sdk_version("templateKotlinGradlePluginVersion") +android_root = ROOT / "wakelock_plus/example/android" + +rewrite_one( + android_root / "settings.gradle", + r'(id "com\.android\.application" version ")[^"]+(" apply false)', + rf'\g<1>{agp}\g<2>', +) +rewrite_one( + android_root / "settings.gradle", + r'(id "org\.jetbrains\.kotlin\.android" version ")[^"]+(" apply false)', + rf'\g<1>{kotlin}\g<2>', +) +rewrite_one( + android_root / "gradle/wrapper/gradle-wrapper.properties", + r'(distributionUrl=https\\://services\.gradle\.org/distributions/gradle-)[0-9.]+(-bin\.zip)', + rf'\g<1>{gradle}\g<2>', +) +rewrite_one( + android_root / "gradle.properties", + r'^android\.builtInKotlin=false$', + "android.builtInKotlin=true", +) +# Keep android.newDsl=false to preserve legacy example app DSL compatibility. +print(f"Flutter beta CI: AGP {agp}, Gradle {gradle}, Kotlin {kotlin}") diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3ad8283..d416675 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -121,6 +121,7 @@ jobs: strategy: matrix: flutter_version: ${{ fromJson(needs.setup_matrix.outputs.flutter_versions_json) }} + fail-fast: false name: Android Example Build (${{ matrix.flutter_version }}) steps: - uses: actions/checkout@v6 @@ -134,6 +135,9 @@ jobs: channel: ${{ (!contains(matrix.flutter_version, '.') && !contains(matrix.flutter_version, 'x')) && matrix.flutter_version || '' }} cache: true cache-key: flutter-:os:-:channel:-:version:-:arch:-:hash:-${{ hashFiles('**/pubspec.lock') }} + - name: Match Android tooling to Flutter beta + if: matrix.flutter_version == 'beta' + run: python3 .github/scripts/align_android_beta_toolchain.py - name: Build Android APK run: | cd wakelock_plus/example @@ -170,6 +174,9 @@ jobs: cache: true cache-key: flutter-:os:-:channel:-:version:-:arch:-:hash:-${{ hashFiles('**/pubspec.lock') }} + - name: Match Android tooling to Flutter beta + if: matrix.flutter_version == 'beta' + run: python3 .github/scripts/align_android_beta_toolchain.py - name: Enable KVM # Linux runners require KVM to run Android emulators with hardware acceleration run: | @@ -450,6 +457,21 @@ jobs: flutter pub get flutter drive -d windows --driver=test_driver/integration_test.dart --target=integration_test/wakelock_plus_test.dart + # Run the browser API mocks without requiring a real browser or Flutter SDK. + web_js_regression_tests: + runs-on: ubuntu-latest + timeout-minutes: 5 + name: Web JavaScript Regression Tests + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Validate JavaScript syntax + run: node --check wakelock_plus/lib/assets/no_sleep.js + - name: Run web concurrency regression tests + run: node --test wakelock_plus/test/no_sleep_concurrency.test.cjs + # --- WEB --- web_example_build: diff --git a/wakelock_plus/lib/assets/no_sleep.js b/wakelock_plus/lib/assets/no_sleep.js index 3ae1af0..d9b8ca5 100644 --- a/wakelock_plus/lib/assets/no_sleep.js +++ b/wakelock_plus/lib/assets/no_sleep.js @@ -1,32 +1,5 @@ /*! Based On NoSleep.js v0.12.0 - git.io/vfn01 - Rich Tibbett - MIT license */ -class PromiseCompleter { - _promise; - _resolve; - _reject; - constructor() { - this._promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - }); - } - - isCompleted = false; - - get future() { - return this._promise; - } - - complete(value) { - this.isCompleted = true; - this._resolve(value); - } - - completeError(error) { - this._reject(error); - } -} - var webm = 'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=' var mp4 = @@ -59,8 +32,6 @@ function _classCallCheck(instance, Constructor) { var nativeWakeLock = 'wakeLock' in navigator var NoSleep = (function () { - var _nativeEnabledCompleter; - var _playVideoCompleter; function NoSleep() { var _this = this @@ -70,6 +41,9 @@ var NoSleep = (function () { this.nativeEnabled = false if (nativeWakeLock) { this._wakeLock = null + this._nativeOperation = Promise.resolve() + this._nativePendingEnable = null + this._requestEnabling = false var handleVisibilityChange = function handleVisibilityChange() { if (_this._wakeLock !== null && document.visibilityState === 'visible') { _this.enable() @@ -86,6 +60,9 @@ var NoSleep = (function () { this._addSourceToVideo(this.noSleepVideo, 'webm', webm) this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4) + this._videoOperation = null + this._videoPendingEnable = null + this._requestEnabling = false this.noSleepVideo.addEventListener('loadedmetadata', function () { if (_this.noSleepVideo.duration <= 1) { @@ -116,51 +93,86 @@ var NoSleep = (function () { { key: 'enable', value: async function enable() { - var _this2 = this - if (nativeWakeLock) { - // Disable any previously held wakelocks. - await this.disable() - if (_nativeEnabledCompleter == null) { - _nativeEnabledCompleter = new PromiseCompleter() + this._requestEnabling = true + // Share in-flight requests and serialize state changes. + if (this._nativePendingEnable != null) { + return this._nativePendingEnable } - navigator.wakeLock - .request('screen') - .then(function (wakeLock) { - _this2._wakeLock = wakeLock - _this2.nativeEnabled = true - - // We now have a wakelock. Notify all of the existing callers. - _this2._wakeLock.addEventListener('release', function () { - _this2.nativeEnabled = false - _this2._wakeLock = null - }) - - _nativeEnabledCompleter.complete() - _nativeEnabledCompleter = null - }) - .catch(function (err) { - _this2.nativeEnabled = false - var errorMessage = err.name + ', ' + err.message - _nativeEnabledCompleter.completeError(errorMessage) - _nativeEnabledCompleter = null + const operation = this._nativeOperation.then(async () => { + if (!this._requestEnabling || this._wakeLock != null) { + return + } + const wakeLock = await navigator.wakeLock.request('screen') + wakeLock.addEventListener('release', () => { + // A late event from a previous lock must not clear the current one. + if (this._wakeLock === wakeLock) { + this._wakeLock = null + this.nativeEnabled = false + } }) - // We then wait for screen to be made available. - return _nativeEnabledCompleter.future + if (!this._requestEnabling) { + await wakeLock.release() + return + } + this._wakeLock = wakeLock + this.nativeEnabled = true + }) + this._nativePendingEnable = operation + // Keep the queue usable after a rejection, but reject the callers. + this._nativeOperation = operation.catch(() => {}) + void operation.then( + () => { + if (this._nativePendingEnable === operation) { + this._nativePendingEnable = null + } + }, + () => { + if (this._nativePendingEnable === operation) { + this._nativePendingEnable = null + } + }, + ) + return operation } else { - if (_playVideoCompleter == null) { - _playVideoCompleter = new PromiseCompleter() + this._requestEnabling = true + if (this._videoPendingEnable != null) { + return this._videoPendingEnable + } + const play = async () => { + if (!this._requestEnabling || !this.noSleepVideo.paused) { + return + } + // Preserve user activation by calling play synchronously when idle. + await this.noSleepVideo.play() + if (!this._requestEnabling) { + this.noSleepVideo.pause() + } } - var playPromise = this.noSleepVideo.play() - playPromise.then(function (res) { - _playVideoCompleter.complete() - _playVideoCompleter = null - }).catch(function (err) { - var errorMessage = err.name + ', ' + err.message - _playVideoCompleter.completeError(errorMessage) - _playVideoCompleter = null - }); - return _playVideoCompleter.future + const operation = this._videoOperation == null + ? play() + : this._videoOperation.then(play) + this._videoPendingEnable = operation + const queue = operation.catch(() => {}) + this._videoOperation = queue + void queue.then(() => { + if (this._videoOperation === queue) { + this._videoOperation = null + } + }) + void operation.then( + () => { + if (this._videoPendingEnable === operation) { + this._videoPendingEnable = null + } + }, + () => { + if (this._videoPendingEnable === operation) { + this._videoPendingEnable = null + } + }, + ) + return operation } }, }, @@ -168,21 +180,39 @@ var NoSleep = (function () { key: 'disable', value: async function disable() { if (nativeWakeLock) { - // If we're still trying to enable the wakelock, wait for it to be enabled - if (_nativeEnabledCompleter != null) { - await _nativeEnabledCompleter.future - } - if (this._wakeLock != null) { + this._requestEnabling = false + // Do not let a later enable inherit an obsolete pending request. + this._nativePendingEnable = null + const operation = this._nativeOperation.then(async () => { + if (this._requestEnabling || this._wakeLock == null) { + return + } + const wakeLock = this._wakeLock + this._wakeLock = null this.nativeEnabled = false - this._wakeLock.release() - } - - this._wakeLock = null + await wakeLock.release() + }) + this._nativeOperation = operation.catch(() => {}) + return operation } else { - if (_playVideoCompleter != null) { - await _playVideoCompleter.future + this._requestEnabling = false + this._videoPendingEnable = null + const pause = () => { + if (!this._requestEnabling) { + this.noSleepVideo.pause() + } } - this.noSleepVideo.pause() + const operation = this._videoOperation == null + ? Promise.resolve(pause()) + : this._videoOperation.then(pause) + const queue = operation.catch(() => {}) + this._videoOperation = queue + void queue.then(() => { + if (this._videoOperation === queue) { + this._videoOperation = null + } + }) + return operation } return Promise.resolve(); }, @@ -191,20 +221,12 @@ var NoSleep = (function () { key: 'isEnabled', value: async function isEnabled() { if (nativeWakeLock) { - // If we're still trying to enable the wakelock, wait for it to be enabled - if (_nativeEnabledCompleter != null) { - await _nativeEnabledCompleter.future - } - + await this._nativeOperation return this.nativeEnabled } else { - if (_playVideoCompleter != null) { - await _playVideoCompleter.future + if (this._videoOperation != null) { + await this._videoOperation } - if (this.noSleepVideo == undefined) { - return false - } - return !this.noSleepVideo.paused } }, diff --git a/wakelock_plus/test/no_sleep_concurrency.test.cjs b/wakelock_plus/test/no_sleep_concurrency.test.cjs new file mode 100644 index 0000000..9e6aa1e --- /dev/null +++ b/wakelock_plus/test/no_sleep_concurrency.test.cjs @@ -0,0 +1,241 @@ +// Regression tests for browser Wake Lock and video fallback concurrency. +// Run: node --test wakelock_plus/test/no_sleep_concurrency.test.cjs +const { test } = require('node:test') +const assert = require('node:assert/strict') +const fs = require('node:fs') +const path = require('node:path') +const vm = require('node:vm') + +const sourcePath = path.join(__dirname, '..', 'lib', 'assets', 'no_sleep.js') +const flush = () => new Promise(resolve => setImmediate(resolve)) + +function deferred() { + let resolve + let reject + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} + +function browser(native) { + const requests = [] + const plays = [] + const video = { + paused: true, + setAttribute() {}, + addEventListener() {}, + appendChild() {}, + play() { + const request = deferred() + plays.push(request) + return request.promise.then(() => { video.paused = false }) + }, + pause() { video.paused = true }, + } + const document = { + visibilityState: 'visible', + addEventListener() {}, + createElement(tag) { + if (tag === 'video') return video + if (tag === 'source') return {} + throw new Error('Unexpected element: ' + tag) + }, + } + const navigator = native ? { wakeLock: { request(type) { + assert.equal(type, 'screen') + const request = deferred() + requests.push(request) + return request.promise + } } } : {} + const sandbox = vm.createContext({ navigator, document, console, setTimeout, clearTimeout }) + vm.runInContext(fs.readFileSync(sourcePath, 'utf8'), sandbox, { filename: sourcePath }) + const NoSleep = vm.runInContext('NoSleep', sandbox) + const noSleep = new NoSleep() + function createLock() { + const handlers = [] + let releases = 0 + return { + addEventListener(name, fn) { assert.equal(name, 'release'); handlers.push(fn) }, + async release() { releases++; handlers.forEach(fn => fn()) }, + emitRelease() { handlers.forEach(fn => fn()) }, + get releases() { return releases }, + } + } + return { noSleep, requests, plays, video, createLock } +} + +test('native: concurrent enable calls share a single request', async () => { + const b = browser(true) + const all = [b.noSleep.enable(), b.noSleep.enable(), b.noSleep.enable()] + await flush() + assert.equal(b.requests.length, 1) + b.requests[0].resolve(b.createLock()) + await Promise.all(all) + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('native: concurrent request rejection reaches each caller', async () => { + const b = browser(true) + const all = [b.noSleep.enable(), b.noSleep.enable()] + await flush() + assert.equal(b.requests.length, 1) + b.requests[0].reject(Object.assign(new Error('activation required'), { name: 'NotAllowedError' })) + assert.deepEqual((await Promise.allSettled(all)).map(x => x.status), ['rejected', 'rejected']) + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('native: disable during pending request releases resulting lock', async () => { + const b = browser(true) + const enable = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + const lock = b.createLock() + b.requests[0].resolve(lock) + await Promise.all([enable, disable]) + assert.equal(lock.releases, 1) + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('native: enable-disable-enable preserves last requested state', async () => { + const b = browser(true) + const first = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + const second = b.noSleep.enable() + b.requests[0].resolve(b.createLock()) + await flush() + if (b.requests[1]) b.requests[1].resolve(b.createLock()) + await Promise.all([first, disable, second]) + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('native: redundant enable does not request a second lock', async () => { + const b = browser(true) + const enable = b.noSleep.enable() + await flush() + const lock = b.createLock() + b.requests[0].resolve(lock) + await enable + await b.noSleep.enable() + assert.equal(b.requests.length, 1) + assert.equal(lock.releases, 0) +}) + +test('native: rejected request permits later retry', async () => { + const b = browser(true) + const first = b.noSleep.enable() + await flush() + b.requests[0].reject(new Error('denied')) + await assert.rejects(first) + const retry = b.noSleep.enable() + await flush() + assert.equal(b.requests.length, 2) + b.requests[1].resolve(b.createLock()) + await retry + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('native: disable after failure remains safe', async () => { + const b = browser(true) + const enable = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + b.requests[0].reject(new Error('denied')) + await assert.rejects(enable) + await assert.doesNotReject(disable) + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('native: stale release event cannot clear a newer wake lock', async () => { + const b = browser(true) + const first = b.noSleep.enable() + await flush() + const previous = b.createLock() + b.requests[0].resolve(previous) + await first + await b.noSleep.disable() + const second = b.noSleep.enable() + await flush() + b.requests[1].resolve(b.createLock()) + await second + previous.emitRelease() + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('native: external release updates enabled state', async () => { + const b = browser(true) + const enable = b.noSleep.enable() + await flush() + const lock = b.createLock() + b.requests[0].resolve(lock) + await enable + lock.emitRelease() + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('fallback: concurrent enables share a single play request', async () => { + const b = browser(false) + const all = [b.noSleep.enable(), b.noSleep.enable(), b.noSleep.enable()] + await flush() + assert.equal(b.plays.length, 1) + b.plays[0].resolve() + await Promise.all(all) + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('fallback: rejected play reaches callers and later retry works', async () => { + const b = browser(false) + const all = [b.noSleep.enable(), b.noSleep.enable()] + await flush() + assert.equal(b.plays.length, 1) + b.plays[0].reject(new Error('denied')) + assert.deepEqual((await Promise.allSettled(all)).map(x => x.status), ['rejected', 'rejected']) + const retry = b.noSleep.enable() + await flush() + assert.equal(b.plays.length, 2) + b.plays[1].resolve() + await retry + assert.equal(await b.noSleep.isEnabled(), true) +}) + +test('fallback: disable during play ends paused', async () => { + const b = browser(false) + const enable = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + b.plays[0].resolve() + await Promise.all([enable, disable]) + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('fallback: disable after play rejection succeeds', async () => { + const b = browser(false) + const enable = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + b.plays[0].reject(new Error('denied')) + await assert.rejects(enable) + await assert.doesNotReject(disable) + assert.equal(await b.noSleep.isEnabled(), false) +}) + +test('fallback: enable-disable-enable ends playing', async () => { + const b = browser(false) + const first = b.noSleep.enable() + await flush() + const disable = b.noSleep.disable() + const second = b.noSleep.enable() + b.plays[0].resolve() + await flush() + if (b.plays[1]) b.plays[1].resolve() + await Promise.all([first, disable, second]) + assert.equal(await b.noSleep.isEnabled(), true) +}) + + +test('fallback: first play remains synchronous for user activation', async () => { + const b = browser(false) + const enabling = b.noSleep.enable() + assert.equal(b.plays.length, 1, 'play() should run during the event handler') + b.plays[0].resolve() + await enabling +})