From a8f89550e36df0ecdaa0dc3eabb2507b851cc87c Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 12:22:33 +0500 Subject: [PATCH 1/8] fix(web): serialize wake lock and fallback playback operations --- wakelock_plus/lib/assets/no_sleep.js | 162 ++++++++++++++++----------- 1 file changed, 95 insertions(+), 67 deletions(-) diff --git a/wakelock_plus/lib/assets/no_sleep.js b/wakelock_plus/lib/assets/no_sleep.js index 3ae1af0..23b8e36 100644 --- a/wakelock_plus/lib/assets/no_sleep.js +++ b/wakelock_plus/lib/assets/no_sleep.js @@ -59,8 +59,6 @@ function _classCallCheck(instance, Constructor) { var nativeWakeLock = 'wakeLock' in navigator var NoSleep = (function () { - var _nativeEnabledCompleter; - var _playVideoCompleter; function NoSleep() { var _this = this @@ -70,6 +68,9 @@ var NoSleep = (function () { this.nativeEnabled = false if (nativeWakeLock) { this._wakeLock = null + this._nativeOperation = Promise.resolve() + this._nativePendingEnable = null + this._desiredEnabled = false var handleVisibilityChange = function handleVisibilityChange() { if (_this._wakeLock !== null && document.visibilityState === 'visible') { _this.enable() @@ -86,6 +87,9 @@ var NoSleep = (function () { this._addSourceToVideo(this.noSleepVideo, 'webm', webm) this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4) + this._videoOperation = Promise.resolve() + this._videoPendingEnable = null + this._desiredEnabled = false this.noSleepVideo.addEventListener('loadedmetadata', function () { if (_this.noSleepVideo.duration <= 1) { @@ -116,51 +120,76 @@ 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._desiredEnabled = 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._desiredEnabled || 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._desiredEnabled) { + 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._desiredEnabled = true + if (this._videoPendingEnable != null) { + return this._videoPendingEnable } - 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.then(async () => { + if (!this._desiredEnabled || !this.noSleepVideo.paused) { + return + } + await this.noSleepVideo.play() + if (!this._desiredEnabled) { + this.noSleepVideo.pause() + } + }) + this._videoPendingEnable = operation + this._videoOperation = operation.catch(() => {}) + void operation.then( + () => { + if (this._videoPendingEnable === operation) { + this._videoPendingEnable = null + } + }, + () => { + if (this._videoPendingEnable === operation) { + this._videoPendingEnable = null + } + }, + ) + return operation } }, }, @@ -168,21 +197,30 @@ 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._desiredEnabled = false + // Do not let a later enable inherit an obsolete pending request. + this._nativePendingEnable = null + const operation = this._nativeOperation.then(async () => { + if (this._desiredEnabled || 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.noSleepVideo.pause() + this._desiredEnabled = false + this._videoPendingEnable = null + const operation = this._videoOperation.then(() => { + if (!this._desiredEnabled) { + this.noSleepVideo.pause() + } + }) + this._videoOperation = operation.catch(() => {}) + return operation } return Promise.resolve(); }, @@ -191,20 +229,10 @@ 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.noSleepVideo == undefined) { - return false - } - + await this._videoOperation return !this.noSleepVideo.paused } }, From 6ebd5518ec1f6367d3d532df52e21a201f017487 Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 12:23:14 +0500 Subject: [PATCH 2/8] test(web): cover wake lock and video fallback races --- .../test/no_sleep_concurrency.test.cjs | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 wakelock_plus/test/no_sleep_concurrency.test.cjs 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..d0e3de6 --- /dev/null +++ b/wakelock_plus/test/no_sleep_concurrency.test.cjs @@ -0,0 +1,232 @@ +// 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) +}) From 1512f867ea3e232c59e73dde5031f188e2f8ab23 Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 12:25:58 +0500 Subject: [PATCH 3/8] fix(web): retain synchronous fallback playback activation --- wakelock_plus/lib/assets/no_sleep.js | 62 +++++++++++++--------------- 1 file changed, 28 insertions(+), 34 deletions(-) diff --git a/wakelock_plus/lib/assets/no_sleep.js b/wakelock_plus/lib/assets/no_sleep.js index 23b8e36..361a650 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 = @@ -87,7 +60,7 @@ var NoSleep = (function () { this._addSourceToVideo(this.noSleepVideo, 'webm', webm) this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4) - this._videoOperation = Promise.resolve() + this._videoOperation = null this._videoPendingEnable = null this._desiredEnabled = false @@ -166,17 +139,27 @@ var NoSleep = (function () { if (this._videoPendingEnable != null) { return this._videoPendingEnable } - const operation = this._videoOperation.then(async () => { + const play = async () => { if (!this._desiredEnabled || !this.noSleepVideo.paused) { return } + // Preserve user activation by calling play synchronously when idle. await this.noSleepVideo.play() if (!this._desiredEnabled) { this.noSleepVideo.pause() } - }) + } + const operation = this._videoOperation == null + ? play() + : this._videoOperation.then(play) this._videoPendingEnable = operation - this._videoOperation = operation.catch(() => {}) + const queue = operation.catch(() => {}) + this._videoOperation = queue + void queue.then(() => { + if (this._videoOperation === queue) { + this._videoOperation = null + } + }) void operation.then( () => { if (this._videoPendingEnable === operation) { @@ -214,12 +197,21 @@ var NoSleep = (function () { } else { this._desiredEnabled = false this._videoPendingEnable = null - const operation = this._videoOperation.then(() => { + const pause = () => { if (!this._desiredEnabled) { 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 + } }) - this._videoOperation = operation.catch(() => {}) return operation } return Promise.resolve(); @@ -232,7 +224,9 @@ var NoSleep = (function () { await this._nativeOperation return this.nativeEnabled } else { - await this._videoOperation + if (this._videoOperation != null) { + await this._videoOperation + } return !this.noSleepVideo.paused } }, From 4219461c796a31428b64b3037e7033528926276e Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 12:26:13 +0500 Subject: [PATCH 4/8] test(web): verify synchronous fallback play preserves activation --- wakelock_plus/test/no_sleep_concurrency.test.cjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/wakelock_plus/test/no_sleep_concurrency.test.cjs b/wakelock_plus/test/no_sleep_concurrency.test.cjs index d0e3de6..9e6aa1e 100644 --- a/wakelock_plus/test/no_sleep_concurrency.test.cjs +++ b/wakelock_plus/test/no_sleep_concurrency.test.cjs @@ -230,3 +230,12 @@ test('fallback: enable-disable-enable ends playing', async () => { 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 +}) From c02c65932bc09edfab8d9efb2a7f73216e1af4a3 Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 12:30:55 +0500 Subject: [PATCH 5/8] ci(web): run JavaScript wake lock regression tests --- .github/workflows/checks.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3ad8283..cc99bee 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -450,6 +450,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: From be8e6555549dae1bf5501aa71557647338ecef4d Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 21:55:08 +0500 Subject: [PATCH 6/8] refactor(web): clarify requested wake-lock enable state --- wakelock_plus/lib/assets/no_sleep.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/wakelock_plus/lib/assets/no_sleep.js b/wakelock_plus/lib/assets/no_sleep.js index 361a650..d9b8ca5 100644 --- a/wakelock_plus/lib/assets/no_sleep.js +++ b/wakelock_plus/lib/assets/no_sleep.js @@ -43,7 +43,7 @@ var NoSleep = (function () { this._wakeLock = null this._nativeOperation = Promise.resolve() this._nativePendingEnable = null - this._desiredEnabled = false + this._requestEnabling = false var handleVisibilityChange = function handleVisibilityChange() { if (_this._wakeLock !== null && document.visibilityState === 'visible') { _this.enable() @@ -62,7 +62,7 @@ var NoSleep = (function () { this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4) this._videoOperation = null this._videoPendingEnable = null - this._desiredEnabled = false + this._requestEnabling = false this.noSleepVideo.addEventListener('loadedmetadata', function () { if (_this.noSleepVideo.duration <= 1) { @@ -94,13 +94,13 @@ var NoSleep = (function () { key: 'enable', value: async function enable() { if (nativeWakeLock) { - this._desiredEnabled = true + this._requestEnabling = true // Share in-flight requests and serialize state changes. if (this._nativePendingEnable != null) { return this._nativePendingEnable } const operation = this._nativeOperation.then(async () => { - if (!this._desiredEnabled || this._wakeLock != null) { + if (!this._requestEnabling || this._wakeLock != null) { return } const wakeLock = await navigator.wakeLock.request('screen') @@ -111,7 +111,7 @@ var NoSleep = (function () { this.nativeEnabled = false } }) - if (!this._desiredEnabled) { + if (!this._requestEnabling) { await wakeLock.release() return } @@ -135,17 +135,17 @@ var NoSleep = (function () { ) return operation } else { - this._desiredEnabled = true + this._requestEnabling = true if (this._videoPendingEnable != null) { return this._videoPendingEnable } const play = async () => { - if (!this._desiredEnabled || !this.noSleepVideo.paused) { + if (!this._requestEnabling || !this.noSleepVideo.paused) { return } // Preserve user activation by calling play synchronously when idle. await this.noSleepVideo.play() - if (!this._desiredEnabled) { + if (!this._requestEnabling) { this.noSleepVideo.pause() } } @@ -180,11 +180,11 @@ var NoSleep = (function () { key: 'disable', value: async function disable() { if (nativeWakeLock) { - this._desiredEnabled = false + 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._desiredEnabled || this._wakeLock == null) { + if (this._requestEnabling || this._wakeLock == null) { return } const wakeLock = this._wakeLock @@ -195,10 +195,10 @@ var NoSleep = (function () { this._nativeOperation = operation.catch(() => {}) return operation } else { - this._desiredEnabled = false + this._requestEnabling = false this._videoPendingEnable = null const pause = () => { - if (!this._desiredEnabled) { + if (!this._requestEnabling) { this.noSleepVideo.pause() } } From 896199ce9f8329aa75fb4c92d803fe73cbf97cec Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 21:58:36 +0500 Subject: [PATCH 7/8] ci(android): prepare beta-compatible Gradle toolchain from Flutter SDK defaults --- .../scripts/align_android_beta_toolchain.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 .github/scripts/align_android_beta_toolchain.py 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}") From 54b1acd9d2a563afcd5aa701d46001d9c9104fa9 Mon Sep 17 00:00:00 2001 From: Faizan Ullah Date: Thu, 29 Oct 2026 21:58:51 +0500 Subject: [PATCH 8/8] ci(android): use beta SDK Android defaults in beta matrix jobs --- .github/workflows/checks.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index cc99bee..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: |