A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(desktop): retire node:test suite for modules and updates
Hampus34cedb567ffa
diff --git a/fluxer_desktop/src/common/ModulePollPlan.test.mjs b/fluxer_desktop/src/common/ModulePollPlan.test.mjsdeleted file mode 100644index 4b38c3545..000000000--- a/fluxer_desktop/src/common/ModulePollPlan.test.mjs+++ /dev/null@@ -1,50 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';--const {MODULE_POLL_INTERVAL_MS, nextModulePollDelay, resolveModulePollPlan} = await import('./ModulePollPlan.ts');--describe('how often a client re-checks the module manifest', () => {- test('a dev override polls fast and exactly, with no jitter', () => {- const plan = resolveModulePollPlan(2000);- assert.deepEqual(plan, {intervalMs: 2000, jitterRatio: 0});- assert.equal(- nextModulePollDelay(plan, () => 0),- 2000,- );- assert.equal(- nextModulePollDelay(plan, () => 1),- 2000,- );- });-- test('a shipped build polls every 75 to 105 seconds', () => {- assert.equal(resolveModulePollPlan(null).intervalMs, MODULE_POLL_INTERVAL_MS);- assert.equal(MODULE_POLL_INTERVAL_MS, 90 * 1000);- const plan = resolveModulePollPlan(null);- assert.ok(nextModulePollDelay(plan, () => 0) >= 75 * 1000);- assert.ok(nextModulePollDelay(plan, () => 1) <= 105 * 1000);- });-- test('a shipped build spreads the poll so clients do not stampede the manifest', () => {- const plan = resolveModulePollPlan(null);- assert.ok(- plan.jitterRatio > 0,- 'a fixed interval aligns every client that booted together onto the same tick, so every release turns into a thundering herd against the manifest endpoint',- );- const low = nextModulePollDelay(plan, () => 0);- const mid = nextModulePollDelay(plan, () => 0.5);- const high = nextModulePollDelay(plan, () => 1);- assert.equal(mid, plan.intervalMs);- assert.equal(low, Math.round(plan.intervalMs * (1 - plan.jitterRatio)));- assert.equal(high, Math.round(plan.intervalMs * (1 + plan.jitterRatio)));- assert.ok(low < mid && mid < high);- });-- test('a delay is never zero or negative whatever the jitter draws', () => {- for (const draw of [0, 0.25, 0.5, 0.75, 1]) {- assert.ok(nextModulePollDelay({intervalMs: 1, jitterRatio: 5}, () => draw) >= 1);- }- });-});diff --git a/fluxer_desktop/src/common/ModuleSystem.test.mjs b/fluxer_desktop/src/common/ModuleSystem.test.mjsdeleted file mode 100644index 2796eef6d..000000000--- a/fluxer_desktop/src/common/ModuleSystem.test.mjs+++ /dev/null@@ -1,169 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import {pathToFileURL} from 'node:url';--const {- getOfflineRendererRoot,- hasOfflineRenderer,- readModuleSystemDisableRequest,- resolveModuleSystemLaunch,- MODULE_SYSTEM_BUILD_ENABLED,-} = await import('./ModuleSystem.ts');--function launch(module, argv, env, hasOfflineRenderer) {- return module.resolveModuleSystemLaunch({argv, env, hasOfflineRenderer});-}--async function importWithBuildDefine(value, cacheKey) {- const previous = process.env.FLUXER_MODULES;- process.env.FLUXER_MODULES = value;- try {- return await import(`./ModuleSystem.ts?${cacheKey}`);- } finally {- if (previous === undefined) {- delete process.env.FLUXER_MODULES;- } else {- process.env.FLUXER_MODULES = previous;- }- }-}--const modulesBuild = await importWithBuildDefine('1', 'build=on');--describe('the launch decision on a build with the module system flag off', () => {- test('the build define defaults off', () => {- assert.equal(MODULE_SYSTEM_BUILD_ENABLED, false);- });-- test('a flag-off build stays off with no runtime flag', () => {- assert.equal(readModuleSystemDisableRequest([], {}), false);- assert.deepEqual(resolveModuleSystemLaunch({argv: [], env: {}, hasOfflineRenderer: true}), {- kind: 'disabled-by-build',- });- });-- test('nothing at launch time can turn the module system on, only the build flag does', () => {- for (const value of ['1', 'true', 'YES', ' on ']) {- assert.equal(- resolveModuleSystemLaunch({argv: [], env: {FLUXER_MODULE_SYSTEM: value}, hasOfflineRenderer: true}).kind,- 'disabled-by-build',- value,- );- }- });-- test('a flag-off build with no offline renderer is left alone, the disable override was never in play', () => {- assert.deepEqual(- resolveModuleSystemLaunch({argv: ['--fluxer-no-module-system'], env: {}, hasOfflineRenderer: false}),- {kind: 'disabled-by-build'},- );- });-- test('an unrecognised environment value is not a disable request', () => {- assert.equal(readModuleSystemDisableRequest([], {FLUXER_MODULE_SYSTEM: 'maybe'}), false);- assert.equal(- resolveModuleSystemLaunch({argv: [], env: {FLUXER_MODULE_SYSTEM: 'maybe'}, hasOfflineRenderer: true}).kind,- 'disabled-by-build',- );- });-- test('an empty environment value is not a disable request', () => {- assert.equal(readModuleSystemDisableRequest([], {FLUXER_MODULE_SYSTEM: ' '}), false);- });-});--describe('the launch decision on a modules build, given an offline renderer no shipped modules build has', () => {- test('the build define carries the module system on its own', () => {- assert.equal(modulesBuild.MODULE_SYSTEM_BUILD_ENABLED, true);- assert.equal(launch(modulesBuild, [], {}, true).kind, 'enabled');- });-- test('the disable argument would turn the module system off', () => {- assert.equal(launch(modulesBuild, ['fluxer', '--fluxer-no-module-system'], {}, true).kind, 'disabled-by-request');- });-- test('the environment variable accepts the documented falsy spellings', () => {- for (const value of ['0', 'false', 'NO', ' off ']) {- assert.equal(launch(modulesBuild, [], {FLUXER_MODULE_SYSTEM: value}, true).kind, 'disabled-by-request', value);- }- for (const value of ['1', 'true', 'YES', ' on ']) {- assert.equal(launch(modulesBuild, [], {FLUXER_MODULE_SYSTEM: value}, true).kind, 'enabled', value);- }- });-});--describe('the disable override on a modules build, the only shape that ships', () => {- test('the disable argument is ignored instead of bricking the install', () => {- assert.deepEqual(launch(modulesBuild, ['fluxer', '--fluxer-no-module-system'], {}, false), {- kind: 'enabled-with-ignored-disable-request',- });- });-- test('the disable environment variable is ignored the same way', () => {- for (const value of ['0', 'false', 'NO', ' off ']) {- assert.deepEqual(- launch(modulesBuild, [], {FLUXER_MODULE_SYSTEM: value}, false),- {kind: 'enabled-with-ignored-disable-request'},- value,- );- }- });-- test('a boot without any disable override reports nothing ignored', () => {- assert.deepEqual(launch(modulesBuild, [], {}, false), {kind: 'enabled'});- });-});--const distRoots = [];--after(() => {- for (const root of distRoots) {- rmSync(root, {recursive: true, force: true});- }-});--function createDistTree() {- const root = mkdtempSync(path.join(os.tmpdir(), 'module-system-dist-'));- distRoots.push(root);- mkdirSync(path.join(root, 'main'), {recursive: true});- return root;-}--function mainModuleUrl(root) {- return pathToFileURL(path.join(root, 'main', 'index.js')).href;-}--describe('the offline renderer probe, which only an offline build can satisfy', () => {- test('resolves dist/renderer as a sibling of the main bundle, the way the preloads resolve', () => {- const root = createDistTree();- assert.equal(getOfflineRendererRoot(mainModuleUrl(root)), path.join(root, 'main', '..', 'renderer'));- });-- test('an asar with no renderer directory has no offline renderer', () => {- assert.equal(hasOfflineRenderer(mainModuleUrl(createDistTree())), false);- });-- test('an empty renderer directory has no offline renderer', () => {- const root = createDistTree();- mkdirSync(path.join(root, 'renderer', 'assets'), {recursive: true});- assert.equal(hasOfflineRenderer(mainModuleUrl(root)), false);- });-- test('a renderer directory carrying index.html is an offline renderer', () => {- const root = createDistTree();- mkdirSync(path.join(root, 'renderer'), {recursive: true});- writeFileSync(path.join(root, 'renderer', 'index.html'), '<html lang="en"></html>');- assert.equal(hasOfflineRenderer(mainModuleUrl(root)), true);- });-- test('a directory named index.html is not an offline renderer', () => {- const root = createDistTree();- mkdirSync(path.join(root, 'renderer', 'index.html'), {recursive: true});- assert.equal(hasOfflineRenderer(mainModuleUrl(root)), false);- });-});diff --git a/fluxer_desktop/src/main/AppImageUpdate.test.mjs b/fluxer_desktop/src/main/AppImageUpdate.test.mjsdeleted file mode 100644index 7f7b4bdb5..000000000--- a/fluxer_desktop/src/main/AppImageUpdate.test.mjs+++ /dev/null@@ -1,732 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createHash} from 'node:crypto';-import {- chmodSync,- existsSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- statSync,- symlinkSync,- writeFileSync,-} from 'node:fs';-import {createServer} from 'node:http';-import {createRequire} from 'node:module';-import {tmpdir} from 'node:os';-import {join} from 'node:path';-import {after, before, describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import vm from 'node:vm';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const sourcePath = fileURLToPath(new URL('./AppImageUpdate.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadAppImageUpdate(env = {}, overrides = {}, requireImpl = require) {- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- require: requireImpl,- console,- Buffer,- AbortController,- setTimeout,- clearTimeout,- fetch,- Error,- Number,- process: {...process, ...overrides, env: {...env}},- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--const INSTALLED_NAME = 'My Fluxer.AppImage';-const OLD_BYTES = Buffer.from('old-appimage-payload');-const NEW_BYTES = Buffer.alloc(400_000, 7);-const NEW_SHA256 = createHash('sha256').update(NEW_BYTES).digest('hex');--let server;-let baseUrl;-let requestCount = 0;--before(async () => {- server = createServer((request, response) => {- requestCount += 1;- if (request.url === '/appimage') {- response.writeHead(200, {'content-type': 'application/octet-stream', 'content-length': NEW_BYTES.length});- response.end(NEW_BYTES);- return;- }- if (request.url === '/corrupt') {- const corrupt = Buffer.from(NEW_BYTES);- corrupt[0] = corrupt[0] ^ 0xff;- response.writeHead(200, {'content-type': 'application/octet-stream', 'content-length': corrupt.length});- response.end(corrupt);- return;- }- response.writeHead(404);- response.end('missing');- });- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));- baseUrl = `http://127.0.0.1:${server.address().port}`;-});--after(async () => {- await new Promise((resolve) => server.close(resolve));-});--function createInstall() {- const root = mkdtempSync(join(tmpdir(), 'fluxer-appimage-test-'));- const applications = join(root, 'Applications');- mkdirSync(applications);- const installedPath = join(applications, INSTALLED_NAME);- writeFileSync(installedPath, OLD_BYTES, {mode: 0o755});- return {root, applications, installedPath};-}--function stagingLeftovers(directory) {- return readdirSync(directory).filter((entry) => entry.startsWith('.fluxer-update-'));-}--function assertUnavailable(result, reason) {- assert.equal(result.ok, false);- assert.equal(result.reason, reason);-}--function createAppDir(name) {- const root = mkdtempSync(join(tmpdir(), 'fluxer-appdir-test-'));- const dir = join(root, name);- mkdirSync(dir);- writeFileSync(join(dir, 'AppRun'), '#!/usr/bin/env bash\n', {mode: 0o755});- const binary = join(dir, 'fluxer-canary');- writeFileSync(binary, 'elf', {mode: 0o755});- return {dir, binary};-}--function stagingPrefixFor(installedPath) {- return `.fluxer-update-${createHash('sha256').update(installedPath).digest('hex').slice(0, 8)}-`;-}--describe('AppImageUpdate process provenance', () => {- test('accepts the process the AppImage runtime execed out of its own mount', () => {- const {isRunningFromAppImage} = loadAppImageUpdate({});- const mounted = createAppDir('.mount_My FluAKcenK');-- assert.equal(isRunningFromAppImage({APPDIR: mounted.dir}, mounted.binary), true);- assert.equal(isRunningFromAppImage({APPDIR: `${mounted.dir}/`}, mounted.binary), true);- assert.equal(isRunningFromAppImage({APPDIR: mounted.dir}, join(mounted.dir, 'usr', 'bin', 'fluxer-canary')), true);- });-- test('refuses an extracted AppDir, whose APPIMAGE belongs to whatever launched it', () => {- const {isRunningFromAppImage} = loadAppImageUpdate({});- const extracted = createAppDir('squashfs-root');- const launcher = createAppDir('.mount_My FluOjOANH');-- assert.equal(isRunningFromAppImage({}, extracted.binary), false);- assert.equal(- isRunningFromAppImage({APPDIR: launcher.dir}, extracted.binary),- false,- 'the generated AppRun assigns APPDIR without exporting it, so an APPDIR that reaches this process and does not contain it came from another AppImage',- );- });-- test('refuses an installed package that inherited APPIMAGE from the terminal it was started in', () => {- const {isRunningFromAppImage} = loadAppImageUpdate({});- const terminal = createAppDir('.mount_Alacritty7fJk2L');-- assert.equal(isRunningFromAppImage({}, '/opt/Fluxer/fluxer'), false);- assert.equal(isRunningFromAppImage({APPDIR: ''}, '/opt/Fluxer/fluxer'), false);- assert.equal(isRunningFromAppImage({APPDIR: terminal.dir}, '/opt/Fluxer/fluxer'), false);- });-- test('refuses a mount path that only prefixes this executable', () => {- const {isRunningFromAppImage} = loadAppImageUpdate({});- const mounted = createAppDir('.mount_My FluAKcenK');-- assert.equal(isRunningFromAppImage({APPDIR: mounted.dir}, `${mounted.dir}-other/fluxer-canary`), false);- });-- test('refuses an APPDIR the runtime cannot have mounted', () => {- const {isRunningFromAppImage} = loadAppImageUpdate({});- const installDir = mkdtempSync(join(tmpdir(), 'fluxer-opt-test-'));- const binary = join(installDir, 'fluxer-canary');- writeFileSync(binary, 'elf', {mode: 0o755});-- assert.equal(isRunningFromAppImage({APPDIR: installDir}, binary), false);- writeFileSync(join(installDir, 'AppRun'), '#!/usr/bin/env bash\n', {mode: 0o755});- assert.equal(isRunningFromAppImage({APPDIR: installDir}, binary), true);- });-});--describe('AppImageUpdate target resolution', () => {- test('falls back when APPIMAGE is unset', () => {- const {resolveAppImageTarget} = loadAppImageUpdate({});-- assertUnavailable(resolveAppImageTarget(), 'appimage-path-missing');- assertUnavailable(resolveAppImageTarget(''), 'appimage-path-missing');- assertUnavailable(resolveAppImageTarget(' '), 'appimage-path-missing');- });-- test('falls back when the AppImage moved since launch', () => {- const install = createInstall();- const {resolveAppImageTarget} = loadAppImageUpdate({APPIMAGE: join(install.applications, 'Gone.AppImage')});-- assertUnavailable(resolveAppImageTarget(), 'appimage-path-gone');- });-- test('falls back when the path is not a regular file', () => {- const install = createInstall();- const {resolveAppImageTarget} = loadAppImageUpdate({APPIMAGE: install.applications});-- assertUnavailable(resolveAppImageTarget(), 'appimage-path-not-a-file');- });-- test('falls back when the containing directory is not writable', {skip: process.getuid?.() === 0}, () => {- const install = createInstall();- chmodSync(install.applications, 0o500);- try {- const {resolveAppImageTarget} = loadAppImageUpdate({APPIMAGE: install.installedPath});-- assertUnavailable(resolveAppImageTarget(), 'directory-not-writable');- } finally {- chmodSync(install.applications, 0o755);- }- });-- test('resolves a writable AppImage to its own path', () => {- const install = createInstall();- const {resolveAppImageTarget} = loadAppImageUpdate({APPIMAGE: install.installedPath});-- const resolved = resolveAppImageTarget();- assert.equal(resolved.ok, true);- assert.equal(resolved.target.installedPath, install.installedPath);- assert.equal(resolved.target.directory, install.applications);- });-});--describe('AppImageUpdate in-place replacement', () => {- test('replaces the running AppImage and keeps the user filename', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- assert.equal(resolved.ok, true);-- const progress = [];- const staged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- onProgress: (sample) => progress.push(sample),- });-- assert.equal(staged.stagedPath, join(staged.stagingDirectory, INSTALLED_NAME));- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- assert.ok(progress.length > 0);- assert.equal(progress.at(-1).transferred, NEW_BYTES.length);- assert.equal(progress.at(-1).total, NEW_BYTES.length);-- appImageUpdate.applyStagedAppImageUpdate(resolved.target, staged);-- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- assert.equal(readFileSync(install.installedPath).equals(NEW_BYTES), true);- assert.equal(createHash('sha256').update(readFileSync(install.installedPath)).digest('hex'), NEW_SHA256);- assert.equal(statSync(install.installedPath).mode & 0o111, 0o111);- });-- test('stages inside the install directory so the rename cannot cross filesystems', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- const staged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- assert.equal(staged.stagingDirectory.startsWith(join(install.applications, '.fluxer-update-')), true);- appImageUpdate.discardStagedAppImageUpdate(staged);- assert.deepEqual(stagingLeftovers(install.applications), []);- });-- test('a download that stops sending data fails instead of hanging and leaves nothing staged', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const silent = new ReadableStream({- start(controller) {- controller.enqueue(NEW_BYTES.subarray(0, 4));- },- });-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: async () => new Response(silent, {headers: {'content-length': String(NEW_BYTES.length)}}),- target: resolved.target,- url: 'https://pkgs.invalid/appimage',- expectedSha256: NEW_SHA256,- stallMs: 30,- }),- /sent no data for 30 ms/,- );- assert.deepEqual(stagingLeftovers(install.applications), []);- });-- test('refuses to swap when the download does not match the published checksum', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/corrupt`,- expectedSha256: NEW_SHA256,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageChecksumError, true);- assert.match(error.message, /checksum mismatch/);- return true;- },- );-- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('refuses a checksum the release feed never published', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const before = requestCount;-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: '',- }),- /checksum is missing or malformed/,- );-- assert.equal(requestCount, before);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('cleans up and leaves the install untouched when the download fails', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/nothing-here`,- expectedSha256: NEW_SHA256,- }),- /Update download failed: 404/,- );-- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('finishes a short write instead of installing a truncated AppImage', async () => {- const install = createInstall();- let shortWrites = 0;- const shortWritingRequire = (specifier) => {- const real = require(specifier);- if (specifier !== 'node:fs/promises') {- return real;- }- return {- ...real,- open: async (...args) => {- const handle = await real.open(...args);- return {- close: () => handle.close(),- datasync: () => handle.datasync(),- write: (buffer, offset, length) => {- const capped = shortWrites === 0 ? Math.min(length, 4096) : length;- shortWrites += 1;- return handle.write(buffer, offset, capped);- },- };- },- };- };- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath}, {}, shortWritingRequire);- const resolved = appImageUpdate.resolveAppImageTarget();-- const staged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- assert.ok(shortWrites > 1, 'the write loop has to come back for the remainder of a short write');- assert.equal(statSync(staged.stagedPath).size, NEW_BYTES.length);- assert.equal(createHash('sha256').update(readFileSync(staged.stagedPath)).digest('hex'), NEW_SHA256);- appImageUpdate.discardStagedAppImageUpdate(staged);- });-- test('checksums the staged file from disk, not the stream it was read from', async () => {- const install = createInstall();- const droppingRequire = (specifier) => {- const real = require(specifier);- if (specifier !== 'node:fs/promises') {- return real;- }- return {- ...real,- open: async (...args) => {- const handle = await real.open(...args);- return {- close: () => handle.close(),- datasync: () => handle.datasync(),- write: async (buffer, offset, length) => {- const kept = Math.max(0, length - 1024);- if (kept > 0) {- await handle.write(buffer, offset, kept);- }- return {bytesWritten: length};- },- };- },- };- };- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath}, {}, droppingRequire);- const resolved = appImageUpdate.resolveAppImageTarget();-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageChecksumError, true);- return true;- },- );-- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('flushes the staged file to disk before it can be renamed over the install', async () => {- const install = createInstall();- let flushes = 0;- const countingRequire = (specifier) => {- const real = require(specifier);- if (specifier !== 'node:fs/promises') {- return real;- }- return {- ...real,- open: async (...args) => {- const handle = await real.open(...args);- return {- close: () => handle.close(),- datasync: () => {- flushes += 1;- return handle.datasync();- },- write: (buffer, offset, length) => handle.write(buffer, offset, length),- };- },- };- };- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath}, {}, countingRequire);- const resolved = appImageUpdate.resolveAppImageTarget();-- const staged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- assert.equal(flushes, 1);- appImageUpdate.discardStagedAppImageUpdate(staged);- });-- test('gives up when the staged bytes cannot be flushed to disk', async () => {- const install = createInstall();- const failingFlushRequire = (specifier) => {- const real = require(specifier);- if (specifier !== 'node:fs/promises') {- return real;- }- return {- ...real,- open: async (...args) => {- const handle = await real.open(...args);- return {- close: () => handle.close(),- datasync: async () => {- const error = new Error('ENOSPC: no space left on device, fsync');- error.code = 'ENOSPC';- throw error;- },- write: (buffer, offset, length) => handle.write(buffer, offset, length),- };- },- };- };- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath}, {}, failingFlushRequire);- const resolved = appImageUpdate.resolveAppImageTarget();-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageStagingError, true);- assert.equal(error.code, 'ENOSPC');- return true;- },- );-- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('retries a body that stops short of content-length instead of calling it a bad build', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const truncatingFetch = async () => {- let sent = false;- return {- ok: true,- status: 200,- headers: {get: (name) => (name === 'content-length' ? String(NEW_BYTES.length) : null)},- body: {- cancel: async () => {},- getReader: () => ({- cancel: async () => {},- read: async () => {- if (sent) {- return {done: true, value: undefined};- }- sent = true;- return {done: false, value: NEW_BYTES.subarray(0, 1024)};- },- }),- },- };- };-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- fetchImpl: truncatingFetch,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageChecksumError, false);- assert.equal(error instanceof appImageUpdate.AppImageStagingError, false);- assert.match(error.message, new RegExp(`ended after 1024 of ${NEW_BYTES.length} bytes`));- return true;- },- );-- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('refuses to stage when the install filesystem cannot hold the download', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const hugeFetch = async () => ({- ok: true,- status: 200,- headers: {get: (name) => (name === 'content-length' ? String(Number.MAX_SAFE_INTEGER) : null)},- body: {- cancel: async () => {},- getReader: () => ({cancel: async () => {}, read: async () => ({done: true, value: undefined})}),- },- });-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- fetchImpl: hugeFetch,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageStagingError, true);- assert.equal(error.code, 'ENOSPC');- return true;- },- );-- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('marks a local write failure as non-retryable', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const failingFetch = async () => ({- ok: true,- status: 200,- headers: {get: () => null},- body: {- cancel: async () => {},- getReader: () => ({- cancel: async () => {},- read: async () => {- const error = new Error('ENOSPC: no space left on device, write');- error.code = 'ENOSPC';- throw error;- },- }),- },- });-- await assert.rejects(- appImageUpdate.stageAppImageUpdate({- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- fetchImpl: failingFetch,- }),- (error) => {- assert.equal(error instanceof appImageUpdate.AppImageStagingError, true);- assert.equal(error.code, 'ENOSPC');- return true;- },- );-- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-- test('refuses to install when the AppImage moved between download and install', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const staged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- const relocated = {installedPath: join(install.applications, 'Moved.AppImage'), directory: install.applications};- assert.throws(- () => appImageUpdate.applyStagedAppImageUpdate(relocated, staged),- /cannot be replaced in place: appimage-path-gone/,- );-- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- assert.deepEqual(stagingLeftovers(install.applications), []);- });-});--describe('AppImageUpdate abandoned staging cleanup', () => {- test('reclaims staged updates left behind by a process that never quit cleanly', async () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const abandoned = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: resolved.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- assert.equal(stagingLeftovers(install.applications).length, 1);-- const reclaimed = appImageUpdate.sweepAbandonedAppImageUpdates(resolved.target);-- assert.deepEqual([...reclaimed], [abandoned.stagingDirectory]);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- assert.equal(readFileSync(install.installedPath).equals(OLD_BYTES), true);- });-- test('leaves a staged update belonging to another AppImage in the same directory alone', async () => {- const install = createInstall();- const siblingPath = join(install.applications, 'Fluxer Canary.AppImage');- writeFileSync(siblingPath, OLD_BYTES, {mode: 0o755});- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();- const sibling = appImageUpdate.resolveAppImageTarget(siblingPath);- const siblingStaged = await appImageUpdate.stageAppImageUpdate({- fetchImpl: fetch,- target: sibling.target,- url: `${baseUrl}/appimage`,- expectedSha256: NEW_SHA256,- });-- const reclaimed = appImageUpdate.sweepAbandonedAppImageUpdates(resolved.target);-- assert.deepEqual([...reclaimed], []);- assert.equal(existsSync(siblingStaged.stagedPath), true);- appImageUpdate.discardStagedAppImageUpdate(siblingStaged);- assert.deepEqual(stagingLeftovers(install.applications), []);- });-- test('unlinks a staging-named symlink instead of following it out of the install directory', () => {- const install = createInstall();- const outside = mkdtempSync(join(tmpdir(), 'fluxer-outside-test-'));- writeFileSync(join(outside, 'keep-me'), 'not ours to delete');- const planted = join(install.applications, `${stagingPrefixFor(install.installedPath)}link`);- symlinkSync(outside, planted);- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- const reclaimed = appImageUpdate.sweepAbandonedAppImageUpdates(resolved.target);-- assert.deepEqual([...reclaimed], [planted]);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- assert.deepEqual(readdirSync(outside), ['keep-me']);- });-- test('leaves everything that is not one of this AppImage staging directories alone', () => {- const install = createInstall();- const neighbours = ['Fluxer Canary.AppImage', '.fluxer-update-notes.txt', '.fluxer-update-'];- for (const name of neighbours) {- writeFileSync(join(install.applications, name), 'keep');- }- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- assert.deepEqual([...appImageUpdate.sweepAbandonedAppImageUpdates(resolved.target)], []);- assert.deepEqual(readdirSync(install.applications).sort(), [...neighbours, INSTALLED_NAME].sort());- });-- test('reports nothing when the install directory holds no staged update', () => {- const install = createInstall();- const appImageUpdate = loadAppImageUpdate({APPIMAGE: install.installedPath});- const resolved = appImageUpdate.resolveAppImageTarget();-- assert.deepEqual([...appImageUpdate.sweepAbandonedAppImageUpdates(resolved.target)], []);- assert.deepEqual(readdirSync(install.applications), [INSTALLED_NAME]);- });-});diff --git a/fluxer_desktop/src/main/DesktopUpdateGate.test.mjs b/fluxer_desktop/src/main/DesktopUpdateGate.test.mjsdeleted file mode 100644index c36a3b943..000000000--- a/fluxer_desktop/src/main/DesktopUpdateGate.test.mjs+++ /dev/null@@ -1,133 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {- armDesktopUpdate,- checkDesktopUpdateNow,- getDesktopUpdateState,- observeDesktopUpdateState,- publishDesktopUpdateCheck,- startDesktopUpdate,-} = await import('@electron/main/DesktopUpdateGate');--function deferred() {- let resolve;- const promise = new Promise((resolvePromise) => {- resolve = resolvePromise;- });- return {promise, resolve};-}--describe('DesktopUpdateGate', () => {- test('nothing is available and nothing starts before the bootstrap arms the gate', async () => {- assert.deepEqual(getDesktopUpdateState(), {available: false, updating: false, replacesShell: false});- assert.deepEqual(await checkDesktopUpdateNow(), {available: false, updating: false, replacesShell: false});- assert.equal(startDesktopUpdate(), false);- });-- test('a check publishes the update and one click runs it exactly once', async () => {- const states = [];- const stop = observeDesktopUpdateState((state) => states.push(state));- const running = deferred();- let starts = 0;- armDesktopUpdate({- check: async () => ({shellNewer: false, modulesChanged: true}),- start: async () => {- starts += 1;- await running.promise;- publishDesktopUpdateCheck({shellNewer: false, modulesChanged: false});- },- });-- assert.deepEqual(await checkDesktopUpdateNow(), {available: true, updating: false, replacesShell: false});- assert.equal(startDesktopUpdate(), true);- assert.equal(startDesktopUpdate(), false, 'a second click while the update runs is a no-op');- assert.deepEqual(- getDesktopUpdateState(),- {available: false, updating: true, replacesShell: false},- 'the affordance hides the moment it is clicked',- );- assert.deepEqual(- await checkDesktopUpdateNow(),- {available: false, updating: true, replacesShell: false},- 'a poll during the update changes nothing',- );-- running.resolve();- await new Promise((resolve) => setImmediate(resolve));-- assert.equal(starts, 1);- assert.deepEqual(getDesktopUpdateState(), {available: false, updating: false, replacesShell: false});- assert.deepEqual(states, [- {available: true, updating: false, replacesShell: false},- {available: false, updating: true, replacesShell: false},- {available: false, updating: false, replacesShell: false},- ]);- stop();- });-- test('a background poll joins a check already running instead of starting another', async () => {- const pending = deferred();- const calls = [];- armDesktopUpdate({- check: async (manual) => {- calls.push(manual);- await pending.promise;- return {shellNewer: false, modulesChanged: false};- },- start: async () => {},- });-- const first = checkDesktopUpdateNow();- const second = checkDesktopUpdateNow();- pending.resolve();- await Promise.all([first, second]);-- assert.deepEqual(calls, [false]);- });-- test('a manual check never settles for the answer of a background poll that was already running', async () => {- const pending = deferred();- const calls = [];- armDesktopUpdate({- check: async (manual) => {- calls.push(manual);- if (!manual) {- await pending.promise;- return {shellNewer: false, modulesChanged: false};- }- return {shellNewer: true, modulesChanged: false};- },- start: async () => {},- });-- const background = checkDesktopUpdateNow();- const manual = checkDesktopUpdateNow({manual: true});- pending.resolve();- await background;-- assert.deepEqual(await manual, {available: true, updating: false, replacesShell: true});- assert.deepEqual(calls, [false, true]);- });-- test('a shell update that could not finish stays available for the next click', async () => {- armDesktopUpdate({- check: async () => ({shellNewer: true, modulesChanged: false}),- start: async () => {- publishDesktopUpdateCheck({shellNewer: true, modulesChanged: false});- },- });- await checkDesktopUpdateNow();-- assert.equal(startDesktopUpdate(), true);- await new Promise((resolve) => setImmediate(resolve));-- assert.deepEqual(getDesktopUpdateState(), {available: true, updating: false, replacesShell: true});- assert.equal(startDesktopUpdate(), true);- });-});diff --git a/fluxer_desktop/src/main/DesktopUpdatePoll.test.mjs b/fluxer_desktop/src/main/DesktopUpdatePoll.test.mjsdeleted file mode 100644index 9baa1d36a..000000000--- a/fluxer_desktop/src/main/DesktopUpdatePoll.test.mjs+++ /dev/null@@ -1,156 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {DesktopUpdatePoll} = await import('@electron/main/DesktopUpdatePoll');--const PLAN = Object.freeze({intervalMs: 90_000, jitterRatio: 0.15});--function settle() {- return new Promise((resolve) => setImmediate(resolve));-}--function harness(results) {- const timers = [];- const logs = [];- let checks = 0;- let release = null;- const poll = new DesktopUpdatePoll({- plan: PLAN,- random: () => 0.5,- check: () => {- const result = results[Math.min(checks, results.length - 1)];- checks += 1;- if (result === 'hold') {- return new Promise((resolve) => {- release = () => resolve({available: false, updating: false});- });- }- return result instanceof Error ? Promise.reject(result) : Promise.resolve(result);- },- logger: {- info: (message) => logs.push(['info', message]),- warn: (message) => logs.push(['warn', message]),- },- setTimer: (callback, delayMs) => {- const timer = {callback, delayMs, cleared: false};- timers.push(timer);- return timer;- },- clearTimer: (timer) => {- timer.cleared = true;- },- });- const fire = async () => {- const timer = timers.findLast((candidate) => !candidate.cleared);- timer.cleared = true;- timer.callback();- await settle();- };- return {- poll,- timers,- logs,- fire,- checks: () => checks,- release: async () => {- release();- await settle();- },- };-}--const NOTHING = Object.freeze({available: false, updating: false});-const AVAILABLE = Object.freeze({available: true, updating: false});--describe('DesktopUpdatePoll', () => {- test('a healthy poll checks about every ninety seconds', async () => {- const {poll, timers, fire, checks} = harness([NOTHING]);-- poll.start(false);- assert.equal(checks(), 0);- assert.equal(timers.at(-1).delayMs, 90_000);-- await fire();- await fire();-- assert.equal(checks(), 2);- assert.equal(timers.at(-1).delayMs, 90_000);- });-- test('a failing poll backs off, warns once, and says so when it recovers', async () => {- const offline = new Error('offline');- const {poll, timers, logs, fire} = harness([offline, offline, offline, NOTHING, NOTHING]);-- poll.start(true);- await settle();- const delays = [timers.at(-1).delayMs];- await fire();- delays.push(timers.at(-1).delayMs);- await fire();- delays.push(timers.at(-1).delayMs);- await fire();- delays.push(timers.at(-1).delayMs);- await fire();-- assert.deepEqual(delays, [135_000, 270_000, 540_000, 90_000]);- assert.deepEqual(- logs.filter(([level]) => level === 'warn').map(([, message]) => message),- ['The desktop update poll failed, backing off until it recovers'],- );- assert.equal(logs.filter(([, message]) => message === 'The desktop update poll recovered').length, 1);- });-- test('the back off never waits longer than fifteen minutes', async () => {- const {poll, timers, fire} = harness([new Error('offline')]);-- poll.start(true);- await settle();- for (let attempt = 0; attempt < 12; attempt += 1) {- await fire();- }-- assert.ok(timers.at(-1).delayMs <= 15 * 60 * 1000);- });-- test('a reopened window or a reload checks at once and restarts the interval', async () => {- const {poll, timers, checks} = harness([NOTHING]);- poll.start(false);- const pending = timers.at(-1);-- poll.wake();- await settle();-- assert.equal(checks(), 1);- assert.equal(pending.cleared, true);- assert.equal(timers.filter((timer) => !timer.cleared).length, 1);- });-- test('a wake while a check runs never starts a second one', async () => {- const {poll, checks, release, timers} = harness(['hold', NOTHING]);- poll.start(true);-- poll.wake();- poll.wake();- assert.equal(checks(), 1);-- await release();- assert.equal(timers.filter((timer) => !timer.cleared).length, 1);- });-- test('an update that stays available is logged once, not on every tick', async () => {- const {poll, logs, fire} = harness([AVAILABLE]);- poll.start(true);- await settle();- await fire();- await fire();-- assert.equal(- logs.filter(([, message]) => message === 'A desktop update is available, waiting for the user to start it')- .length,- 1,- );- });-});diff --git a/fluxer_desktop/src/main/DesktopUpdatePrompt.test.mjs b/fluxer_desktop/src/main/DesktopUpdatePrompt.test.mjsdeleted file mode 100644index 6bff99c69..000000000--- a/fluxer_desktop/src/main/DesktopUpdatePrompt.test.mjs+++ /dev/null@@ -1,137 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';-import vm from 'node:vm';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const sourcePath = fileURLToPath(new URL('./DesktopUpdatePrompt.ts', import.meta.url));-const transformedSource = esbuild.transformSync(readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--const DOWNLOAD_PAGE_URL = 'https://fluxer.app/download';-const FLATPAK_APP_ID = 'app.fluxer.FluxerDesktop';-const NEWER_SHELL = '2026.1013.15209';--function loadPrompt({plan, flatpakAppId = null, response = 0}) {- const dialogs = [];- const opened = [];- const logger = {info: () => {}, warn: () => {}, error: () => {}};- function requireStub(specifier) {- switch (specifier) {- case '@electron/common/DesktopIdentity':- return {DESKTOP_APP_NAME: 'Fluxer'};- case '@electron/common/ErrorMessage':- return {errorMessage: (error) => String(error)};- case '@electron/common/Logger':- return {createChildLogger: () => logger};- case '@electron/main/DesktopUpdateGate':- return {- checkDesktopUpdateNow: async () => ({available: false}),- desktopUpdateReplacesShell: () => false,- getDesktopUpdateState: () => ({available: false}),- startDesktopUpdate: () => false,- };- case '@electron/main/LinuxSandbox':- return {getFlatpakAppId: () => flatpakAppId, isFlatpakRuntime: () => flatpakAppId != null};- case '@electron/main/MainI18n':- return {t: (key) => key};- case '@electron/main/OpenExternal':- return {- openExternalDeduped: async (url) => {- opened.push(url);- },- };- case '@electron/main/ShellUpdateCapability':- return {- resolveShellUpdatePlan: () => plan,- ShellUpdateCapability: {- SELF_UPDATE: 'self-update',- MANUAL_DOWNLOAD: 'manual-download',- MANAGED_PACKAGE: 'managed-package',- },- };- case '@electron/main/Updater':- return {findNewerManualShell: async () => ({version: NEWER_SHELL})};- case '@electron/main/UpdaterDownloads':- return {DOWNLOAD_PAGE_URL};- case 'electron':- return {- app: {getVersion: () => '2026.1006.171735'},- BrowserWindow: {getFocusedWindow: () => null},- dialog: {- showMessageBox: async (options) => {- dialogs.push(options);- return {response};- },- },- };- default:- throw new Error(`Unexpected import: ${specifier}`);- }- }- const module = {exports: {}};- vm.runInContext(- transformedSource,- vm.createContext({require: requireStub, module, exports: module.exports, console}),- {filename: sourcePath},- );- return {prompt: module.exports, dialogs, opened};-}--describe('the native update prompt for a shell that cannot update itself', () => {- test('a Flatpak with a newer shell offers the software center', async () => {- const {prompt, dialogs, opened} = loadPrompt({- plan: {capability: 'managed-package'},- flatpakAppId: FLATPAK_APP_ID,- });-- await prompt.checkForUpdatesFromShell();-- assert.equal(dialogs.length, 1);- assert.equal(dialogs[0].message, 'desktop.update.manualMessage');- assert.equal(dialogs[0].detail, 'desktop.update.flatpakDetail');- assert.deepEqual([...dialogs[0].buttons], ['desktop.update.openSoftwareCenter', 'desktop.update.later']);- assert.deepEqual(opened, [`appstream://${FLATPAK_APP_ID}`]);- });-- test('a deb install with a newer shell offers the download page', async () => {- const {prompt, dialogs, opened} = loadPrompt({plan: {capability: 'managed-package'}});-- await prompt.checkForUpdatesFromShell();-- assert.equal(dialogs[0].detail, 'desktop.update.managedDetail');- assert.deepEqual([...dialogs[0].buttons], ['desktop.update.download', 'desktop.update.later']);- assert.deepEqual(opened, [DOWNLOAD_PAGE_URL]);- });-- test('a portable build keeps the plain download wording', async () => {- const {prompt, dialogs, opened} = loadPrompt({plan: {capability: 'manual-download', reason: 'platform'}});-- await prompt.checkForUpdatesFromShell();-- assert.equal(dialogs[0].detail, 'desktop.update.manualDetail');- assert.deepEqual(opened, [DOWNLOAD_PAGE_URL]);- });-- test('choosing later opens nothing', async () => {- const {prompt, opened} = loadPrompt({- plan: {capability: 'managed-package'},- flatpakAppId: FLATPAK_APP_ID,- response: 1,- });-- await prompt.checkForUpdatesFromShell();-- assert.deepEqual(opened, []);- });-});diff --git a/fluxer_desktop/src/main/DesktopUpdateRun.test.mjs b/fluxer_desktop/src/main/DesktopUpdateRun.test.mjsdeleted file mode 100644index defa3d52a..000000000--- a/fluxer_desktop/src/main/DesktopUpdateRun.test.mjs+++ /dev/null@@ -1,299 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopUpdateRun} = await import('@electron/main/DesktopUpdateRun');--const LAUNCH_ATTEMPT = Object.freeze({committed: {fluxer_renderer: 'b'.repeat(64)}});--function harness({- probes = [{shellLatestVersion: '2026.1008.2', shellNewer: false, modulesChanged: true}],- canSelfUpdateShell = true,- shellResults = [],- installFails = false,- settled = true,- now = () => 0,-} = {}) {- const steps = [];- const published = [];- const failures = [];- let probeIndex = 0;- let shellIndex = 0;- const quiet = () => undefined;- const run = new DesktopUpdateRun({- probe: async () => {- const next = probes[Math.min(probeIndex, probes.length - 1)];- probeIndex += 1;- steps.push('probe');- if (next instanceof Error) throw next;- return next;- },- canSelfUpdateShell,- runShellSelfUpdate: async () => {- steps.push('shell-update');- const result = shellResults[Math.min(shellIndex, shellResults.length - 1)];- shellIndex += 1;- return result;- },- installModules: async () => {- steps.push('install');- if (installFails) throw new Error('disk full');- return LAUNCH_ATTEMPT;- },- takeover: {- begin: async () => {- steps.push('takeover');- },- restore: () => {- steps.push('restore');- },- closeApp: async () => {- steps.push('close');- },- reopen: (launchAttempt) => {- steps.push(launchAttempt == null ? 'reopen' : 'reopen-updated');- },- reloadInPlace: async () => {- steps.push('reload-in-place');- },- },- publish: (check) => {- published.push(check);- },- openDownloadsPage: async () => {- steps.push('downloads-page');- },- reportFailure: (failure) => {- failures.push(failure);- },- logger: {info: quiet, warn: quiet, error: quiet},- now,- });- if (settled) run.markLaunchSettled();- return {run, steps, published, failures};-}--describe('DesktopUpdateRun', () => {- test('the background check only looks, it never downloads, closes or installs anything', async () => {- const {run, steps, published} = harness();-- assert.deepEqual(await run.check(), {shellNewer: false, modulesChanged: true});-- assert.deepEqual(steps, ['probe']);- assert.deepEqual(published, []);- });-- test('a click takes the window over, checks, and only then closes the app and installs', async () => {- const {run, steps, published} = harness();-- await run.start();-- assert.deepEqual(steps, ['probe', 'takeover', 'close', 'install', 'reopen-updated']);- assert.deepEqual(published, [{shellNewer: false, modulesChanged: false}]);- });-- test('a click while offline gives the same windows back instead of tearing the app down', async () => {- const {run, steps, published} = harness({probes: [new Error('offline')]});-- await run.start();-- assert.deepEqual(steps, ['probe', 'takeover', 'restore']);- assert.deepEqual(published, [], 'the icon stays so the next click can try again');- });-- test('a click after the update was withdrawn gives the windows back and hides the icon', async () => {- const {run, steps, published} = harness({- probes: [{shellLatestVersion: '2026.1008.1', shellNewer: false, modulesChanged: false}],- });-- await run.start();-- assert.deepEqual(steps, ['probe', 'takeover', 'restore']);- assert.deepEqual(published, [{shellNewer: false, modulesChanged: false}]);- });-- test('a shell update runs before any module download, and modules install only when the shell did not restart', async () => {- const {run, steps} = harness({- probes: [{shellLatestVersion: '2026.1008.2', shellNewer: true, modulesChanged: true}],- shellResults: [{reason: 'install-failed', detail: 'nope'}],- });-- await run.start();-- assert.deepEqual(steps, ['probe', 'takeover', 'close', 'shell-update', 'install', 'reopen-updated']);- });-- test('a shell feed that lags the manifest stops offering the shell until the manifest moves on', async () => {- const lagging = {shellLatestVersion: '2026.1008.2', shellNewer: true, modulesChanged: false};- const {run, steps, published} = harness({- probes: [lagging, lagging, {...lagging, shellLatestVersion: '2026.1008.3'}],- shellResults: [{reason: 'no-update', detail: null}],- });-- await run.start();- assert.deepEqual(published, [{shellNewer: false, modulesChanged: false}]);-- assert.deepEqual(- await run.check(),- {shellNewer: false, modulesChanged: false},- 'the poll no longer shows the icon',- );- assert.deepEqual(await run.check(), {shellNewer: true, modulesChanged: false}, 'a newer manifest shell does');- assert.deepEqual(steps, ['probe', 'takeover', 'close', 'shell-update', 'reopen', 'probe', 'probe']);- });-- test('a manual check offers the shell again even after the platform feed said it had nothing', async () => {- const lagging = {shellLatestVersion: '2026.1012.154032', shellNewer: true, modulesChanged: false};- const {run} = harness({probes: [lagging], shellResults: [{reason: 'no-update', detail: null}]});- await run.start();- assert.deepEqual(await run.check(), {shellNewer: false, modulesChanged: false});-- assert.deepEqual(- await run.check({manual: true}),- {shellNewer: true, modulesChanged: false},- 'one stale answer from the platform feed must not make Check for updates say up to date for the rest of the session',- );- assert.deepEqual(await run.check(), {shellNewer: true, modulesChanged: false});- });-- test('the background check offers a lagging shell again once the platform feed had time to catch up', async () => {- let clock = 0;- const lagging = {shellLatestVersion: '2026.1012.154032', shellNewer: true, modulesChanged: false};- const {run} = harness({- probes: [lagging],- shellResults: [{reason: 'no-update', detail: null}],- now: () => clock,- });- await run.start();-- clock = 9 * 60_000;- assert.deepEqual(await run.check(), {shellNewer: false, modulesChanged: false});- clock = 10 * 60_000;- assert.deepEqual(await run.check(), {shellNewer: true, modulesChanged: false});- });-- test('a shell update that failed on the network is retried by the next click', async () => {- const shell = {shellLatestVersion: '2026.1008.2', shellNewer: true, modulesChanged: false};- const {run, steps, published} = harness({- probes: [shell],- shellResults: [- {reason: 'timed-out', detail: 'slow link'},- {reason: 'check-failed', detail: 'offline'},- ],- });-- await run.start();- await run.start();-- assert.deepEqual(published, [- {shellNewer: true, modulesChanged: false},- {shellNewer: true, modulesChanged: false},- ]);- assert.equal(steps.filter((step) => step === 'shell-update').length, 2);- assert.equal(steps.includes('downloads-page'), false);- });-- test('only a shell update that failed to install falls back to the downloads page', async () => {- const shell = {shellLatestVersion: '2026.1008.2', shellNewer: true, modulesChanged: false};- const {run, steps} = harness({probes: [shell], shellResults: [{reason: 'install-failed', detail: 'apply'}]});-- await run.start();- steps.length = 0;- await run.start();-- assert.deepEqual(steps, ['downloads-page']);- });-- test('a shell that cannot update itself never offers the shell part', async () => {- const {run} = harness({- canSelfUpdateShell: false,- probes: [{shellLatestVersion: '2026.1008.2', shellNewer: true, modulesChanged: false}],- });-- assert.deepEqual(await run.check(), {shellNewer: false, modulesChanged: false});- });-- test('a failed module install reopens the app on the installed set and keeps the icon', async () => {- const {run, steps, published} = harness({installFails: true});-- await run.start();-- assert.deepEqual(steps, ['probe', 'takeover', 'close', 'install', 'reopen']);- assert.deepEqual(published, [{shellNewer: false, modulesChanged: true}]);- });-- test('a click before the renderer confirmed its launch does nothing', async () => {- const {run, steps} = harness({settled: false});-- await run.start();-- assert.deepEqual(steps, []);- });-});--describe('DesktopUpdateRun installing a renderer only update in place', () => {- const MODULES_ONLY = {shellLatestVersion: '2026.1008.2', shellNewer: false, modulesChanged: true};- const SHELL_TOO = {shellLatestVersion: '2026.1008.3', shellNewer: true, modulesChanged: true};-- test('a click after the background check found only modules never shows the splash or closes a window', async () => {- const {run, steps, published, failures} = harness({probes: [MODULES_ONLY]});- await run.check();-- await run.start();-- assert.deepEqual(steps, ['probe', 'probe', 'install', 'reload-in-place']);- assert.deepEqual(published, [{shellNewer: false, modulesChanged: false}]);- assert.deepEqual(failures, []);- });-- test('a shell that turned newer since the background check still updates behind the splash', async () => {- const {run, steps} = harness({- probes: [MODULES_ONLY, SHELL_TOO],- shellResults: [{reason: 'no-update', detail: null}],- });- await run.check();-- await run.start();-- assert.deepEqual(steps, ['probe', 'probe', 'takeover', 'close', 'shell-update', 'install', 'reopen-updated']);- });-- test('a download that fails leaves the running app alone and says so', async () => {- const {run, steps, published, failures} = harness({probes: [MODULES_ONLY], installFails: true});- await run.check();-- await run.start();-- assert.deepEqual(steps, ['probe', 'probe', 'install']);- assert.deepEqual(published, [{shellNewer: false, modulesChanged: true}]);- assert.deepEqual(failures, [{reason: 'download-failed', detail: 'disk full'}]);- });-- test('a click while offline changes nothing on screen', async () => {- const {run, steps, failures} = harness({probes: [MODULES_ONLY, new Error('offline')]});- await run.check();-- await run.start();-- assert.deepEqual(steps, ['probe', 'probe']);- assert.deepEqual(failures, [{reason: 'check-failed', detail: 'offline'}]);- });-- test('a check works from the first window, a click only after the renderer confirmed its launch', async () => {- const {run, steps} = harness({probes: [MODULES_ONLY], settled: false});-- assert.deepEqual(await run.check(), {shellNewer: false, modulesChanged: true});- await run.start();-- assert.deepEqual(steps, ['probe']);-- run.markLaunchSettled();- await run.start();-- assert.deepEqual(steps, ['probe', 'probe', 'install', 'reload-in-place']);- });-});diff --git a/fluxer_desktop/src/main/ModuleManifest.test.mjs b/fluxer_desktop/src/main/ModuleManifest.test.mjsdeleted file mode 100644index 1f60f82ad..000000000--- a/fluxer_desktop/src/main/ModuleManifest.test.mjs+++ /dev/null@@ -1,115 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {registerHooks} from 'node:module';-import {describe, test} from 'node:test';--const DESKTOP_SRC = new URL('../', import.meta.url);-const PACKAGES = new URL('../../../packages/', import.meta.url);--registerHooks({- resolve(specifier, context, nextResolve) {- if (specifier.startsWith('@electron/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@electron/'.length)}.ts`, DESKTOP_SRC).href};- }- if (specifier.startsWith('@fluxer/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@fluxer/'.length)}.ts`, PACKAGES).href};- }- return nextResolve(specifier, context);- },-});--const {parseModuleUpdateManifest} = await import('./ModuleManifest.ts');--const SHELL_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const PLATFORM = 'darwin';-const ARCH = 'arm64';-const RENDERER_SHA = 'a'.repeat(64);-const EXPECTED_TARGET = {releaseChannel: RELEASE_CHANNEL, platform: PLATFORM, arch: ARCH};--function manifestBytes(overrides = {}) {- return Buffer.from(- JSON.stringify({- manifest_version: 1,- release_channel: RELEASE_CHANNEL,- platform: PLATFORM,- arch: ARCH,- build_version: SHELL_VERSION,- pub_date: '2026-08-23T00:00:00.000Z',- metadata_version: 4,- shell: {latest_version: SHELL_VERSION, minimum_version: SHELL_VERSION},- modules: {- fluxer_renderer: {sha256: RENDERER_SHA, bytes: 1024, url: `https://api.invalid/dl/desktop/${RENDERER_SHA}.br`},- },- required_modules: ['fluxer_renderer'],- ...overrides,- }),- 'utf8',- );-}--describe('parseModuleUpdateManifest', () => {- test('accepts a manifest cut for this shell channel, platform and arch', () => {- const manifest = parseModuleUpdateManifest(manifestBytes(), EXPECTED_TARGET);-- assert.equal(manifest.releaseChannel, RELEASE_CHANNEL);- assert.equal(manifest.platform, PLATFORM);- assert.equal(manifest.arch, ARCH);- assert.equal(manifest.metadataVersion, 4);- assert.deepEqual(manifest.requiredModules, ['fluxer_renderer']);- assert.equal(manifest.modules.fluxer_renderer.sha256, RENDERER_SHA);- });-- test('refuses a manifest cut for another channel, another platform or another arch', () => {- for (const overrides of [{release_channel: 'stable'}, {platform: 'win32'}, {arch: 'x64'}]) {- assert.throws(() => parseModuleUpdateManifest(manifestBytes(overrides), EXPECTED_TARGET), {- name: 'ModuleManifestMalformedError',- message: /manifest targets/u,- });- }- });-- test('refuses required_modules naming an Object.prototype property', () => {- assert.throws(- () =>- parseModuleUpdateManifest(manifestBytes({required_modules: ['fluxer_renderer', 'toString']}), EXPECTED_TARGET),- {- name: 'ModuleManifestMalformedError',- message: /required_modules names an undeclared module: toString/u,- },- );- });-- test('linux_security_minimum is ignored, even one shipped shells would enforce', () => {- const bytes = manifestBytes({- platform: 'linux',- shell: {latest_version: '2026.900.1', minimum_version: '0.0.0'},- linux_security_minimum: {version: '2026.900.1', required_modules: ['constructor']},- });-- const manifest = parseModuleUpdateManifest(bytes, {...EXPECTED_TARGET, platform: 'linux'});-- assert.equal(Object.hasOwn(manifest, 'linuxSecurityMinimum'), false);- assert.equal(manifest.shell.minimumVersion.source, '0.0.0');- });-- test('a manifest carrying shell_compatibility parses', () => {- const bytes = manifestBytes({- shell_compatibility: {- minimum_shell_version: '0.0.0',- source_sha: 'b'.repeat(40),- previous_source_sha: 'c'.repeat(40),- floor_source_sha: null,- decision: 'compatible',- contract_base_sha: 'c'.repeat(40),- contract_changes: ['fluxer_desktop/src/preload/index.ts'],- },- });-- const manifest = parseModuleUpdateManifest(bytes, EXPECTED_TARGET);-- assert.equal(manifest.modules.fluxer_renderer.sha256, RENDERER_SHA);- });-});diff --git a/fluxer_desktop/src/main/ModuleOnDemand.test.mjs b/fluxer_desktop/src/main/ModuleOnDemand.test.mjsdeleted file mode 100644index f0ba0e807..000000000--- a/fluxer_desktop/src/main/ModuleOnDemand.test.mjs+++ /dev/null@@ -1,139 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {setOnDemandModuleInstaller} = await import('@electron/main/ModuleBootHandoff');-const {createOnDemandModuleInstaller, ensureDesktopModule, UnknownDesktopModuleRequestError} = await import(- '@electron/main/ModuleOnDemand'-);--function deferred() {- let resolve;- let reject;- const promise = new Promise((resolvePromise, rejectPromise) => {- resolve = resolvePromise;- reject = rejectPromise;- });- return {promise, resolve, reject};-}--describe('createOnDemandModuleInstaller', () => {- test('coalesces concurrent requests for the same module into one install', async () => {- const gate = deferred();- const requested = [];- const refreshed = [];- const install = createOnDemandModuleInstaller({- ensure: async (moduleName) => {- requested.push(moduleName);- await gate.promise;- return {module: moduleName, status: 'installed'};- },- refresh: async () => {- refreshed.push(Date.now());- },- });-- const first = install('fluxer_grammars');- const second = install('fluxer_grammars');- const other = install('fluxer_fonts_sc');- assert.equal(first, second);- assert.notEqual(first, other);- gate.resolve();-- assert.deepEqual(await first, {module: 'fluxer_grammars', status: 'installed'});- assert.deepEqual(await second, {module: 'fluxer_grammars', status: 'installed'});- await other;- assert.deepEqual(requested, ['fluxer_grammars', 'fluxer_fonts_sc']);- assert.equal(refreshed.length, 2);- });-- test('a request that arrives after the install settles starts a new install', async () => {- let calls = 0;- const install = createOnDemandModuleInstaller({- ensure: async (moduleName) => {- calls += 1;- return {module: moduleName, status: 'installed'};- },- refresh: async () => {},- });-- await install('fluxer_grammars');- await install('fluxer_grammars');-- assert.equal(calls, 2);- });-- test('an already committed module never touches the served file index', async () => {- let refreshes = 0;- const install = createOnDemandModuleInstaller({- ensure: async (moduleName) => ({module: moduleName, status: 'already-installed'}),- refresh: async () => {- refreshes += 1;- },- });-- assert.deepEqual(await install('fluxer_grammars'), {module: 'fluxer_grammars', status: 'already-installed'});- assert.equal(refreshes, 0);- });-- test('a failed install reports the module as unavailable instead of rejecting', async () => {- const failures = [];- const install = createOnDemandModuleInstaller({- ensure: async () => {- throw new Error('the manifest could not be reached');- },- refresh: async () => {},- onFailure: (moduleName, error) => {- failures.push([moduleName, error.message]);- },- });-- assert.deepEqual(await install('fluxer_grammars'), {module: 'fluxer_grammars', status: 'unavailable'});- assert.deepEqual(failures, [['fluxer_grammars', 'the manifest could not be reached']]);- });-- test('a module that installs but cannot be indexed is reported as unavailable', async () => {- const install = createOnDemandModuleInstaller({- ensure: async (moduleName) => ({module: moduleName, status: 'installed'}),- refresh: async () => {- throw new Error('the module manifest is missing');- },- });-- assert.deepEqual(await install('fluxer_grammars'), {module: 'fluxer_grammars', status: 'unavailable'});- });-});--describe('ensureDesktopModule', () => {- test('reports the module system as disabled when no installer is registered', async () => {- setOnDemandModuleInstaller(null);- assert.deepEqual(await ensureDesktopModule('fluxer_grammars'), {- module: 'fluxer_grammars',- status: 'disabled',- });- });-- test('rejects a module name the store could never hold', async () => {- setOnDemandModuleInstaller(null);- for (const candidate of ['', '../escape', 'Fluxer_Grammars', 'fluxer grammars', 42, null, 'a'.repeat(65)]) {- await assert.rejects(() => ensureDesktopModule(candidate), UnknownDesktopModuleRequestError);- }- });-- test('hands a valid request to the registered installer', async () => {- const seen = [];- setOnDemandModuleInstaller(async (moduleName) => {- seen.push(moduleName);- return {module: moduleName, status: 'installed'};- });-- assert.deepEqual(await ensureDesktopModule('fluxer_grammars'), {- module: 'fluxer_grammars',- status: 'installed',- });- assert.deepEqual(seen, ['fluxer_grammars']);- setOnDemandModuleInstaller(null);- });-});diff --git a/fluxer_desktop/src/main/ModulePackage.test.mjs b/fluxer_desktop/src/main/ModulePackage.test.mjsdeleted file mode 100644index c1a11a8f9..000000000--- a/fluxer_desktop/src/main/ModulePackage.test.mjs+++ /dev/null@@ -1,530 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {createHash} from 'node:crypto';-import {mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import {registerHooks} from 'node:module';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import zlib from 'node:zlib';--const DESKTOP_SRC = new URL('../', import.meta.url);-const PACKAGES = new URL('../../../packages/', import.meta.url);--registerHooks({- resolve(specifier, context, nextResolve) {- if (specifier.startsWith('@electron/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@electron/'.length)}.ts`, DESKTOP_SRC).href};- }- if (specifier.startsWith('@fluxer/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@fluxer/'.length)}.ts`, PACKAGES).href};- }- return nextResolve(specifier, context);- },-});--const {verifyAndExtract} = await import('./ModulePackage.ts');-const {parseModuleVersion} = await import('@electron/main/ModuleVersion');--const BLOCK = 512;-const MODULE_NAME = 'fluxer_renderer';-const BUILD_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const SOURCE_SHA = 'a'.repeat(40);--const temporaryRoots = [];--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--function createRoot(prefix) {- const root = mkdtempSync(path.join(os.tmpdir(), prefix));- temporaryRoots.push(root);- return root;-}--const workspace = createRoot('module-package-');-let counter = 0;--function packagePath(packed) {- const file = path.join(workspace, `package-${(counter += 1)}.br`);- writeFileSync(file, packed);- return file;-}--function destination() {- return path.join(workspace, `store-${(counter += 1)}`);-}--function sha256(data) {- return createHash('sha256').update(data).digest('hex');-}--function octal(value, width) {- return `${value.toString(8).padStart(width - 1, '0')}\0`;-}--function fixChecksum(header) {- header.fill(0x20, 148, 156);- let sum = 0;- for (const byte of header) {- sum += byte;- }- header.write(octal(sum, 8), 148, 8, 'ascii');-}--function ustarHeader({name, size, mode = 0o644, mtime = 0, typeflag = '0', prefix = ''}) {- const header = Buffer.alloc(BLOCK);- header.write(name, 0, 100, 'utf8');- header.write(octal(mode, 8), 100, 8, 'ascii');- header.write(octal(0, 8), 108, 8, 'ascii');- header.write(octal(0, 8), 116, 8, 'ascii');- header.write(octal(size, 12), 124, 12, 'ascii');- header.write(octal(mtime, 12), 136, 12, 'ascii');- header.write(typeflag, 156, 1, 'ascii');- header.write('ustar\0', 257, 6, 'ascii');- header.write('00', 263, 2, 'ascii');- header.write(prefix, 345, 155, 'utf8');- fixChecksum(header);- return header;-}--function pad(size) {- const remainder = size % BLOCK;- return remainder === 0 ? Buffer.alloc(0) : Buffer.alloc(BLOCK - remainder);-}--function packArchive(manifestBytes, members) {- const chunks = [- ustarHeader({name: 'module.json', size: manifestBytes.length}),- manifestBytes,- pad(manifestBytes.length),- ];- for (const member of members) {- chunks.push(ustarHeader({name: member.name, size: member.body.length}), member.body, pad(member.body.length));- }- chunks.push(Buffer.alloc(BLOCK * 2));- const tar = Buffer.concat(chunks);- return repack(tar);-}--function repack(tar) {- const packed = zlib.brotliCompressSync(tar, {- params: {- [zlib.constants.BROTLI_PARAM_QUALITY]: 5,- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: tar.length,- },- });- return {tar, packed, sha256: sha256(packed)};-}--function manifestBytesFor(files) {- return Buffer.from(- `${JSON.stringify(- {- module: MODULE_NAME,- build_version: BUILD_VERSION,- release_channel: RELEASE_CHANNEL,- source_sha: SOURCE_SHA,- files,- },- null,- '\t',- )}\n`,- 'utf8',- );-}--function walk(root, base = '') {- const out = [];- for (const entry of readdirSync(path.join(root, base), {withFileTypes: true})) {- const relative = base ? path.posix.join(base, entry.name) : entry.name;- if (entry.isDirectory()) {- out.push(...walk(root, relative));- } else if (entry.isFile()) {- out.push(relative);- }- }- return out.sort();-}--function packModule(sourceDir) {- const files = [];- const members = [];- for (const relative of walk(sourceDir)) {- const body = readFileSync(path.join(sourceDir, relative));- files.push({path: relative, sha256: sha256(body), bytes: body.length});- members.push({name: `files/${relative}`, body});- }- return packArchive(manifestBytesFor(files), members);-}--function forgeHeader(tar, targetName, mutate) {- const forged = Buffer.from(tar);- const at = forged.indexOf(Buffer.from(`${targetName}\0`, 'utf8'));- if (at === -1) {- throw new Error(`fixture header ${targetName} not found`);- }- const header = forged.subarray(at, at + BLOCK);- mutate(header);- fixChecksum(header);- return forged;-}--function renameHeader(tar, oldName, newName) {- return forgeHeader(tar, oldName, (header) => {- header.fill(0, 0, 100);- header.write(newName, 0, 100, 'utf8');- });-}--const fixture = createRoot('module-package-fixture-');-mkdirSync(path.join(fixture, 'assets'));-mkdirSync(path.join(fixture, 'web'));-writeFileSync(path.join(fixture, 'index.html'), '<html lang="en"><head></head><body></body></html>');-writeFileSync(path.join(fixture, 'assets', 'deadbeefdeadbeef.js'), 'console.log(1)');-writeFileSync(path.join(fixture, 'web', 'favicon-32x32.png'), 'png-bytes');--const good = packModule(fixture);--describe('module package extraction', () => {- test('a valid package verifies and lands every declared file', async () => {- const destinationDir = destination();- const manifest = await verifyAndExtract({- packedPath: packagePath(good.packed),- expectedSha256: good.sha256,- destinationDir,- });- assert.equal(manifest.module, MODULE_NAME);- assert.equal(manifest.build_version, BUILD_VERSION);- assert.equal(manifest.release_channel, RELEASE_CHANNEL);- assert.equal(manifest.source_sha, SOURCE_SHA);- assert.deepEqual(- manifest.files.map((file) => file.path),- ['assets/deadbeefdeadbeef.js', 'index.html', 'web/favicon-32x32.png'],- );- assert.equal(readFileSync(path.join(destinationDir, 'assets', 'deadbeefdeadbeef.js'), 'utf8'), 'console.log(1)');- assert.equal(readFileSync(path.join(destinationDir, 'web', 'favicon-32x32.png'), 'utf8'), 'png-bytes');- assert.equal(JSON.parse(readFileSync(path.join(destinationDir, 'module.json'), 'utf8')).module, MODULE_NAME);- });-- test('a wrong package sha256 is rejected before anything is extracted', async () => {- const destinationDir = destination();- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(good.packed),- expectedSha256: '0'.repeat(64),- destinationDir,- }),- {name: 'ModulePackageHashMismatchError'},- );- assert.throws(() => readdirSync(destinationDir));- });-- test('a tampered payload fails its per-file sha256', async () => {- const tar = Buffer.from(good.tar);- const at = tar.indexOf(Buffer.from('console.log', 'utf8'));- assert.notEqual(at, -1);- tar[at] ^= 0xff;- const tampered = repack(tar);- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(tampered.packed),- expectedSha256: tampered.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageHashMismatchError', message: 'hash mismatch: assets/deadbeefdeadbeef.js'},- );- });-- test('an archive member outside files/ is rejected even with a valid ustar checksum', async () => {- const forged = repack(renameHeader(good.tar, 'files/index.html', '../../../etc/passwd'));- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'path must start with files/: ../../../etc/passwd'},- );- });-- test('an undeclared member under files/ is rejected even with a valid ustar checksum', async () => {- const forged = repack(renameHeader(good.tar, 'files/index.html', 'files/smuggled.js'));- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'unexpected file in archive: not in manifest: files/smuggled.js'},- );- });-- test('a truncated brotli stream is rejected', async () => {- const truncated = good.packed.subarray(0, Math.floor(good.packed.length / 2));- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(truncated),- expectedSha256: sha256(truncated),- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError'},- );- });-- test('an archive without module.json at the root is rejected', async () => {- const forged = repack(renameHeader(good.tar, 'module.json', 'notmodule.json'));- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'module.json missing from archive root'},- );- });-- test('a symlink typeflag is rejected even with a valid ustar checksum', async () => {- const forged = repack(- forgeHeader(good.tar, 'files/index.html', (header) => {- header.write('2', 156, 1, 'ascii');- }),- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError'},- );- });-- test('a manifest declaring an escaping path is rejected', async () => {- const body = Buffer.from('owned', 'utf8');- const escaping = packArchive(- manifestBytesFor([{path: '../../../etc/passwd', sha256: sha256(body), bytes: body.length}]),- [{name: 'files/../../../etc/passwd', body}],- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(escaping.packed),- expectedSha256: escaping.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'unsafe path in archive: ../../../etc/passwd'},- );- });-- test('a manifest declaring module.json is rejected instead of colliding with the extracted manifest', async () => {- const body = Buffer.from('{"module":"smuggled"}', 'utf8');- const reserved = packArchive(manifestBytesFor([{path: 'module.json', sha256: sha256(body), bytes: body.length}]), [- {name: 'files/module.json', body},- ]);- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(reserved.packed),- expectedSha256: reserved.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'module.json declares the reserved path module.json'},- );- });-- test('a manifest declaring two paths that differ only in ASCII case is rejected', async () => {- const first = Buffer.from('console.log(1)', 'utf8');- const second = Buffer.from('console.log(2)', 'utf8');- const colliding = packArchive(- manifestBytesFor([- {path: 'assets/App.js', sha256: sha256(first), bytes: first.length},- {path: 'assets/app.js', sha256: sha256(second), bytes: second.length},- ]),- [- {name: 'files/assets/App.js', body: first},- {name: 'files/assets/app.js', body: second},- ],- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(colliding.packed),- expectedSha256: colliding.sha256,- destinationDir: destination(),- }),- {- name: 'ModulePackageMalformedError',- message: 'module.json declares colliding paths assets/App.js and assets/app.js',- },- );- });-- test('a manifest declaring two paths that differ only in non-ASCII case is rejected', async () => {- const first = Buffer.from('console.log(1)', 'utf8');- const second = Buffer.from('console.log(2)', 'utf8');- const colliding = packArchive(- manifestBytesFor([- {path: 'assets/\u00c9.js', sha256: sha256(first), bytes: first.length},- {path: 'assets/\u00e9.js', sha256: sha256(second), bytes: second.length},- ]),- [- {name: 'files/assets/\u00c9.js', body: first},- {name: 'files/assets/\u00e9.js', body: second},- ],- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(colliding.packed),- expectedSha256: colliding.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError'},- );- });-- test('a manifest declaring the same path in NFD and NFC is rejected', async () => {- const decomposed = 'assets/e\u0301.js';- const composed = 'assets/\u00e9.js';- const first = Buffer.from('console.log(1)', 'utf8');- const second = Buffer.from('console.log(2)', 'utf8');- const colliding = packArchive(- manifestBytesFor([- {path: decomposed, sha256: sha256(first), bytes: first.length},- {path: composed, sha256: sha256(second), bytes: second.length},- ]),- [- {name: `files/${decomposed}`, body: first},- {name: `files/${composed}`, body: second},- ],- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(colliding.packed),- expectedSha256: colliding.sha256,- destinationDir: destination(),- }),- {- name: 'ModulePackageMalformedError',- message: `module.json declares colliding paths ${decomposed} and ${composed}`,- },- );- });-- test('a manifest declaring a file that is also a directory prefix is rejected', async () => {- const first = Buffer.from('console.log(1)', 'utf8');- const second = Buffer.from('console.log(2)', 'utf8');- const colliding = packArchive(- manifestBytesFor([- {path: 'assets', sha256: sha256(first), bytes: first.length},- {path: 'assets/app.js', sha256: sha256(second), bytes: second.length},- ]),- [- {name: 'files/assets', body: first},- {name: 'files/assets/app.js', body: second},- ],- );- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(colliding.packed),- expectedSha256: colliding.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'module.json declares colliding paths assets and assets/app.js'},- );- });-- test('a manifest declaring an absolute path is rejected', async () => {- const body = Buffer.from('owned', 'utf8');- const absolute = packArchive(manifestBytesFor([{path: '/etc/passwd', sha256: sha256(body), bytes: body.length}]), [- {name: 'files//etc/passwd', body},- ]);- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(absolute.packed),- expectedSha256: absolute.sha256,- destinationDir: destination(),- }),- {name: 'ModulePackageMalformedError', message: 'unsafe path in archive: /etc/passwd'},- );- });-});--describe('module package build version', () => {- function packWithBuildVersion(buildVersion) {- const body = Buffer.from('console.log(1)', 'utf8');- const files = [{path: 'index.html', sha256: sha256(body), bytes: body.length}];- const manifestBytes = Buffer.from(- `${JSON.stringify(- {- module: MODULE_NAME,- build_version: buildVersion,- release_channel: RELEASE_CHANNEL,- source_sha: SOURCE_SHA,- files,- },- null,- '\t',- )}\n`,- 'utf8',- );- return packArchive(manifestBytes, [{name: 'files/index.html', body}]);- }-- test('a package whose build_version is not a semantic version is rejected at install', async () => {- assert.throws(() => parseModuleVersion('2026.823.1.4', 'installed module fluxer_renderer build version'), {- name: 'ModuleVersionMalformedError',- });- const forged = packWithBuildVersion('2026.823.1.4');- const destinationDir = destination();- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir,- }),- {- name: 'ModulePackageMalformedError',- message: 'module.json build_version is not a valid semantic version: 2026.823.1.4',- },- );- assert.deepEqual(readdirSync(destinationDir), []);- });-- test('a package whose build_version has a leading zero component is rejected at install', async () => {- assert.throws(() => parseModuleVersion('2026.08.1', 'installed module fluxer_renderer build version'), {- name: 'ModuleVersionMalformedError',- });- const forged = packWithBuildVersion('2026.08.1');- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {- name: 'ModulePackageMalformedError',- message: 'module.json build_version is not a valid semantic version: 2026.08.1',- },- );- });-- test('a package whose build_version carries a prerelease is rejected at install', async () => {- const forged = packWithBuildVersion('2026.823.1-rc.1');- await assert.rejects(- verifyAndExtract({- packedPath: packagePath(forged.packed),- expectedSha256: forged.sha256,- destinationDir: destination(),- }),- {- name: 'ModulePackageMalformedError',- message: 'module.json build_version must contain exactly three numeric components: 2026.823.1-rc.1',- },- );- });-});diff --git a/fluxer_desktop/src/main/ModulePackageInstaller.test.mjs b/fluxer_desktop/src/main/ModulePackageInstaller.test.mjsdeleted file mode 100644index e56f9f8d3..000000000--- a/fluxer_desktop/src/main/ModulePackageInstaller.test.mjs+++ /dev/null@@ -1,217 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {createHash} from 'node:crypto';-import {mkdtempSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {ModulePackageIOError, verifyAndExtract} = await import('@electron/main/ModulePackage');-const {isDeterministicPackageFailure, ModulePackageInstaller} = await import('@electron/main/ModulePackageInstaller');--const temporaryRoots = [];--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--function createRoot() {- const root = mkdtempSync(path.join(os.tmpdir(), 'module-package-installer-'));- temporaryRoots.push(root);- return root;-}--function sha256(data) {- return createHash('sha256').update(data).digest('hex');-}--describe('module package failure classification', () => {- test('an EEXIST failure from the extractor is deterministic', async () => {- const root = createRoot();- const packed = Buffer.from('module package bytes', 'utf8');- const packedPath = path.join(root, 'package.br');- writeFileSync(packedPath, packed);- const destinationDir = path.join(root, 'incoming');- writeFileSync(destinationDir, 'occupied');- const failure = await verifyAndExtract({packedPath, expectedSha256: sha256(packed), destinationDir}).then(- () => null,- (error) => error,- );- assert.equal(failure?.name, 'ModulePackageIOError');- assert.equal(failure?.cause?.code, 'EEXIST');- assert.equal(isDeterministicPackageFailure(failure), true);- });-- test('a storage-full failure from the extractor stays non-deterministic', () => {- const cause = Object.assign(new Error('no space left on device'), {code: 'ENOSPC'});- const failure = new ModulePackageIOError('failed to write index.html', {cause});- assert.equal(isDeterministicPackageFailure(failure), false);- });-});--const PACKAGE_BYTES = Buffer.from('0123456789abcdefghijklmnopqrstuvwxyz', 'utf8');-const PACKAGE_ORIGIN = 'https://pkgs.example.test';--function planItem({- url = `${PACKAGE_ORIGIN}/desktop/canary/modules/fluxer_renderer/${sha256(PACKAGE_BYTES)}/package.br`,-} = {}) {- return {- module: 'fluxer_renderer',- entry: {sha256: sha256(PACKAGE_BYTES), bytes: PACKAGE_BYTES.length, url},- requirement: 'required',- };-}--async function collect(download) {- const parts = [];- for await (const chunk of download.chunks) {- parts.push(Buffer.from(chunk));- }- return {offset: download.offset, bytes: Buffer.concat(parts)};-}--function createInstaller({respond, resumeFrom}) {- const requests = [];- const reports = [];- const downloads = [];- const installer = new ModulePackageInstaller({- store: {- installModule: async ({download}) => {- downloads.push(await collect(await download(resumeFrom)));- },- recordShellRanges: async () => {},- },- packageOrigin: PACKAGE_ORIGIN,- fetch: async (url, init) => {- requests.push({url, range: init.headers.range ?? null});- return respond(requests.length, init);- },- onProgress: () => {},- report: (report) => reports.push(report),- });- return {installer, requests, reports, downloads};-}--describe('resuming a module package download', () => {- test('asks for the remaining bytes and hands back the range the server confirmed', async () => {- const {installer, requests, downloads} = createInstaller({- resumeFrom: 10,- respond: () =>- new Response(PACKAGE_BYTES.subarray(10), {- status: 206,- headers: {'content-range': `bytes 10-${PACKAGE_BYTES.length - 1}/${PACKAGE_BYTES.length}`},- }),- });-- await installer.install(planItem(), 1, 1);-- assert.deepEqual(- requests.map((request) => request.range),- ['bytes=10-'],- );- assert.equal(downloads[0].offset, 10);- assert.deepEqual(downloads[0].bytes, PACKAGE_BYTES.subarray(10));- });-- test('a full response to a range request restarts from the first byte', async () => {- const {installer, downloads} = createInstaller({- resumeFrom: 10,- respond: () => new Response(PACKAGE_BYTES, {status: 200}),- });-- await installer.install(planItem(), 1, 1);-- assert.equal(downloads[0].offset, 0);- assert.deepEqual(downloads[0].bytes, PACKAGE_BYTES);- });-- test('an unsatisfiable range falls back to a plain request', async () => {- const {installer, requests, downloads} = createInstaller({- resumeFrom: 10,- respond: (attempt) =>- attempt === 1 ? new Response('', {status: 416}) : new Response(PACKAGE_BYTES, {status: 200}),- });-- await installer.install(planItem(), 1, 1);-- assert.deepEqual(- requests.map((request) => request.range),- ['bytes=10-', null],- );- assert.equal(downloads[0].offset, 0);- });-- test('a partial response that starts somewhere else is discarded for a plain request', async () => {- const {installer, requests, downloads} = createInstaller({- resumeFrom: 10,- respond: (attempt) =>- attempt === 1- ? new Response(PACKAGE_BYTES.subarray(5), {- status: 206,- headers: {'content-range': `bytes 5-${PACKAGE_BYTES.length - 1}/${PACKAGE_BYTES.length}`},- })- : new Response(PACKAGE_BYTES, {status: 200}),- });-- await installer.install(planItem(), 1, 1);-- assert.deepEqual(- requests.map((request) => request.range),- ['bytes=10-', null],- );- assert.deepEqual(downloads[0].bytes, PACKAGE_BYTES);- });-- test('a partial file that already holds every byte needs no request', async () => {- const {installer, requests, downloads} = createInstaller({- resumeFrom: PACKAGE_BYTES.length,- respond: () => {- throw new Error('unexpected request');- },- });-- await installer.install(planItem(), 1, 1);-- assert.equal(requests.length, 0);- assert.equal(downloads[0].offset, PACKAGE_BYTES.length);- assert.equal(downloads[0].bytes.length, 0);- });-- test('a partial file longer than the package is downloaded again from the start', async () => {- const {installer, requests} = createInstaller({- resumeFrom: PACKAGE_BYTES.length + 1,- respond: () => new Response(PACKAGE_BYTES, {status: 200}),- });-- await installer.install(planItem(), 1, 1);-- assert.deepEqual(- requests.map((request) => request.range),- [null],- );- });-});--describe('reporting deterministic package failures', () => {- test('a package url the policy refuses is reported with the url', async () => {- const url = 'http://192.168.139.107:48780/package.br';- const {installer, reports} = createInstaller({- resumeFrom: 0,- respond: () => {- throw new Error('unexpected request');- },- });-- await assert.rejects(installer.install(planItem({url}), 1, 1), /not https/u);-- assert.equal(reports.length, 1);- assert.equal(reports[0].type, 'package-rejected');- assert.match(reports[0].message, /192\.168\.139\.107/u);- });-});diff --git a/fluxer_desktop/src/main/ModuleStore.test.mjs b/fluxer_desktop/src/main/ModuleStore.test.mjsdeleted file mode 100644index ee3bc967c..000000000--- a/fluxer_desktop/src/main/ModuleStore.test.mjs+++ /dev/null@@ -1,1435 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {createHash} from 'node:crypto';-import {- cpSync,- existsSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- symlinkSync,- utimesSync,- writeFileSync,-} from 'node:fs';-import fsPromises, {rm} from 'node:fs/promises';-import {registerHooks} from 'node:module';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import zlib from 'node:zlib';--const DESKTOP_SRC = new URL('../', import.meta.url);-const PACKAGES = new URL('../../../packages/', import.meta.url);--registerHooks({- resolve(specifier, context, nextResolve) {- if (specifier.startsWith('@electron/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@electron/'.length)}.ts`, DESKTOP_SRC).href};- }- if (specifier.startsWith('@fluxer/')) {- return {shortCircuit: true, url: new URL(`${specifier.slice('@fluxer/'.length)}.ts`, PACKAGES).href};- }- return nextResolve(specifier, context);- },-});--const {- MODULE_FILE_STAMPS_NAME,- MODULE_INCOMING_STORE_PREFIX,- MODULE_PACKAGE_MAX_AGE_MS,- MODULE_STATE_FILE_NAME,- MODULE_STATE_VERSION,- ModuleManifestEquivocationError,- ModuleManifestRollbackError,- ModuleStore,- ModuleStoreDownloadHashMismatchError,- ModuleStoreGarbageCollectionOrderError,- ModuleStoreInstallationMissingError,- getModuleStoreRoot,-} = await import('./ModuleStore.ts');-const {ModulePackageHashMismatchError} = await import('./ModulePackage.ts');--const BLOCK = 512;-const SHELL_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const SOURCE_SHA = 'a'.repeat(40);-const MANIFEST_FEED = {releaseChannel: RELEASE_CHANNEL, platform: 'darwin', arch: 'arm64'};-const MANIFEST_FETCHED_AT = '2026-08-23T12:00:00.000Z';--const temporaryRoots = [];--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--function createUserData() {- const root = mkdtempSync(path.join(os.tmpdir(), 'module-store-'));- temporaryRoots.push(root);- return root;-}--function sha256(data) {- return createHash('sha256').update(data).digest('hex');-}--function octal(value, width) {- return `${value.toString(8).padStart(width - 1, '0')}\0`;-}--function ustarHeader(name, size) {- const header = Buffer.alloc(BLOCK);- header.write(name, 0, 100, 'utf8');- header.write(octal(0o644, 8), 100, 8, 'ascii');- header.write(octal(0, 8), 108, 8, 'ascii');- header.write(octal(0, 8), 116, 8, 'ascii');- header.write(octal(size, 12), 124, 12, 'ascii');- header.write(octal(0, 12), 136, 12, 'ascii');- header.write('0', 156, 1, 'ascii');- header.write('ustar\0', 257, 6, 'ascii');- header.write('00', 263, 2, 'ascii');- header.fill(0x20, 148, 156);- let sum = 0;- for (const byte of header) {- sum += byte;- }- header.write(octal(sum, 8), 148, 8, 'ascii');- return header;-}--function pad(size) {- const remainder = size % BLOCK;- return remainder === 0 ? Buffer.alloc(0) : Buffer.alloc(BLOCK - remainder);-}--function packModule(moduleName, entries, {declaredSha256 = {}} = {}) {- const files = entries.map(([relative, body]) => ({- path: relative,- sha256: declaredSha256[relative] ?? sha256(Buffer.from(body, 'utf8')),- bytes: Buffer.byteLength(body, 'utf8'),- }));- const manifest = Buffer.from(- `${JSON.stringify(- {- module: moduleName,- build_version: SHELL_VERSION,- release_channel: RELEASE_CHANNEL,- source_sha: SOURCE_SHA,- files,- },- null,- '\t',- )}\n`,- 'utf8',- );- const chunks = [ustarHeader('module.json', manifest.length), manifest, pad(manifest.length)];- for (const [relative, body] of entries) {- const payload = Buffer.from(body, 'utf8');- chunks.push(ustarHeader(`files/${relative}`, payload.length), payload, pad(payload.length));- }- chunks.push(Buffer.alloc(BLOCK * 2));- const tar = Buffer.concat(chunks);- const packed = zlib.brotliCompressSync(tar, {- params: {[zlib.constants.BROTLI_PARAM_QUALITY]: 5, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: tar.length},- });- return {module: moduleName, packed, sha256: sha256(packed), files};-}--function streamOf(buffer) {- return {- offset: 0,- chunks: (async function* stream() {- for (let offset = 0; offset < buffer.length; offset += 4096) {- yield buffer.subarray(offset, Math.min(offset + 4096, buffer.length));- }- })(),- };-}--async function openStore(userDataPath) {- return await ModuleStore.open({- root: getModuleStoreRoot(userDataPath),- shellVersion: SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- });-}--function deferred() {- let resolve;- const promise = new Promise((resolvePromise) => {- resolve = resolvePromise;- });- return {promise, resolve};-}--async function markLaunched(store) {- return await store.markLaunchAttemptSucceeded(await store.recordLaunchAttempt());-}--async function install(store, packageFile) {- const installed = await store.installModule({- module: packageFile.module,- sha256: packageFile.sha256,- download: () => streamOf(packageFile.packed),- });- await store.settleInstalledModules();- return installed;-}--function manifestObservation(metadataVersion, manifestSha256) {- return {feed: MANIFEST_FEED, metadataVersion, manifestSha256};-}--async function recordManifest(store, metadataVersion, manifestSha256) {- return await store.recordManifestFetch({- etag: null,- fetchedAt: MANIFEST_FETCHED_AT,- manifest: manifestObservation(metadataVersion, manifestSha256),- });-}--function readState(userDataPath) {- return JSON.parse(readFileSync(path.join(getModuleStoreRoot(userDataPath), MODULE_STATE_FILE_NAME), 'utf8'));-}--const RENDERER_V1 = packModule('fluxer_renderer', [- ['assets/index-v1.js', 'renderer one'],- ['assets/style-v1.css', 'body{}'],-]);-const RENDERER_V2 = packModule('fluxer_renderer', [['assets/index-v2.js', 'renderer two']]);-const GRAMMARS_V1 = packModule('fluxer_grammars', [['assets/rust-v1.wasm', 'grammar one']]);-const RENDERER_BAD_MEMBER = packModule('fluxer_renderer', [['assets/index-v1.js', 'renderer one']], {- declaredSha256: {'assets/index-v1.js': 'e'.repeat(64)},-});--describe('ModuleStore', () => {- test('is beside the account store, never inside it', () => {- const userDataPath = createUserData();- const root = getModuleStoreRoot(userDataPath);- assert.equal(root, path.join(userDataPath, 'modules'));- assert.equal(path.dirname(root), userDataPath);- assert.equal(existsSync(path.join(userDataPath, 'desktop-app-store.sqlite3')), false);- });-- test('says when the shell changed version since the store was last opened', async () => {- const userDataPath = createUserData();- assert.equal((await openStore(userDataPath)).shellVersionChanged, false);- assert.equal((await openStore(userDataPath)).shellVersionChanged, false);-- const upgraded = await ModuleStore.open({- root: getModuleStoreRoot(userDataPath),- shellVersion: '2026.824.1',- releaseChannel: RELEASE_CHANNEL,- });-- assert.equal(upgraded.shellVersionChanged, true);- assert.notEqual(- readState(userDataPath).shell_version,- '2026.824.1',- 'a quit or crash before the modules converge has to force the update again on the next boot',- );- const reopened = await ModuleStore.open({- root: getModuleStoreRoot(userDataPath),- shellVersion: '2026.824.1',- releaseChannel: RELEASE_CHANNEL,- });- assert.equal(reopened.shellVersionChanged, true);-- await reopened.recordShellVersionConverged();-- assert.equal(readState(userDataPath).shell_version, '2026.824.1');- const converged = await ModuleStore.open({- root: getModuleStoreRoot(userDataPath),- shellVersion: '2026.824.1',- releaseChannel: RELEASE_CHANNEL,- });- assert.equal(converged.shellVersionChanged, false);- });-- test('writes state.json atomically and leaves no temporary behind', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await install(store, GRAMMARS_V1);- const before = readState(userDataPath);- assert.deepEqual(before.committed, {});-- await store.commit({fluxer_renderer: RENDERER_V1.sha256, fluxer_grammars: GRAMMARS_V1.sha256});-- const after = readState(userDataPath);- assert.equal(after.state_version, MODULE_STATE_VERSION);- assert.deepEqual(after.committed, {- fluxer_grammars: GRAMMARS_V1.sha256,- fluxer_renderer: RENDERER_V1.sha256,- });- assert.deepEqual(after.previous, {});- assert.equal(after.boot_attempt, 0);- const leftovers = readdirSync(getModuleStoreRoot(userDataPath)).filter((name) => name.endsWith('.tmp'));- assert.deepEqual(leftovers, []);-- const reopened = await openStore(userDataPath);- assert.deepEqual(reopened.getCommitted(), after.committed);- });-- test('moves the old committed map to previous on the next commit', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});-- const state = readState(userDataPath);- assert.deepEqual(state.committed, {fluxer_renderer: RENDERER_V2.sha256});- assert.deepEqual(state.previous, {fluxer_renderer: RENDERER_V1.sha256});- });-- test('a crash before the commit point leaves the old set committed', async () => {- const userDataPath = createUserData();- const first = await openStore(userDataPath);- await install(first, RENDERER_V1);- await first.commit({fluxer_renderer: RENDERER_V1.sha256});-- const crashing = await openStore(userDataPath);- const staged = await install(crashing, RENDERER_V2);- assert.equal(existsSync(path.join(staged.directory, 'module.json')), true);-- const rebooted = await openStore(userDataPath);- assert.deepEqual(rebooted.getCommitted(), {fluxer_renderer: RENDERER_V1.sha256});- const index = await rebooted.buildModuleIndex();- assert.deepEqual([...index.keys()].sort(), ['assets/index-v1.js', 'assets/style-v1.css']);- assert.equal(existsSync(staged.directory), true);- });-- test('a download hash mismatch fails that module only and caches nothing', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await assert.rejects(- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: () => streamOf(Buffer.from('not the package', 'utf8')),- }),- ModuleStoreDownloadHashMismatchError,- );- assert.equal(existsSync(store.getPackagePath(RENDERER_V1.sha256)), false);- assert.deepEqual(readdirSync(store.incomingDownloadRoot), []);-- const installed = await install(store, GRAMMARS_V1);- assert.equal(existsSync(path.join(installed.directory, 'module.json')), true);- await store.commit({fluxer_grammars: GRAMMARS_V1.sha256});- assert.deepEqual(readState(userDataPath).committed, {fluxer_grammars: GRAMMARS_V1.sha256});- });-- test('a member digest mismatch leaves the verified package cached for every later attempt', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- let downloads = 0;- const attempt = () =>- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_BAD_MEMBER.sha256,- download: () => {- downloads += 1;- return streamOf(RENDERER_BAD_MEMBER.packed);- },- });- const memberMismatch = (error) =>- error instanceof ModulePackageHashMismatchError && error.message === 'hash mismatch: assets/index-v1.js';- const packagePath = store.getPackagePath(RENDERER_BAD_MEMBER.sha256);-- await assert.rejects(attempt(), memberMismatch);- assert.equal(downloads, 1);- assert.equal(existsSync(packagePath), true);-- await assert.rejects(attempt(), memberMismatch);- assert.equal(existsSync(packagePath), true);- await assert.rejects(attempt(), memberMismatch);-- assert.equal(downloads, 1);- assert.deepEqual(readdirSync(store.storeRoot), []);- });-- test('a cached package whose own digest no longer matches is dropped and downloaded again', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- let downloads = 0;- const attempt = () =>- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_BAD_MEMBER.sha256,- download: () => {- downloads += 1;- return streamOf(RENDERER_BAD_MEMBER.packed);- },- });- const packagePath = store.getPackagePath(RENDERER_BAD_MEMBER.sha256);-- await assert.rejects(attempt(), ModulePackageHashMismatchError);- assert.equal(downloads, 1);- writeFileSync(packagePath, 'not the package');-- await assert.rejects(- attempt(),- (error) =>- error instanceof ModulePackageHashMismatchError && error.message.startsWith('package sha256 mismatch:'),- );- assert.equal(existsSync(packagePath), false);-- await assert.rejects(attempt(), ModulePackageHashMismatchError);- assert.equal(downloads, 2);- assert.equal(existsSync(packagePath), true);- });-- test('commit refuses when a store directory is missing', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await rm(installed.directory, {recursive: true, force: true});-- await assert.rejects(store.commit({fluxer_renderer: RENDERER_V1.sha256}), ModuleStoreInstallationMissingError);- assert.deepEqual(readState(userDataPath).committed, {});- });-- test('commit refuses to re-affirm a committed module whose directory was deleted', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await rm(installed.directory, {recursive: true, force: true});-- await assert.rejects(store.commit({fluxer_renderer: RENDERER_V1.sha256}), ModuleStoreInstallationMissingError);- assert.deepEqual(readState(userDataPath).committed, {fluxer_renderer: RENDERER_V1.sha256});- });-- test('commit refuses when module.json is unreadable', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- writeFileSync(path.join(installed.directory, 'module.json'), 'not json');-- await assert.rejects(store.commit({fluxer_renderer: RENDERER_V1.sha256}), ModuleStoreInstallationMissingError);- });-- test('garbage collection only runs after a successful launch', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await assert.rejects(store.collectGarbage(), ModuleStoreGarbageCollectionOrderError);- });-- test('garbage collection preserves committed and previous', async () => {- const userDataPath = createUserData();- const earlierRun = await openStore(userDataPath);- const v1 = await install(earlierRun, RENDERER_V1);- await earlierRun.commit({fluxer_renderer: RENDERER_V1.sha256});- const v2 = await install(earlierRun, RENDERER_V2);- await earlierRun.commit({fluxer_renderer: RENDERER_V2.sha256});- const orphan = await install(earlierRun, GRAMMARS_V1);- const store = await openStore(userDataPath);-- const incoming = path.join(store.storeRoot, `${MODULE_INCOMING_STORE_PREFIX}${'b'.repeat(64)}`);- mkdirSync(incoming, {recursive: true});- const stale = path.join(store.downloadRoot, `${'c'.repeat(64)}.br`);- writeFileSync(stale, 'stale');- const staleSeconds = (Date.now() - MODULE_PACKAGE_MAX_AGE_MS - 60_000) / 1000;- utimesSync(stale, staleSeconds, staleSeconds);- const fresh = store.getPackagePath(RENDERER_V2.sha256);- assert.equal(existsSync(fresh), true);-- await markLaunched(store);- const result = await store.collectGarbage();-- assert.equal(existsSync(v1.directory), true);- assert.equal(existsSync(v2.directory), true);- assert.equal(existsSync(orphan.directory), false);- assert.equal(existsSync(incoming), false);- assert.equal(existsSync(stale), false);- assert.equal(existsSync(fresh), true);- assert.equal(result.removedDirectories.includes(incoming), true);- assert.equal(result.removedPackages.includes(stale), true);- });-- test('garbage collection keeps an installation that has not been committed yet', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await markLaunched(store);- const pending = await install(store, GRAMMARS_V1);-- await store.collectGarbage();-- assert.equal(existsSync(path.join(pending.directory, 'module.json')), true);- await store.mergeCommitted({fluxer_grammars: GRAMMARS_V1.sha256});- assert.deepEqual(readState(userDataPath).committed, {- fluxer_grammars: GRAMMARS_V1.sha256,- fluxer_renderer: RENDERER_V1.sha256,- });- });-- test('garbage collection waits for an in-flight install instead of deleting its staging tree', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await markLaunched(store);-- const staging = path.join(store.storeRoot, `${MODULE_INCOMING_STORE_PREFIX}${GRAMMARS_V1.sha256}`);- const rename = fsPromises.rename;- const staged = deferred();- const release = deferred();- fsPromises.rename = async (from, to) => {- if (from === staging) {- staged.resolve();- await release.promise;- }- return await rename(from, to);- };- try {- const installing = install(store, GRAMMARS_V1);- await staged.promise;- const collecting = store.collectGarbage();- await new Promise((resolve) => setTimeout(resolve, 50));-- assert.equal(existsSync(staging), true);- release.resolve();- const installed = await installing;- const result = await collecting;- assert.equal(existsSync(path.join(installed.directory, 'module.json')), true);- assert.equal(result.removedDirectories.includes(staging), false);- } finally {- fsPromises.rename = rename;- }- });-- test('garbage collection keeps a cached package that an install is already using', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await markLaunched(store);- const reclaimed = await install(store, GRAMMARS_V1);- await rm(reclaimed.directory, {recursive: true, force: true});- const cached = store.getPackagePath(GRAMMARS_V1.sha256);- const staleSeconds = (Date.now() - MODULE_PACKAGE_MAX_AGE_MS - 60_000) / 1000;- utimesSync(cached, staleSeconds, staleSeconds);-- const readdir = fsPromises.readdir;- const sweeping = deferred();- const release = deferred();- let held = false;- fsPromises.readdir = async (directory, options) => {- if (directory === store.storeRoot && !held) {- held = true;- sweeping.resolve();- await release.promise;- }- return await readdir(directory, options);- };- try {- const collecting = store.collectGarbage();- await sweeping.promise;- const installing = install(store, GRAMMARS_V1);- await new Promise((resolve) => setTimeout(resolve, 50));- release.resolve();- const result = await collecting;- const installed = await installing;-- assert.equal(existsSync(cached), true);- assert.equal(result.removedPackages.includes(cached), false);- assert.equal(existsSync(path.join(installed.directory, 'module.json')), true);- } finally {- fsPromises.readdir = readdir;- }- });-- test('a second rollback onto the same set reports no rollback, so the update path still runs', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});-- for (let boot = 0; boot < 2; boot += 1) {- const failing = await openStore(userDataPath);- await failing.beginBootAttempt();- await failing.recordLaunchAttempt();- }- const rolledBackStore = await openStore(userDataPath);- const rollback = await rolledBackStore.beginBootAttempt();- assert.equal(rollback.rolledBack, true);- assert.deepEqual(rollback.committed, {fluxer_renderer: RENDERER_V1.sha256});- await rolledBackStore.recordLaunchAttempt();-- for (let boot = 0; boot < 1; boot += 1) {- const failing = await openStore(userDataPath);- await failing.beginBootAttempt();- await failing.recordLaunchAttempt();- }- const secondRollback = await (await openStore(userDataPath)).beginBootAttempt();-- assert.equal(secondRollback.rolledBack, false);- assert.equal(secondRollback.bootAttempt, 0);- assert.deepEqual(secondRollback.committed, {fluxer_renderer: RENDERER_V1.sha256});- assert.equal(readState(userDataPath).boot_attempt, 0);- });-- test('a first-ever committed set is never rolled back into an empty committed map', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});-- for (let boot = 0; boot < 2; boot += 1) {- const failing = await openStore(userDataPath);- await failing.beginBootAttempt();- await failing.recordLaunchAttempt();- }- const rollback = await (await openStore(userDataPath)).beginBootAttempt();-- assert.equal(rollback.rolledBack, false);- assert.equal(rollback.bootAttempt, 0);- assert.deepEqual(rollback.committed, {fluxer_renderer: RENDERER_V1.sha256});- assert.deepEqual(readState(userDataPath).committed, {fluxer_renderer: RENDERER_V1.sha256});- });-- test('rolls back to the previous set after two failed boots', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});-- const firstStore = await openStore(userDataPath);- const firstBoot = await firstStore.beginBootAttempt();- assert.deepEqual(firstBoot, {- rolledBack: false,- bootAttempt: 0,- committed: {fluxer_renderer: RENDERER_V2.sha256},- });- await firstStore.recordLaunchAttempt();- assert.equal(readState(userDataPath).boot_attempt, 1);-- const secondStore = await openStore(userDataPath);- const secondBoot = await secondStore.beginBootAttempt();- assert.equal(secondBoot.rolledBack, false);- assert.equal(secondBoot.bootAttempt, 1);- await secondStore.recordLaunchAttempt();- assert.equal(readState(userDataPath).boot_attempt, 2);-- const thirdStore = await openStore(userDataPath);- const thirdBoot = await thirdStore.beginBootAttempt();- assert.equal(thirdBoot.rolledBack, true);- assert.equal(thirdBoot.bootAttempt, 0);- assert.deepEqual(thirdBoot.committed, {fluxer_renderer: RENDERER_V1.sha256});- assert.deepEqual(readState(userDataPath).committed, {fluxer_renderer: RENDERER_V1.sha256});-- const index = await thirdStore.buildModuleIndex();- assert.deepEqual([...index.keys()].sort(), ['assets/index-v1.js', 'assets/style-v1.css']);-- await markLaunched(thirdStore);- assert.equal(readState(userDataPath).boot_attempt, 0);- const fourthBoot = await (await openStore(userDataPath)).beginBootAttempt();- assert.equal(fourthBoot.rolledBack, false);- assert.equal(fourthBoot.bootAttempt, 0);- });-- test('a boot that never launches leaves the attempt counter alone, so blocking cannot downgrade anyone', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});-- for (let attempt = 0; attempt < 5; attempt += 1) {- const blocked = await openStore(userDataPath);- assert.equal((await blocked.beginBootAttempt()).rolledBack, false);- }-- assert.equal(readState(userDataPath).boot_attempt, 0);- assert.deepEqual(readState(userDataPath).committed, {fluxer_renderer: RENDERER_V2.sha256});- });-- test('the attempt counter is fsynced before the handoff, not after it', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});-- await store.recordLaunchAttempt();-- assert.equal(readState(userDataPath).boot_attempt, 1);- assert.equal(store.getState().boot_attempt, 1);- });-- test('builds an index map across every committed module', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const renderer = await install(store, RENDERER_V1);- const grammars = await install(store, GRAMMARS_V1);- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V1.sha256, fluxer_grammars: GRAMMARS_V1.sha256});-- const index = await store.buildModuleIndex();- assert.equal(index.size, 3);- assert.equal(index.get('assets/index-v1.js'), path.join(renderer.directory, 'assets', 'index-v1.js'));- assert.equal(index.get('assets/style-v1.css'), path.join(renderer.directory, 'assets', 'style-v1.css'));- assert.equal(index.get('assets/rust-v1.wasm'), path.join(grammars.directory, 'assets', 'rust-v1.wasm'));- assert.equal(index.has('assets/index-v2.js'), false);- for (const absolute of index.values()) {- assert.equal(existsSync(absolute), true);- }- assert.equal(readFileSync(index.get('assets/rust-v1.wasm'), 'utf8'), 'grammar one');- });-- test('builds the index from one committed generation even when a merge lands mid-scan', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const renderer = await install(store, RENDERER_V1);- await install(store, GRAMMARS_V1);- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V1.sha256, fluxer_grammars: GRAMMARS_V1.sha256});-- const grammarsDirectory = store.getModuleDirectory('fluxer_grammars', GRAMMARS_V1.sha256);- const lstat = fsPromises.lstat;- const scanning = deferred();- const release = deferred();- let held = false;- fsPromises.lstat = async (target, ...rest) => {- if (target === grammarsDirectory && !held) {- held = true;- scanning.resolve();- await release.promise;- }- return await lstat(target, ...rest);- };- try {- const building = store.buildModuleIndex();- await scanning.promise;- await store.mergeCommitted({fluxer_renderer: RENDERER_V2.sha256});- release.resolve();- const index = await building;-- assert.deepEqual([...index.keys()].sort(), ['assets/index-v1.js', 'assets/rust-v1.wasm', 'assets/style-v1.css']);- assert.equal(index.get('assets/index-v1.js'), path.join(renderer.directory, 'assets', 'index-v1.js'));- } finally {- fsPromises.lstat = lstat;- }- });-- test('a served file swapped for different bytes of the same length is no longer installed', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const served = path.join(installed.directory, 'assets', 'index-v1.js');- writeFileSync(served, 'RENDERER ONE');- assert.equal(readFileSync(served).length, Buffer.byteLength('renderer one', 'utf8'));-- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);- await assert.rejects(store.buildModuleIndex(), ModuleStoreInstallationMissingError);- await assert.rejects(store.commit({fluxer_renderer: RENDERER_V1.sha256}), ModuleStoreInstallationMissingError);- });-- test('a repair reinstall keeps the committed tree served until the replacement is renamed in', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const corrupted = path.join(installed.directory, 'assets', 'index-v1.js');- const untouched = path.join(installed.directory, 'assets', 'style-v1.css');- writeFileSync(corrupted, 'RENDERER ONE');- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);-- const incoming = path.join(store.storeRoot, `${MODULE_INCOMING_STORE_PREFIX}${RENDERER_V1.sha256}`);- const mkdir = fsPromises.mkdir;- const servedDuringExtraction = [];- fsPromises.mkdir = async (target, ...rest) => {- if (typeof target === 'string' && (target === incoming || target.startsWith(`${incoming}${path.sep}`))) {- servedDuringExtraction.push(existsSync(untouched));- }- return await mkdir(target, ...rest);- };- let repaired;- try {- repaired = await install(store, RENDERER_V1);- } finally {- fsPromises.mkdir = mkdir;- }-- assert.equal(servedDuringExtraction.length > 0, true);- assert.deepEqual(- servedDuringExtraction.filter((present) => !present),- [],- );- assert.equal(repaired.directory, installed.directory);- assert.equal(readFileSync(corrupted, 'utf8'), 'renderer one');- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), true);- assert.deepEqual(- readdirSync(store.storeRoot).filter((name) => name.startsWith('.')),- [],- );- const index = await store.buildModuleIndex();- assert.deepEqual([...index.keys()].sort(), ['assets/index-v1.js', 'assets/style-v1.css']);- });-- test('a manifest below the highest metadata_version seen for its feed is refused as a downgrade', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await recordManifest(store, 7, 'd'.repeat(64));-- assert.throws(- () => store.requireManifestFresh(manifestObservation(6, 'e'.repeat(64))),- ModuleManifestRollbackError,- );- await assert.rejects(recordManifest(store, 6, 'e'.repeat(64)), ModuleManifestRollbackError);-- const highWater = readState(userDataPath).manifest_high_water;- assert.equal(highWater.length, 1);- assert.equal(highWater[0].metadata_version, 7);- assert.equal(highWater[0].manifest_sha256, 'd'.repeat(64));- await recordManifest(store, 8, 'f'.repeat(64));- assert.equal(readState(userDataPath).manifest_high_water[0].metadata_version, 8);- });-- test('a second manifest body at an already seen metadata_version is refused as equivocation', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await recordManifest(store, 7, 'd'.repeat(64));-- assert.throws(- () => store.requireManifestFresh(manifestObservation(7, 'e'.repeat(64))),- ModuleManifestEquivocationError,- );- await assert.rejects(recordManifest(store, 7, 'e'.repeat(64)), ModuleManifestEquivocationError);-- store.requireManifestFresh(manifestObservation(7, 'd'.repeat(64)));- await recordManifest(store, 7, 'd'.repeat(64));- const highWater = readState(userDataPath).manifest_high_water;- assert.equal(highWater.length, 1);- assert.equal(highWater[0].manifest_sha256, 'd'.repeat(64));- });-- test('a superseded launch attempt cannot clear the boot counter that drives rollback', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const superseded = await store.recordLaunchAttempt();- const active = await store.recordLaunchAttempt();-- assert.equal(await store.markLaunchAttemptSucceeded(superseded), false);- assert.equal(readState(userDataPath).boot_attempt, 2);- assert.equal(store.getState().boot_attempt, 2);-- assert.equal(await store.markLaunchAttemptSucceeded(active), true);- assert.equal(readState(userDataPath).boot_attempt, 0);- });-- test('a store directory whose module.json names another module is not an installation of it', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const renderer = await install(store, RENDERER_V1);- const impostor = store.getModuleDirectory('fluxer_grammars', RENDERER_V1.sha256);- mkdirSync(path.dirname(impostor), {recursive: true});- cpSync(renderer.directory, impostor, {recursive: true});-- assert.equal(await store.isInstalled('fluxer_grammars', RENDERER_V1.sha256), false);- assert.equal(await store.getInstalledManifest('fluxer_grammars', RENDERER_V1.sha256), null);- await assert.rejects(store.commit({fluxer_grammars: RENDERER_V1.sha256}), ModuleStoreInstallationMissingError);- });-- test('a symlinked store directory is never served, even when it points at a real installation', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const renderer = await install(store, RENDERER_V1);- const outside = path.join(userDataPath, 'outside-the-store');- cpSync(renderer.directory, outside, {recursive: true});- const linkedSha256 = 'b'.repeat(64);- const linked = store.getModuleDirectory('fluxer_renderer', linkedSha256);- symlinkSync(outside, linked, 'dir');- assert.equal(existsSync(path.join(linked, 'module.json')), true);-- assert.equal(await store.isInstalled('fluxer_renderer', linkedSha256), false);- await assert.rejects(store.commit({fluxer_renderer: linkedSha256}), ModuleStoreInstallationMissingError);- });-- test('an index built over a deleted committed module fails loudly', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await rm(installed.directory, {recursive: true, force: true});-- await assert.rejects(store.buildModuleIndex(), ModuleStoreInstallationMissingError);- });-});--function chunksOf(buffer) {- return (async function* stream() {- for (let offset = 0; offset < buffer.length; offset += 4096) {- yield buffer.subarray(offset, Math.min(offset + 4096, buffer.length));- }- })();-}--function interruptedAfter(buffer, bytes) {- return (async function* stream() {- yield buffer.subarray(0, bytes);- throw new Error('connection reset');- })();-}--describe('ModuleStore resumable package downloads', () => {- test('an interrupted download keeps its bytes and the next attempt resumes from them', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const cut = Math.floor(RENDERER_V1.packed.length / 2);- const offsets = [];- await assert.rejects(- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: (resumeFrom) => {- offsets.push(resumeFrom);- return {offset: 0, chunks: interruptedAfter(RENDERER_V1.packed, cut)};- },- }),- );- assert.equal(readFileSync(store.getPartialPackagePath(RENDERER_V1.sha256)).length, cut);-- const installed = await store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: (resumeFrom) => {- offsets.push(resumeFrom);- return {offset: resumeFrom, chunks: chunksOf(RENDERER_V1.packed.subarray(resumeFrom))};- },- });-- assert.deepEqual(offsets, [0, cut]);- assert.equal(existsSync(path.join(installed.directory, 'module.json')), true);- assert.equal(existsSync(store.getPartialPackagePath(RENDERER_V1.sha256)), false);- assert.equal(existsSync(store.getPackagePath(RENDERER_V1.sha256)), true);- });-- test('a server that ignores the range restarts the download from the first byte', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- mkdirSync(store.incomingDownloadRoot, {recursive: true});- writeFileSync(store.getPartialPackagePath(RENDERER_V1.sha256), RENDERER_V1.packed.subarray(0, 100));-- const installed = await store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: () => ({offset: 0, chunks: chunksOf(RENDERER_V1.packed)}),- });-- assert.equal(existsSync(path.join(installed.directory, 'module.json')), true);- });-- test('a resumed partial that does not hash to the package is dropped so the retry starts clean', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- mkdirSync(store.incomingDownloadRoot, {recursive: true});- const partial = store.getPartialPackagePath(RENDERER_V1.sha256);- writeFileSync(partial, Buffer.alloc(100, 7));-- await assert.rejects(- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: (resumeFrom) => ({offset: resumeFrom, chunks: chunksOf(RENDERER_V1.packed.subarray(resumeFrom))}),- }),- ModuleStoreDownloadHashMismatchError,- );- assert.equal(existsSync(partial), false);- });-- test('a download that resumes at an offset nobody asked for is refused', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);-- await assert.rejects(- store.installModule({- module: 'fluxer_renderer',- sha256: RENDERER_V1.sha256,- download: () => ({offset: 10, chunks: chunksOf(RENDERER_V1.packed.subarray(10))}),- }),- /resumed at byte 10, expected 0/u,- );- });-});--describe('ModuleStore rejected module sets', () => {- async function bootTwiceWithoutReady(userDataPath) {- for (let boot = 0; boot < 2; boot += 1) {- const store = await openStore(userDataPath);- await store.beginBootAttempt();- await store.recordLaunchAttempt();- }- return await openStore(userDataPath);- }-- test('a rollback that reverts remembers the module set it rejected', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});-- const rebooted = await bootTwiceWithoutReady(userDataPath);- const attempt = await rebooted.beginBootAttempt();-- assert.equal(attempt.rolledBack, true);- assert.deepEqual(readState(userDataPath).rejected, {fluxer_renderer: RENDERER_V2.sha256});- assert.equal(rebooted.isRejected('fluxer_renderer', RENDERER_V2.sha256), true);- assert.equal(rebooted.isRejected('fluxer_renderer', RENDERER_V1.sha256), false);- });-- test('the rejection holds while the manifest still advertises that build and clears once it moves on', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await install(store, RENDERER_V2);- await store.commit({fluxer_renderer: RENDERER_V2.sha256});- const rebooted = await bootTwiceWithoutReady(userDataPath);- await rebooted.beginBootAttempt();-- await rebooted.recordManifestFetch({- etag: null,- fetchedAt: MANIFEST_FETCHED_AT,- manifest: manifestObservation(1, 'a'.repeat(64)),- advertised: {fluxer_renderer: RENDERER_V2.sha256},- });- assert.equal(rebooted.isRejected('fluxer_renderer', RENDERER_V2.sha256), true);-- await rebooted.recordManifestFetch({- etag: null,- fetchedAt: MANIFEST_FETCHED_AT,- manifest: manifestObservation(2, 'b'.repeat(64)),- advertised: {fluxer_renderer: 'c'.repeat(64)},- });- assert.equal(rebooted.isRejected('fluxer_renderer', RENDERER_V2.sha256), false);- assert.deepEqual(readState(userDataPath).rejected, {});- });-- test('a state file written before rejections existed still opens', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const statePath = path.join(store.root, MODULE_STATE_FILE_NAME);- const legacy = readState(userDataPath);- delete legacy.rejected;- writeFileSync(statePath, JSON.stringify(legacy));-- const reopened = await openStore(userDataPath);-- assert.deepEqual(reopened.getState().rejected, {});- });-});--describe('ModuleStore shell ranges beside older shells', () => {- test('state written by this shell stays readable by shells that require linux_security_minimum', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});-- const written = readState(userDataPath);-- assert.equal(Object.hasOwn(written, 'linux_security_minimum'), true);- assert.equal(written.linux_security_minimum, null);- assert.equal(written.state_version, MODULE_STATE_VERSION);- });-- test('state that persisted a security minimum still opens', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const legacy = readState(userDataPath);- legacy.linux_security_minimum = {version: '2026.900.1', required_modules: ['fluxer_renderer']};- delete legacy.shell_ranges;- writeFileSync(path.join(store.root, MODULE_STATE_FILE_NAME), JSON.stringify(legacy));-- const reopened = await openStore(userDataPath);-- assert.equal(reopened.recoveredUnreadableState, null);- assert.deepEqual(reopened.getCommitted(), {fluxer_renderer: RENDERER_V1.sha256});- assert.deepEqual(reopened.getState().shell_ranges, {});- await reopened.commit({fluxer_renderer: RENDERER_V1.sha256});- assert.equal(readState(userDataPath).linux_security_minimum, null);- });-- test('shell ranges survive a reopen and garbage collection prunes them', async () => {- const userDataPath = createUserData();- const earlierRun = await openStore(userDataPath);- await install(earlierRun, RENDERER_V1);- await earlierRun.commit({fluxer_renderer: RENDERER_V1.sha256});- const orphan = await install(earlierRun, GRAMMARS_V1);- await earlierRun.recordShellRanges([- {module: 'fluxer_renderer', sha256: RENDERER_V1.sha256, minimum: SHELL_VERSION, maximum: null},- {module: 'fluxer_grammars', sha256: GRAMMARS_V1.sha256, minimum: null, maximum: '2026.900.1'},- {module: 'fluxer_renderer', sha256: 'd'.repeat(64), minimum: '2026.900.1', maximum: null},- ]);- const store = await openStore(userDataPath);-- assert.deepEqual(store.getShellRange('fluxer_renderer', RENDERER_V1.sha256), {- minimum_shell_version: SHELL_VERSION,- maximum_shell_version: null,- });- assert.deepEqual(store.getShellRange('fluxer_grammars', GRAMMARS_V1.sha256), {- minimum_shell_version: null,- maximum_shell_version: '2026.900.1',- });-- await markLaunched(store);- await store.collectGarbage();-- assert.equal(existsSync(orphan.directory), false);- assert.deepEqual(Object.keys(readState(userDataPath).shell_ranges), [`fluxer_renderer/${RENDERER_V1.sha256}`]);- assert.equal(store.getShellRange('fluxer_grammars', GRAMMARS_V1.sha256), null);- });-- test('a recorded range that no longer parses is dropped instead of discarding the state', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const state = readState(userDataPath);- state.shell_ranges = {- [`fluxer_renderer/${'d'.repeat(64)}`]: {minimum_shell_version: 'not a version', maximum_shell_version: null},- [`fluxer_renderer/${'e'.repeat(64)}`]: {minimum_shell_version: SHELL_VERSION, maximum_shell_version: null},- };- writeFileSync(path.join(store.root, MODULE_STATE_FILE_NAME), JSON.stringify(state));-- const reopened = await openStore(userDataPath);-- assert.equal(reopened.recoveredUnreadableState, null);- assert.deepEqual(Object.keys(reopened.getState().shell_ranges), [`fluxer_renderer/${'e'.repeat(64)}`]);- });-- test('retireIncompatible drops non-runnable pairs from committed, previous and floor', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await install(store, RENDERER_V2);- await install(store, GRAMMARS_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await store.commit({fluxer_renderer: RENDERER_V2.sha256, fluxer_grammars: GRAMMARS_V1.sha256});- await store.recordManifestFetch({- etag: null,- fetchedAt: MANIFEST_FETCHED_AT,- manifest: manifestObservation(1, 'a'.repeat(64)),- floor: {fluxer_renderer: RENDERER_V2.sha256, fluxer_grammars: GRAMMARS_V1.sha256},- });-- const retired = await store.retireIncompatible(- (moduleName, digest) => !(moduleName === 'fluxer_renderer' && digest === RENDERER_V2.sha256),- );-- assert.deepEqual(retired, ['fluxer_renderer']);- assert.deepEqual(store.getCommitted(), {fluxer_grammars: GRAMMARS_V1.sha256});- assert.deepEqual(store.getState().previous, {fluxer_renderer: RENDERER_V1.sha256});- assert.deepEqual(store.getState().floor, {fluxer_grammars: GRAMMARS_V1.sha256});- assert.deepEqual(await store.retireIncompatible(() => true), []);- });-});--describe('ModuleStore on Windows sharing violations', () => {- test('a rename that an antivirus scanner briefly locks is retried instead of failing the install', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const platform = Object.getOwnPropertyDescriptor(process, 'platform');- const rename = fsPromises.rename;- let failures = 0;- Object.defineProperty(process, 'platform', {...platform, value: 'win32'});- fsPromises.rename = async (...args) => {- if (failures < 2) {- failures += 1;- throw Object.assign(new Error('operation not permitted'), {code: 'EPERM'});- }- return await rename(...args);- };- try {- await store.recordLaunchAttempt();- } finally {- fsPromises.rename = rename;- Object.defineProperty(process, 'platform', platform);- }-- assert.equal(failures, 2);- assert.equal(readState(userDataPath).boot_attempt, 1);- });-- test('the same lock on another platform is not retried', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const rename = fsPromises.rename;- let calls = 0;- fsPromises.rename = async () => {- calls += 1;- throw Object.assign(new Error('operation not permitted'), {code: 'EPERM'});- };- try {- await assert.rejects(store.recordLaunchAttempt(), /failed to publish/u);- } finally {- fsPromises.rename = rename;- }-- assert.equal(calls, process.platform === 'win32' ? 7 : 1);- });-});--describe('ModuleStore boot checks without rehashing', () => {- async function countServedFileOpens(directory, operation) {- const open = fsPromises.open;- const opened = [];- fsPromises.open = async (target, ...rest) => {- if (- typeof target === 'string' &&- target.startsWith(`${directory}${path.sep}`) &&- path.basename(target) !== 'module.json' &&- !path.basename(target).startsWith(MODULE_FILE_STAMPS_NAME)- ) {- opened.push(target);- }- return await open(target, ...rest);- };- try {- return {result: await operation(), opened};- } finally {- fsPromises.open = open;- }- }-- test('an installed module is trusted from its persisted file stamps without reading a served file', async () => {- const userDataPath = createUserData();- const first = await openStore(userDataPath);- const installed = await install(first, RENDERER_V1);- await first.commit({fluxer_renderer: RENDERER_V1.sha256});- assert.equal(existsSync(path.join(installed.directory, MODULE_FILE_STAMPS_NAME)), true);-- const store = await openStore(userDataPath);- const {result, opened} = await countServedFileOpens(installed.directory, async () => {- const isInstalled = await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256);- const index = await store.buildModuleIndex();- return {isInstalled, index};- });-- assert.equal(result.isInstalled, true);- assert.deepEqual([...result.index.keys()].sort(), ['assets/index-v1.js', 'assets/style-v1.css']);- assert.deepEqual(opened, []);- });-- test('a fresh install launches from its in-memory stamps and persists them only once the tree is durable', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await store.installModule({- module: RENDERER_V1.module,- sha256: RENDERER_V1.sha256,- download: () => streamOf(RENDERER_V1.packed),- });- const stampsPath = path.join(installed.directory, MODULE_FILE_STAMPS_NAME);- assert.equal(existsSync(stampsPath), false);-- const {result, opened} = await countServedFileOpens(installed.directory, async () => {- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- return await store.buildModuleIndex();- });- assert.deepEqual([...result.keys()].sort(), ['assets/index-v1.js', 'assets/style-v1.css']);- assert.deepEqual(opened, []);- assert.equal(existsSync(stampsPath), false);-- const attempt = await store.recordLaunchAttempt();- assert.equal(await store.markLaunchAttemptSucceeded(attempt), true);- await store.settleInstalledModules();- assert.equal(existsSync(stampsPath), true);- const reopened = await openStore(userDataPath);- const later = await countServedFileOpens(installed.directory, () =>- reopened.isInstalled('fluxer_renderer', RENDERER_V1.sha256),- );- assert.equal(later.result, true);- assert.deepEqual(later.opened, []);- });-- test('a served file rewritten with the same length and its old mtime is still caught', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const served = path.join(installed.directory, 'assets', 'index-v1.js');- const before = await fsPromises.stat(served);- await new Promise((resolve) => setTimeout(resolve, 20));- writeFileSync(served, 'RENDERER ONE');- utimesSync(served, before.atime, before.mtime);-- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);- await assert.rejects(store.buildModuleIndex(), ModuleStoreInstallationMissingError);- });-- test('a deleted served file is caught without hashing the rest of the module', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- await rm(path.join(installed.directory, 'assets', 'style-v1.css'));-- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);- });-- test('an installation without stamps is hashed once and then trusted from the stamps it wrote', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const stampsPath = path.join(installed.directory, MODULE_FILE_STAMPS_NAME);- await rm(stampsPath);-- const firstPass = await countServedFileOpens(installed.directory, () =>- store.isInstalled('fluxer_renderer', RENDERER_V1.sha256),- );- assert.equal(firstPass.result, true);- assert.equal(firstPass.opened.length, 2);- assert.equal(existsSync(stampsPath), true);-- const secondPass = await countServedFileOpens(installed.directory, () =>- store.isInstalled('fluxer_renderer', RENDERER_V1.sha256),- );- assert.equal(secondPass.result, true);- assert.deepEqual(secondPass.opened, []);- });-- test('unreadable or foreign stamps fall back to hashing instead of trusting the tree', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const installed = await install(store, RENDERER_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const stampsPath = path.join(installed.directory, MODULE_FILE_STAMPS_NAME);- const stamps = JSON.parse(readFileSync(stampsPath, 'utf8'));- const served = path.join(installed.directory, 'assets', 'index-v1.js');- writeFileSync(served, 'RENDERER ONE');- const tampered = await fsPromises.lstat(served);- const forged = {- ...stamps,- manifest_sha256: 'f'.repeat(64),- files: {- ...stamps.files,- 'assets/index-v1.js': [tampered.size, tampered.mtimeMs, tampered.ctimeMs, tampered.ino],- },- };- writeFileSync(stampsPath, JSON.stringify(forged));-- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);-- writeFileSync(stampsPath, 'not json');- assert.equal(await store.isInstalled('fluxer_renderer', RENDERER_V1.sha256), false);- });-});--describe('ModuleStore beside a renderer bundled in the shell', () => {- test('an unreadable state file is set aside and the store starts clean', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const statePath = path.join(getModuleStoreRoot(userDataPath), MODULE_STATE_FILE_NAME);- for (const contents of ['{not json', JSON.stringify({state_version: 1})]) {- writeFileSync(statePath, contents);-- const recovered = await openStore(userDataPath);-- assert.equal(recovered.recoveredUnreadableState, `${statePath}.unreadable`);- assert.equal(readFileSync(`${statePath}.unreadable`, 'utf8'), contents);- assert.deepEqual(recovered.getCommitted(), {});- assert.equal(readState(userDataPath).state_version, MODULE_STATE_VERSION);- }- assert.equal(store.recoveredUnreadableState, null);- });-- test('retiring a module drops it from the committed and previous sets so it can be collected', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const first = await install(store, RENDERER_V1);- const second = await install(store, RENDERER_V2);- await install(store, GRAMMARS_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256, fluxer_grammars: GRAMMARS_V1.sha256});- await store.commit({fluxer_renderer: RENDERER_V2.sha256, fluxer_grammars: GRAMMARS_V1.sha256});-- assert.equal(await store.retireModule('fluxer_renderer'), true);- assert.equal(await store.retireModule('fluxer_renderer'), false);-- assert.deepEqual(readState(userDataPath).committed, {fluxer_grammars: GRAMMARS_V1.sha256});- assert.deepEqual(readState(userDataPath).previous, {fluxer_grammars: GRAMMARS_V1.sha256});- await markLaunched(store);- await store.collectGarbage();- assert.equal(existsSync(first.directory), false);- assert.equal(existsSync(second.directory), false);- assert.equal(await store.isInstalled('fluxer_grammars', GRAMMARS_V1.sha256), true);- });-- test('two failed boots of a first renderer module fall back to the bundle instead of looping', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await install(store, GRAMMARS_V1);- await store.commit({fluxer_grammars: GRAMMARS_V1.sha256});- await store.activateMergedForRendererReload({fluxer_renderer: RENDERER_V1.sha256});- await store.commit({fluxer_renderer: RENDERER_V1.sha256, fluxer_grammars: GRAMMARS_V1.sha256});- const state = readState(userDataPath);- writeFileSync(- path.join(getModuleStoreRoot(userDataPath), MODULE_STATE_FILE_NAME),- JSON.stringify({...state, previous: {}, boot_attempt: 2}),- );- const reopened = await openStore(userDataPath);-- const withoutBundle = await reopened.beginBootAttempt();- assert.equal(withoutBundle.rolledBack, false);- writeFileSync(- path.join(getModuleStoreRoot(userDataPath), MODULE_STATE_FILE_NAME),- JSON.stringify({...readState(userDataPath), boot_attempt: 2}),- );- const bundled = await openStore(userDataPath);-- const attempt = await bundled.beginBootAttempt({bundled: ['fluxer_renderer']});-- assert.equal(attempt.rolledBack, true);- assert.deepEqual(attempt.committed, {fluxer_grammars: GRAMMARS_V1.sha256});- assert.equal(bundled.isRejected('fluxer_renderer', RENDERER_V1.sha256), true);- assert.equal(readState(userDataPath).boot_attempt, 0);- });-- test('a renderer update that never confirms is reverted and rejected', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- await install(store, RENDERER_V1);- await install(store, RENDERER_V2);- await install(store, GRAMMARS_V1);- await store.commit({fluxer_renderer: RENDERER_V1.sha256});- const attempt = await store.activateMergedForRendererReload({- fluxer_renderer: RENDERER_V2.sha256,- fluxer_grammars: GRAMMARS_V1.sha256,- });-- assert.deepEqual(await store.revertLaunchAttempt(attempt, ['fluxer_renderer']), {- fluxer_renderer: RENDERER_V1.sha256,- fluxer_grammars: GRAMMARS_V1.sha256,- });- assert.equal(store.isRejected('fluxer_renderer', RENDERER_V2.sha256), true);- assert.equal(store.isRejected('fluxer_grammars', GRAMMARS_V1.sha256), false);- assert.equal(await store.revertLaunchAttempt(attempt, ['fluxer_renderer']), null);-- const first = await store.activateMergedForRendererReload({fluxer_renderer: RENDERER_V2.sha256});- await store.revertLaunchAttempt(first, ['fluxer_renderer']);- await store.retireModule('fluxer_renderer');- const onBundle = await store.activateMergedForRendererReload({fluxer_renderer: RENDERER_V1.sha256});- assert.deepEqual(await store.revertLaunchAttempt(onBundle, ['fluxer_renderer']), {- fluxer_grammars: GRAMMARS_V1.sha256,- });- });-});diff --git a/fluxer_desktop/src/main/ModuleUpdatePlanner.test.mjs b/fluxer_desktop/src/main/ModuleUpdatePlanner.test.mjsdeleted file mode 100644index 014153edb..000000000--- a/fluxer_desktop/src/main/ModuleUpdatePlanner.test.mjs+++ /dev/null@@ -1,521 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {parseModuleUpdateManifest} = await import('@electron/main/ModuleManifest');-const {MODULE_BOOT_ATTEMPT_ROLLBACK_THRESHOLD} = await import('@electron/main/ModuleStore');-const {ModuleUnreachableLaunchDecision, ModuleUpdatePlanner, ModuleUpdaterBlockReason} = await import(- '@electron/main/ModuleUpdatePlanner'-);-const {parseModuleVersion} = await import('@electron/main/ModuleVersion');--const SHELL_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const PLATFORM = 'darwin';-const ARCH = 'arm64';-const FETCHED_AT = '2026-08-23T00:00:00.000Z';-const RENDERER_SHA = 'a'.repeat(64);-const OVERLAY_SHA = 'b'.repeat(64);--const TARGET = {releaseChannel: RELEASE_CHANNEL, platform: PLATFORM, arch: ARCH};--function manifest({shellMinimum = SHELL_VERSION, modules = {}, required = null} = {}) {- const entries = Object.entries(modules);- return parseModuleUpdateManifest(- Buffer.from(- JSON.stringify({- manifest_version: 1,- release_channel: RELEASE_CHANNEL,- platform: PLATFORM,- arch: ARCH,- build_version: SHELL_VERSION,- pub_date: FETCHED_AT,- metadata_version: 1,- shell: {latest_version: SHELL_VERSION, minimum_version: shellMinimum},- modules: Object.fromEntries(- entries.map(([moduleName, entry]) => [- moduleName,- {- sha256: entry.sha256,- bytes: 1024,- url: `https://api.invalid/dl/desktop/${entry.sha256}.br`,- minimum_shell_version: entry.minimumShellVersion ?? null,- maximum_shell_version: entry.maximumShellVersion ?? null,- },- ]),- ),- required_modules: required ?? entries.map(([moduleName]) => moduleName),- }),- 'utf8',- ),- TARGET,- );-}--function createStore({- committed = {},- floor = {},- rejected = {},- lastManifestFetch = FETCHED_AT,- bootAttempt = 0,- missing = [],- installedManifests = {},- shellRanges = {},-} = {}) {- const absent = new Set(missing);- return {- getState: () => ({- committed,- floor,- rejected,- last_manifest_fetch: lastManifestFetch,- boot_attempt: bootAttempt,- }),- getCommitted: () => committed,- isRejected: (moduleName, sha256) => rejected[moduleName] === sha256,- isInstalled: async (moduleName, sha256) => !absent.has(`${moduleName}:${sha256}`),- getInstalledManifest: async (moduleName, sha256) => installedManifests[`${moduleName}:${sha256}`] ?? null,- getShellRange: (moduleName, sha256) => shellRanges[`${moduleName}/${sha256}`] ?? null,- };-}--function createPlanner(- store,- {shellVersion = SHELL_VERSION, hasOfflineRenderer = false, bundledRendererVersion = null} = {},-) {- return new ModuleUpdatePlanner(- store,- parseModuleVersion(shellVersion, 'desktop shell version'),- hasOfflineRenderer,- bundledRendererVersion == null ? null : parseModuleVersion(bundledRendererVersion, 'bundled renderer version'),- );-}--function bundledPlanner(store, bundledRendererVersion = SHELL_VERSION) {- return createPlanner(store, {hasOfflineRenderer: true, bundledRendererVersion});-}--function installedRenderer(sha256, buildVersion) {- return {[`fluxer_renderer:${sha256}`]: {build_version: buildVersion}};-}--describe('ModuleUpdatePlanner.isShellCompatible', () => {- test('an entry with no shell bounds is compatible', () => {- const planner = createPlanner(createStore());- assert.equal(planner.isShellCompatible({minimumShellVersion: null, maximumShellVersion: null}), true);- });-- test('the shell floor and ceiling are inclusive', () => {- const planner = createPlanner(createStore());- const bound = parseModuleVersion(SHELL_VERSION, 'bound');- assert.equal(planner.isShellCompatible({minimumShellVersion: bound, maximumShellVersion: null}), true);- assert.equal(planner.isShellCompatible({minimumShellVersion: null, maximumShellVersion: bound}), true);- });-- test('a shell below the entry floor is incompatible', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.isShellCompatible({- minimumShellVersion: parseModuleVersion('2026.824.0', 'floor'),- maximumShellVersion: null,- }),- false,- );- });-- test('a shell above the entry ceiling is incompatible', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.isShellCompatible({- minimumShellVersion: null,- maximumShellVersion: parseModuleVersion('2026.823.0', 'ceiling'),- }),- false,- );- });-- test('a prerelease shell does not satisfy the release it precedes', () => {- const planner = createPlanner(createStore(), {shellVersion: '2026.823.1-rc.1'});- assert.equal(- planner.isShellCompatible({- minimumShellVersion: parseModuleVersion(SHELL_VERSION, 'floor'),- maximumShellVersion: null,- }),- false,- );- });-});--describe('ModuleUpdatePlanner.shellUpdateRequired', () => {- test('a manifest whose shell floor matches this shell asks for nothing', () => {- const planner = createPlanner(createStore());- assert.equal(planner.shellUpdateRequired(manifest({modules: {fluxer_renderer: {sha256: RENDERER_SHA}}})), false);- });-- test('a shell floor above this shell requires a shell update', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.shellUpdateRequired(- manifest({shellMinimum: '2026.824.0', modules: {fluxer_renderer: {sha256: RENDERER_SHA}}}),- ),- true,- );- });-- test('a required module that outruns this shell requires a shell update', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.shellUpdateRequired(- manifest({modules: {fluxer_renderer: {sha256: RENDERER_SHA, minimumShellVersion: '2026.824.0'}}}),- ),- true,- );- });-- test('a required module capped below this shell requires a shell update', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.shellUpdateRequired(- manifest({modules: {fluxer_renderer: {sha256: RENDERER_SHA, maximumShellVersion: '2026.823.0'}}}),- ),- true,- );- });-- test('an optional module that outruns this shell does not require a shell update', () => {- const planner = createPlanner(createStore());- assert.equal(- planner.shellUpdateRequired(- manifest({- modules: {- fluxer_renderer: {sha256: RENDERER_SHA},- fluxer_overlay: {sha256: OVERLAY_SHA, minimumShellVersion: '2026.824.0'},- },- required: ['fluxer_renderer'],- }),- ),- false,- );- });-});--describe('ModuleUpdatePlanner.plan', () => {- test('a shell-incompatible optional module keeps its committed copy instead of updating', async () => {- const store = createStore({committed: {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA}});- const planner = createPlanner(store);- const plan = await planner.plan(- manifest({- modules: {- fluxer_renderer: {sha256: RENDERER_SHA},- fluxer_overlay: {sha256: 'c'.repeat(64), minimumShellVersion: '2026.824.0'},- },- required: ['fluxer_renderer'],- }),- );-- assert.deepEqual(plan.items, []);- assert.deepEqual(plan.base, {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA});- });-- test('a shell-incompatible optional module that is not installed is dropped entirely', async () => {- const store = createStore({- committed: {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA},- missing: [`fluxer_overlay:${OVERLAY_SHA}`],- });- const planner = createPlanner(store);- const plan = await planner.plan(- manifest({- modules: {- fluxer_renderer: {sha256: RENDERER_SHA},- fluxer_overlay: {sha256: 'c'.repeat(64), maximumShellVersion: '2026.823.0'},- },- required: ['fluxer_renderer'],- }),- );-- assert.deepEqual(plan.items, []);- assert.deepEqual(plan.base, {fluxer_renderer: RENDERER_SHA});- });-- test('plan keeps the committed renderer and assets when the feed renderer needs a newer shell', async () => {- const dictionarySha = 'd'.repeat(64);- const store = createStore({committed: {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA}});- const planner = createPlanner(store);- const plan = await planner.plan(- manifest({- modules: {- fluxer_renderer: {sha256: 'c'.repeat(64), minimumShellVersion: '2026.900.1'},- fluxer_overlay: {sha256: 'e'.repeat(64)},- fluxer_dict_en: {sha256: dictionarySha},- },- required: ['fluxer_renderer', 'fluxer_dict_en'],- }),- );-- assert.deepEqual(- plan.items.map((item) => [item.module, item.entry.sha256, item.requirement]),- [['fluxer_dict_en', dictionarySha, 'required']],- );- assert.deepEqual(plan.base, {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA});- });-});--describe('ModuleUpdatePlanner.compatibleEntry', () => {- test('a shell below the manifest shell floor gets no entry even when the entry has no floor', () => {- const planner = createPlanner(createStore());- const feed = manifest({shellMinimum: '2026.900.1', modules: {fluxer_renderer: {sha256: RENDERER_SHA}}});-- assert.equal(planner.compatibleEntry(feed, 'fluxer_renderer'), null);- });-- test('an entry inside its shell range is returned, one outside or missing is not', () => {- const planner = createPlanner(createStore());- const feed = manifest({- shellMinimum: '0.0.0',- modules: {- fluxer_renderer: {sha256: RENDERER_SHA, minimumShellVersion: SHELL_VERSION},- fluxer_overlay: {sha256: OVERLAY_SHA, minimumShellVersion: '2026.900.1'},- },- });-- assert.equal(planner.compatibleEntry(feed, 'fluxer_renderer')?.sha256, RENDERER_SHA);- assert.equal(planner.compatibleEntry(feed, 'fluxer_overlay'), null);- assert.equal(planner.compatibleEntry(feed, 'toString'), null);- });-});--describe('ModuleUpdatePlanner.isRunnable', () => {- const cachedFeed = () =>- manifest({- shellMinimum: '0.0.0',- modules: {fluxer_renderer: {sha256: RENDERER_SHA, minimumShellVersion: '2026.900.1'}},- });-- test('a module with no record and no cached entry is runnable', () => {- const planner = createPlanner(createStore());-- assert.equal(planner.isRunnable('fluxer_renderer', RENDERER_SHA, null), true);- });-- test('a recorded range this shell is outside of is not runnable', () => {- const planner = createPlanner(- createStore({- shellRanges: {- [`fluxer_renderer/${RENDERER_SHA}`]: {minimum_shell_version: '2026.900.1', maximum_shell_version: null},- [`fluxer_overlay/${OVERLAY_SHA}`]: {minimum_shell_version: null, maximum_shell_version: '2026.823.0'},- },- }),- );-- assert.equal(planner.isRunnable('fluxer_renderer', RENDERER_SHA, null), false);- assert.equal(planner.isRunnable('fluxer_overlay', OVERLAY_SHA, null), false);- });-- test('a recorded range that ends on this shell is runnable', () => {- const planner = createPlanner(- createStore({- shellRanges: {- [`fluxer_renderer/${RENDERER_SHA}`]: {- minimum_shell_version: SHELL_VERSION,- maximum_shell_version: SHELL_VERSION,- },- },- }),- );-- assert.equal(planner.isRunnable('fluxer_renderer', RENDERER_SHA, cachedFeed()), true);- });-- test('the cached manifest stands in for a missing record only for the same sha', () => {- const planner = createPlanner(createStore());-- assert.equal(planner.isRunnable('fluxer_renderer', RENDERER_SHA, cachedFeed()), false);- assert.equal(planner.isRunnable('fluxer_renderer', 'f'.repeat(64), cachedFeed()), true);- });-});--describe('ModuleUpdatePlanner.evaluateUnreachableLaunch', () => {- test('a store that never reached the manifest feed blocks with nothing-installed', async () => {- const planner = createPlanner(createStore({committed: {fluxer_renderer: RENDERER_SHA}, lastManifestFetch: null}));-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.BLOCK,- reason: ModuleUpdaterBlockReason.NOTHING_INSTALLED,- });- });-- test('an empty committed set with no offline renderer blocks with nothing-installed', async () => {- const planner = createPlanner(createStore({committed: {}}));-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.BLOCK,- reason: ModuleUpdaterBlockReason.NOTHING_INSTALLED,- });- });-- test('an offline renderer carries an empty committed set past the nothing-installed block', async () => {- const planner = createPlanner(createStore({committed: {}}), {hasOfflineRenderer: true});-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.LAUNCH,- });- });-- test('one boot attempt below the threshold still launches', async () => {- const planner = createPlanner(- createStore({- committed: {fluxer_renderer: RENDERER_SHA},- bootAttempt: MODULE_BOOT_ATTEMPT_ROLLBACK_THRESHOLD - 1,- }),- );-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.LAUNCH,- });- });-- test('a committed set behind the floor blocks only while startup updates are enforced', async () => {- const store = createStore({- committed: {fluxer_renderer: RENDERER_SHA},- floor: {fluxer_renderer: 'c'.repeat(64)},- });- const planner = createPlanner(store);-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.BLOCK,- reason: ModuleUpdaterBlockReason.UNREACHABLE_BELOW_FLOOR,- });- assert.deepEqual(await planner.evaluateUnreachableLaunch(false), {- kind: ModuleUnreachableLaunchDecision.LAUNCH,- });- });-- test('a committed module that is no longer on disk blocks with unreachable-below-floor', async () => {- const planner = createPlanner(- createStore({- committed: {fluxer_renderer: RENDERER_SHA},- missing: [`fluxer_renderer:${RENDERER_SHA}`],- }),- );-- assert.deepEqual(await planner.evaluateUnreachableLaunch(false), {- kind: ModuleUnreachableLaunchDecision.BLOCK,- reason: ModuleUpdaterBlockReason.UNREACHABLE_BELOW_FLOOR,- });- });-- test('a healthy committed set launches while the feed is unreachable', async () => {- const planner = createPlanner(- createStore({- committed: {fluxer_renderer: RENDERER_SHA},- floor: {fluxer_renderer: RENDERER_SHA},- }),- );-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.LAUNCH,- });- });-});--describe('ModuleUpdatePlanner with a renderer bundled in the shell', () => {- const OLDER = '2026.822.9';- const NEWER = '2026.824.1';-- test('a feed renderer no newer than the bundle is never planned or pending', async () => {- const planner = bundledPlanner(createStore());- const feed = manifest({modules: {fluxer_renderer: {sha256: RENDERER_SHA}}});-- assert.equal(planner.bundleCoversModule('fluxer_renderer', feed), true);- assert.deepEqual(await planner.plan(feed), {items: [], base: {}});- });-- test('a feed renderer newer than the bundle is downloaded but never required to launch', async () => {- const planner = bundledPlanner(createStore(), OLDER);- const feed = manifest({modules: {fluxer_renderer: {sha256: RENDERER_SHA}}});-- assert.equal(planner.bundleCoversModule('fluxer_renderer', feed), false);- const plan = await planner.plan(feed);- assert.deepEqual(- plan.items.map((item) => [item.module, item.requirement]),- [['fluxer_renderer', 'optional']],- );- });-- test('the bundle only ever stands in for the renderer module', async () => {- const planner = bundledPlanner(createStore());- const feed = manifest({modules: {fluxer_overlay: {sha256: OVERLAY_SHA}}});-- assert.equal(planner.bundleCoversModule('fluxer_overlay', feed), false);- assert.equal((await planner.plan(feed)).items.length, 1);- });-- test('a committed renderer older than or equal to the bundle is stale, a newer one is not', async () => {- for (const [installedVersion, stale] of [- [OLDER, true],- [SHELL_VERSION, true],- [NEWER, false],- ]) {- const planner = bundledPlanner(- createStore({- committed: {fluxer_renderer: RENDERER_SHA},- installedManifests: installedRenderer(RENDERER_SHA, installedVersion),- }),- );- assert.equal(await planner.staleRendererModule(), stale ? RENDERER_SHA : null, installedVersion);- }- });-- test('a committed renderer whose installation is unreadable is stale', async () => {- const planner = bundledPlanner(createStore({committed: {fluxer_renderer: RENDERER_SHA}}));-- assert.equal(await planner.staleRendererModule(), RENDERER_SHA);- });-- test('without a bundle no committed renderer is ever stale', async () => {- const planner = createPlanner(- createStore({- committed: {fluxer_renderer: RENDERER_SHA},- installedManifests: installedRenderer(RENDERER_SHA, OLDER),- }),- );-- assert.equal(await planner.staleRendererModule(), null);- });-- test('serving drops an older renderer module and keeps every other module', async () => {- const planner = bundledPlanner(createStore({installedManifests: installedRenderer(RENDERER_SHA, OLDER)}));-- assert.deepEqual(await planner.selectServedModules({fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA}), {- modules: {fluxer_overlay: OVERLAY_SHA},- renderer: {source: 'bundled', version: SHELL_VERSION, bundledVersion: SHELL_VERSION},- });- });-- test('serving keeps a renderer module newer than the bundle', async () => {- const planner = bundledPlanner(createStore({installedManifests: installedRenderer(RENDERER_SHA, NEWER)}));- const modules = {fluxer_renderer: RENDERER_SHA};-- assert.deepEqual(await planner.selectServedModules(modules), {- modules,- renderer: {source: 'module', version: NEWER, bundledVersion: SHELL_VERSION},- });- });-- test('a renderer floor never holds the launch of a shell that bundles its renderer', async () => {- const planner = bundledPlanner(createStore({floor: {fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA}}));-- assert.deepEqual(await planner.modulesBelowFloor(true), ['fluxer_overlay']);- });-- test('a fresh install that never reached the feed launches the bundled renderer', async () => {- const planner = bundledPlanner(createStore({lastManifestFetch: null}));-- assert.deepEqual(await planner.evaluateUnreachableLaunch(true), {- kind: ModuleUnreachableLaunchDecision.LAUNCH,- });- });-});diff --git a/fluxer_desktop/src/main/ModuleUpdater.test.mjs b/fluxer_desktop/src/main/ModuleUpdater.test.mjsdeleted file mode 100644index 0bcc8480e..000000000--- a/fluxer_desktop/src/main/ModuleUpdater.test.mjs+++ /dev/null@@ -1,1746 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {Buffer} from 'node:buffer';-import {createHash} from 'node:crypto';-import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {ModuleStore, getModuleStoreRoot} = await import('@electron/main/ModuleStore');-const {ModuleUpdater} = await import('@electron/main/ModuleUpdater');--const SHELL_VERSION = '2026.823.1';-const RELEASE_CHANNEL = 'canary';-const PLATFORM = 'darwin';-const ARCH = 'arm64';-const PACKAGE_ORIGIN = 'https://pkgs.invalid';-const SOURCE_SHA = 'a'.repeat(40);-const NOW = Date.parse('2026-08-23T12:00:00.000Z');--const temporaryRoots = [];--after(async () => {- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--function sha256(data) {- return createHash('sha256').update(data).digest('hex');-}--function createUserData() {- const root = mkdtempSync(path.join(os.tmpdir(), 'module-updater-'));- temporaryRoots.push(root);- return root;-}--function installModuleOnDisk(storeRoot, moduleName, digest, entries, buildVersion = SHELL_VERSION) {- const directory = path.join(storeRoot, 'store', moduleName, digest);- mkdirSync(directory, {recursive: true});- const files = entries.map(([relative, body]) => {- writeFileSync(path.join(directory, relative), body);- return {path: relative, sha256: sha256(Buffer.from(body, 'utf8')), bytes: Buffer.byteLength(body, 'utf8')};- });- writeFileSync(- path.join(directory, 'module.json'),- `${JSON.stringify(- {- module: moduleName,- build_version: buildVersion,- release_channel: RELEASE_CHANNEL,- source_sha: SOURCE_SHA,- files,- },- null,- '\t',- )}\n`,- );- return directory;-}--function manifestBytes(- modules,- {- shellLatest = SHELL_VERSION,- shellMinimum = SHELL_VERSION,- required = null,- bounds = {},- metadataVersion = 1,- platform = PLATFORM,- buildVersion = SHELL_VERSION,- extra = {},- } = {},-) {- return Buffer.from(- JSON.stringify({- manifest_version: 1,- release_channel: RELEASE_CHANNEL,- platform,- arch: ARCH,- build_version: buildVersion,- pub_date: '2026-08-23T00:00:00.000Z',- metadata_version: metadataVersion,- shell: {latest_version: shellLatest, minimum_version: shellMinimum},- modules: Object.fromEntries(- Object.entries(modules).map(([moduleName, digest]) => [- moduleName,- {- sha256: digest,- bytes: 1024,- url: `${PACKAGE_ORIGIN}/desktop/${RELEASE_CHANNEL}/modules/${moduleName}/${digest}/package.br`,- ...(bounds[moduleName] ?? {}),- },- ]),- ),- required_modules: required ?? Object.keys(modules),- ...extra,- }),- 'utf8',- );-}--async function openStore(userDataPath, shellVersion = SHELL_VERSION) {- return await ModuleStore.open({- root: getModuleStoreRoot(userDataPath),- shellVersion,- releaseChannel: RELEASE_CHANNEL,- });-}--function createUpdater(store, modules, options = {}) {- const bytes = manifestBytes(modules, options);- const requests = [];- const sleeps = [];- const reports = [];- const updater = new ModuleUpdater({- store,- shellVersion: options.shellVersion ?? SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- platform: options.platform ?? PLATFORM,- arch: ARCH,- packageOrigin: PACKAGE_ORIGIN,- hasOfflineRenderer: options.bundledRendererVersion != null,- bundledRendererVersion: options.bundledRendererVersion ?? null,- forceStartupUpdate: options.forceStartupUpdate ?? false,- startupUpdateRequested: options.startupUpdateRequested ?? false,- moduleUpdatesDisabled: options.moduleUpdatesDisabled ?? false,- updateOnDemand: options.updateOnDemand ?? false,- selfUpdateShellFirst: options.selfUpdateShellFirst,- onState: options.onState,- fetch: async (url, init) => {- requests.push(url);- const response = options.respond == null ? null : await options.respond(url, init);- if (response != null) {- return response;- }- if (String(url).endsWith('/latest.json')) {- const version = options.shellFeed ?? options.shellLatest ?? SHELL_VERSION;- return new Response(JSON.stringify({version}), {status: 200, headers: {etag: `"feed-${version}"`}});- }- return new Response(bytes, {status: 200, headers: {etag: '"manifest-1"'}});- },- sleep: async (ms) => {- sleeps.push(ms);- },- random: () => 0,- now: () => NOW,- report: (report) => {- reports.push(report);- },- });- return {updater, requests, sleeps, reports};-}--function failNthInstallationCheck(store, nth, failure) {- let checks = 0;- return new Proxy(store, {- get(target, property) {- const value = Reflect.get(target, property, target);- if (typeof value !== 'function') {- return value;- }- if (property !== 'isInstalled') {- return value.bind(target);- }- return async (moduleName, digest) => {- checks += 1;- if (checks === nth) {- throw failure;- }- return await value.call(target, moduleName, digest);- };- },- });-}--const RENDERER_SHA = sha256('renderer-one');-const NEXT_RENDERER_SHA = sha256('renderer-two');-const OVERLAY_SHA = sha256('overlay-one');-const NEXT_OVERLAY_SHA = sha256('overlay-two');--function failInstallModule(store, failure) {- return new Proxy(store, {- get(target, property) {- const value = Reflect.get(target, property, target);- if (typeof value !== 'function') {- return value;- }- if (property !== 'installModule') {- return value.bind(target);- }- return async () => {- throw failure;- };- },- });-}--function failInstallModuleFor(store, moduleName, failure) {- return new Proxy(store, {- get(target, property) {- const value = Reflect.get(target, property, target);- if (typeof value !== 'function') {- return value;- }- if (property !== 'installModule') {- return value.bind(target);- }- return async (request) => {- if (request.module === moduleName) {- throw failure;- }- return await value.call(target, request);- };- },- });-}--function mergeDuringInstall(store, entries) {- let merged = false;- return new Proxy(store, {- get(target, property) {- const value = Reflect.get(target, property, target);- if (typeof value !== 'function') {- return value;- }- if (property !== 'installModule') {- return value.bind(target);- }- return async (request) => {- if (!merged) {- merged = true;- await target.mergeCommitted(entries);- }- return await value.call(target, request);- };- },- });-}--function recordInstalls(store, installs) {- return new Proxy(store, {- get(target, property) {- const value = Reflect.get(target, property, target);- if (typeof value !== 'function') {- return value;- }- if (property !== 'installModule') {- return value.bind(target);- }- return async (request) => {- installs.push(request.module);- return await value.call(target, request);- };- },- });-}--function unreachableFeed() {- return async () => {- throw new Error('module feed is unreachable');- };-}--function missingPackages() {- return async (url) => (url.endsWith('.br') ? new Response('', {status: 404}) : null);-}--function seedCachedPackage(store, digest) {- const packagePath = store.getPackagePath(digest);- mkdirSync(path.dirname(packagePath), {recursive: true});- writeFileSync(packagePath, 'cached');-}--describe('ModuleUpdater.run', () => {- test('launches the committed set when the manifest asks for nothing new', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater, requests, sleeps} = createUpdater(store, {fluxer_renderer: RENDERER_SHA});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.equal(outcome.rolledBack, false);- assert.deepEqual(outcome.belowFloor, []);- assert.equal(Object.hasOwn(outcome, 'installed'), false);- assert.equal(requests.length, 1);- assert.deepEqual(sleeps, []);- assert.deepEqual(store.getState().floor, {fluxer_renderer: RENDERER_SHA});- assert.equal(store.getState().boot_attempt, 1);- });-- test('a store failure at the floor check is retried instead of escaping run', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const failure = Object.assign(new Error('failed to inspect installed module path'), {- name: 'ModuleStoreIOError',- });- const {updater, sleeps, reports} = createUpdater(failNthInstallationCheck(store, 2, failure), {- fluxer_renderer: RENDERER_SHA,- });-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(sleeps, [500]);- assert.deepEqual(- reports.map((report) => [report.type, report.message]),- [['network-error', failure.message]],- );- });-- test('a manifest that no longer carries the committed module blocks instead of launching nothing', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater} = createUpdater(store, {});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'nothing-installed');- });-- test('a shell floor above this shell blocks on the shell update instead of installing modules', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {shellLatest: '2026.824.0', shellMinimum: '2026.824.0'},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-shell-update');- assert.equal(outcome.latestVersion, '2026.824.0');- assert.equal(outcome.minimumVersion, '2026.824.0');- assert.deepEqual(requests, [`${PACKAGE_ORIGIN}/desktop/${RELEASE_CHANNEL}/${PLATFORM}/${ARCH}/modules.json`]);- assert.deepEqual(store.getCommitted(), {fluxer_renderer: RENDERER_SHA});- });-- test('a required module that outruns this shell blocks on the shell update', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {bounds: {fluxer_renderer: {minimum_shell_version: '2026.824.0'}}},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-shell-update');- assert.equal(outcome.latestVersion, SHELL_VERSION);- assert.equal(outcome.minimumVersion, SHELL_VERSION);- assert.equal(requests.length, 1, 'a shell block must not start downloading packages');- });-- test('an optional module this shell has outgrown keeps its committed copy and still launches', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- const {updater, requests} = createUpdater(- store,- {fluxer_overlay: NEXT_OVERLAY_SHA, fluxer_renderer: RENDERER_SHA},- {required: ['fluxer_renderer'], bounds: {fluxer_overlay: {minimum_shell_version: '2026.824.0'}}},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- assert.equal(requests.length, 1, 'a module this shell cannot run must never be downloaded');- });-- test('an unreachable feed with no recorded fetch blocks instead of launching whatever is on disk', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater, sleeps} = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {respond: unreachableFeed()});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'nothing-installed');- assert.deepEqual(sleeps, [500, 1000, 2000, 4000, 8000]);- assert.equal(store.getState().boot_attempt, 0);- });-- test('an unreachable feed launches the set a previous boot already verified without waiting out the backoff', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- assert.equal((await createUpdater(store, {fluxer_renderer: RENDERER_SHA}).updater.run()).status, 'launching');- const {updater, sleeps} = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {respond: unreachableFeed()});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(sleeps, []);- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.equal(outcome.launchAttempt.committed.fluxer_renderer, RENDERER_SHA);- assert.equal(store.getState().boot_attempt, 2);- });-- test('a manifest older than the one already seen launches on the last accepted manifest without retrying', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const seen = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {metadataVersion: 5});- assert.equal((await seen.updater.run()).status, 'launching');- const {updater, sleeps, reports} = createUpdater(store, {fluxer_renderer: NEXT_RENDERER_SHA}, {metadataVersion: 4});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(sleeps, []);- assert.deepEqual(reports, []);- assert.equal(store.getState().manifest_high_water[0].metadataVersion, 5);- });-- test('an older manifest with no accepted copy to fall back on retries like an outage instead of blocking', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const seen = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {metadataVersion: 5});- assert.equal((await seen.updater.run()).status, 'launching');- rmSync(path.join(storeRoot, 'manifest.json'));- const {updater, sleeps, reports} = createUpdater(store, {fluxer_renderer: NEXT_RENDERER_SHA}, {metadataVersion: 4});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.ok(sleeps.length > 0, 'a stale edge copy clears within a minute, so the launch retries before giving up');- assert.ok(reports.every((report) => report.type === 'manifest-rollback'));- });-- test('a package the server no longer has demotes an optional module to its committed digest', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- const {updater, reports} = createUpdater(- store,- {fluxer_overlay: NEXT_OVERLAY_SHA, fluxer_renderer: RENDERER_SHA},- {required: ['fluxer_renderer'], respond: missingPackages()},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- assert.deepEqual(- reports.filter((report) => report.type !== 'network-error').map((report) => [report.type, report.module]),- [['package-missing', 'fluxer_overlay']],- );- });-- test('an install that runs out of disk space reports the storage error and commits nothing', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- const failure = Object.assign(new Error('no space left on device'), {code: 'ENOSPC'});- const {updater, reports} = createUpdater(failInstallModule(store, failure), {- fluxer_renderer: NEXT_RENDERER_SHA,- });-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'unreachable-below-floor');- assert.equal(outcome.message, 'no space left to install fluxer_renderer: no space left on device');- assert.equal(outcome.updateServerUnreachable, false);- assert.deepEqual(store.getCommitted(), {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(- [...new Set(reports.filter((report) => report.type === 'storage-error').map((report) => report.module))],- ['fluxer_renderer', null],- );- assert.equal(updater.getLastState().detail, 'Not enough disk space to install the update');- });-});--describe('ModuleUpdater with module updates disabled', () => {- test('launches the verified set without fetching even when the manifest demands a shell update', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- assert.equal((await createUpdater(store, {fluxer_renderer: RENDERER_SHA}).updater.run()).status, 'launching');- const statuses = [];- let shellUpdates = 0;- const {updater, requests, sleeps} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {- shellLatest: '2026.824.0',- shellMinimum: '2026.824.0',- forceStartupUpdate: true,- moduleUpdatesDisabled: true,- onState: (state) => statuses.push(state.status),- selfUpdateShellFirst: async () => {- shellUpdates += 1;- return {reason: 'no-update'};- },- },- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(requests, []);- assert.deepEqual(sleeps, []);- assert.equal(shellUpdates, 0);- assert.deepEqual(statuses, ['unreachable-launch']);- assert.equal(outcome.launchAttempt.committed.fluxer_renderer, RENDERER_SHA);- });-- test('launches the bundled renderer on a fresh store without fetching', async () => {- const store = await openStore(createUserData());- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {bundledRendererVersion: SHELL_VERSION, moduleUpdatesDisabled: true},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {});- assert.deepEqual(requests, []);- });-- test('blocks at once on the unreachable splash without fetching when nothing is installed', async () => {- const store = await openStore(createUserData());- const {updater, requests, sleeps} = createUpdater(- store,- {fluxer_renderer: RENDERER_SHA},- {moduleUpdatesDisabled: true},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'nothing-installed');- assert.equal(outcome.updateServerUnreachable, true);- assert.deepEqual(requests, []);- assert.deepEqual(sleeps, []);- });-- test('ignores an explicit update request', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- installModuleOnDisk(getModuleStoreRoot(userDataPath), 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- assert.equal((await createUpdater(store, {fluxer_renderer: RENDERER_SHA}).updater.run()).status, 'launching');- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {moduleUpdatesDisabled: true, startupUpdateRequested: true},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(requests, []);- });-});--describe('ModuleUpdater with updates on demand', () => {- async function storeOnRenderer() {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- return {store, storeRoot};- }-- test('launches the verified set without fetching when an automatic check left an update waiting', async () => {- const {store} = await storeOnRenderer();- assert.equal((await createUpdater(store, {fluxer_renderer: RENDERER_SHA}).updater.run()).status, 'launching');- const statuses = [];- let shellUpdates = 0;- const {updater, requests, sleeps} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {- shellLatest: '2026.824.0',- forceStartupUpdate: true,- updateOnDemand: true,- onState: (state) => statuses.push(state.status),- selfUpdateShellFirst: async () => {- shellUpdates += 1;- return {reason: 'no-update'};- },- },- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(requests, []);- assert.deepEqual(sleeps, []);- assert.equal(shellUpdates, 0);- assert.deepEqual(statuses, ['launching']);- });-- test('installs the update the user asked for before launch', async () => {- const {store, storeRoot} = await storeOnRenderer();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const steps = [];- const {updater, requests} = createUpdater(- recordInstalls(store, steps),- {fluxer_renderer: NEXT_RENDERER_SHA},- {- shellLatest: '2026.824.1',- updateOnDemand: true,- startupUpdateRequested: true,- selfUpdateShellFirst: async (latestVersion) => {- steps.push(`shell ${latestVersion}`);- return {reason: 'install-failed'};- },- },- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: NEXT_RENDERER_SHA});- assert.deepEqual(steps, ['shell 2026.824.1', 'fluxer_renderer']);- assert.ok(requests.some((url) => String(url).endsWith('/modules.json')));- });-- test('goes to the update server when nothing can launch', async () => {- const store = await openStore(createUserData());- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: RENDERER_SHA},- {updateOnDemand: true, respond: missingPackages()},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'required-module-unavailable');- assert.equal(outcome.updateServerUnreachable, false);- assert.ok(requests.some((url) => String(url).endsWith('/modules.json')));- });-});--describe('ModuleUpdater checks without downloading and installs only when asked', () => {- async function storeOnRenderer() {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- return {store, storeRoot};- }-- test('a check reads only the manifest and leaves the committed set, the floor and the boot attempt alone', async () => {- const {store} = await storeOnRenderer();- const before = store.getState();- const installs = [];- const {updater, requests} = createUpdater(recordInstalls(store, installs), {fluxer_renderer: NEXT_RENDERER_SHA});-- const check = await updater.checkForUpdate();-- assert.deepEqual(check, {shellLatestVersion: SHELL_VERSION, shellNewer: false, modulesChanged: true});- assert.deepEqual(- requests.map((url) => String(url).split('/').pop()),- ['modules.json', 'latest.json'],- );- assert.deepEqual(installs, []);- assert.deepEqual(store.getCommitted(), {fluxer_renderer: RENDERER_SHA});- assert.equal(store.getState().boot_attempt, before.boot_attempt);- assert.deepEqual(store.getState().floor, before.floor);- assert.equal(store.getState().last_manifest_fetch, before.last_manifest_fetch);- });-- test('a check reports a newer shell and an unchanged module set', async () => {- const {store} = await storeOnRenderer();- const {updater} = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {shellLatest: '2026.824.1'});-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: '2026.824.1',- shellNewer: true,- modulesChanged: false,- });- });-- test('a shell feed ahead of the manifest offers the newer shell', async () => {- const {store} = await storeOnRenderer();- const {updater} = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {shellFeed: '2026.1012.154032'});-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: '2026.1012.154032',- shellNewer: true,- modulesChanged: false,- });- });-- test('a shell feed behind the manifest never hides the shell the manifest names', async () => {- const {store} = await storeOnRenderer();- const {updater} = createUpdater(- store,- {fluxer_renderer: RENDERER_SHA},- {shellLatest: '2026.824.1', shellFeed: SHELL_VERSION},- );-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: '2026.824.1',- shellNewer: true,- modulesChanged: false,- });- });-- test('an unreachable shell feed still answers from the manifest', async () => {- const {store} = await storeOnRenderer();- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {respond: async (url) => (String(url).endsWith('/latest.json') ? new Response('', {status: 503}) : null)},- );-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: SHELL_VERSION,- shellNewer: false,- modulesChanged: true,- });- });-- test('repeat checks revalidate both feeds and reuse them when nothing changed', async () => {- const {store} = await storeOnRenderer();- const conditions = [];- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {- shellFeed: '2026.824.1',- respond: async (url, init) => {- const etag = init?.headers?.['if-none-match'] ?? null;- conditions.push([String(url).split('/').pop(), etag]);- return etag == null ? null : new Response(null, {status: 304});- },- },- );- const first = await updater.checkForUpdate();-- const second = await updater.checkForUpdate();-- assert.deepEqual(second, first);- assert.deepEqual(second, {shellLatestVersion: '2026.824.1', shellNewer: true, modulesChanged: true});- assert.deepEqual(conditions.slice(-2), [- ['modules.json', '"manifest-1"'],- ['latest.json', '"feed-2026.824.1"'],- ]);- });-- test('an older manifest during a background check reads as nothing new instead of failing', async () => {- const {store} = await storeOnRenderer();- let metadataVersion = 6;- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {- respond: async (url) =>- String(url).endsWith('/modules.json')- ? new Response(manifestBytes({fluxer_renderer: NEXT_RENDERER_SHA}, {metadataVersion}), {status: 200})- : null,- },- );- const fresh = await updater.checkForUpdate();- metadataVersion = 5;-- const stale = await updater.checkForUpdate();-- assert.deepEqual(stale, fresh);- assert.deepEqual(stale, {shellLatestVersion: SHELL_VERSION, shellNewer: false, modulesChanged: true});- });-- test('a module that needs the next shell reads as a shell update, not as a module update', async () => {- const {store} = await storeOnRenderer();- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {shellLatest: '2026.824.1', bounds: {fluxer_renderer: {minimum_shell_version: '2026.824.1'}}},- );-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: '2026.824.1',- shellNewer: true,- modulesChanged: false,- });- });-- test('the click installs the new set, reports progress and arms a launch attempt for the next window', async () => {- const {store, storeRoot} = await storeOnRenderer();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const statuses = [];- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {onState: (state) => statuses.push(state.status)},- );-- const attempt = await updater.installPending();-- assert.deepEqual(attempt?.committed, {fluxer_renderer: NEXT_RENDERER_SHA});- assert.deepEqual(store.getCommitted(), {fluxer_renderer: NEXT_RENDERER_SHA});- assert.equal(store.getState().boot_attempt, 1);- assert.equal(statuses[0], 'checking');- assert.equal(statuses.at(-1), 'verifying');- await updater.markLaunchSucceeded(attempt);- assert.equal(store.getState().boot_attempt, 0);- });-- test('the click keeps a module installed on demand while it was downloading', async () => {- const {store, storeRoot} = await storeOnRenderer();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const {updater} = createUpdater(mergeDuringInstall(store, {fluxer_overlay: OVERLAY_SHA}), {- fluxer_renderer: NEXT_RENDERER_SHA,- });-- const attempt = await updater.installPending();-- assert.deepEqual(attempt?.committed, {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA});- assert.deepEqual(store.getCommitted(), {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA});- });-- test('the click installs nothing when the manifest now needs a newer shell', async () => {- const {store} = await storeOnRenderer();- const installs = [];- const {updater} = createUpdater(- recordInstalls(store, installs),- {fluxer_renderer: NEXT_RENDERER_SHA},- {shellLatest: '2026.824.1', shellMinimum: '2026.824.1'},- );-- assert.equal(await updater.installPending(), null);- assert.deepEqual(installs, []);- assert.deepEqual(store.getCommitted(), {fluxer_renderer: RENDERER_SHA});- });-- test('a module the manifest advertises but the CDN never got does not strand the rest of the update', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const {updater, reports} = createUpdater(- store,- {fluxer_overlay: NEXT_OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA},- {- required: ['fluxer_renderer'],- respond: async (url) =>- url.endsWith(`${NEXT_OVERLAY_SHA}/package.br`) ? new Response('', {status: 404}) : null,- },- );-- const attempt = await updater.installPending();-- assert.deepEqual(attempt?.committed, {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA});- assert.deepEqual(- [...new Set(reports.filter((report) => report.type === 'package-missing').map((report) => report.module))],- ['fluxer_overlay'],- );- });-- test('a committed optional module whose tree is gone and whose package 404s still lets the renderer activate', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- await rm(path.join(storeRoot, 'store', 'fluxer_overlay', OVERLAY_SHA), {recursive: true, force: true});- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const {updater} = createUpdater(- store,- {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA},- {- required: ['fluxer_renderer'],- respond: async (url) => (url.endsWith(`${OVERLAY_SHA}/package.br`) ? new Response('', {status: 404}) : null),- },- );-- await updater.installPending();-- assert.deepEqual(store.getCommitted(), {fluxer_renderer: NEXT_RENDERER_SHA});- });-- test('a package failure with no deterministic cause rejects the click and keeps the installed set', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- installModuleOnDisk(storeRoot, 'fluxer_overlay', NEXT_OVERLAY_SHA, [['index.js', 'overlay-two']]);- seedCachedPackage(store, NEXT_OVERLAY_SHA);- const {updater} = createUpdater(- store,- {fluxer_overlay: NEXT_OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA},- {- required: ['fluxer_renderer'],- respond: async (url) =>- url.endsWith(`${NEXT_RENDERER_SHA}/package.br`) ? new Response('', {status: 503}) : null,- },- );-- await assert.rejects(updater.installPending(), /failed to download module fluxer_renderer/u);-- assert.deepEqual(store.getCommitted(), {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- });-- test('a click that runs out of disk space aborts instead of activating the part that fit', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['index.js', 'overlay']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- await store.commit({fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- installModuleOnDisk(storeRoot, 'fluxer_overlay', NEXT_OVERLAY_SHA, [['index.js', 'overlay-two']]);- seedCachedPackage(store, NEXT_OVERLAY_SHA);- const failure = Object.assign(new Error('no space left on device'), {code: 'ENOSPC'});- const {updater} = createUpdater(- failInstallModuleFor(store, 'fluxer_renderer', failure),- {fluxer_overlay: NEXT_OVERLAY_SHA, fluxer_renderer: NEXT_RENDERER_SHA},- {required: ['fluxer_renderer']},- );-- await assert.rejects(updater.installPending(), /no space left on device/u);-- assert.deepEqual(store.getCommitted(), {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- });-- test('a boot with a newer shell updates the shell before downloading any module', async () => {- const {store, storeRoot} = await storeOnRenderer();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const steps = [];- const {updater} = createUpdater(- recordInstalls(store, steps),- {fluxer_renderer: NEXT_RENDERER_SHA},- {- shellLatest: '2026.824.1',- forceStartupUpdate: true,- selfUpdateShellFirst: async (latestVersion) => {- steps.push(`shell ${latestVersion}`);- return {reason: 'install-failed'};- },- },- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(steps, ['shell 2026.824.1', 'fluxer_renderer']);- });-- test('a boot with the newest shell never runs the shell update', async () => {- const {store, storeRoot} = await storeOnRenderer();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(store, NEXT_RENDERER_SHA);- const steps = [];- const {updater} = createUpdater(- recordInstalls(store, steps),- {fluxer_renderer: NEXT_RENDERER_SHA},- {- forceStartupUpdate: true,- selfUpdateShellFirst: async (latestVersion) => {- steps.push(`shell ${latestVersion}`);- return {reason: 'install-failed'};- },- },- );-- await updater.run();-- assert.deepEqual(steps, ['fluxer_renderer']);- });-- test('a Linux boot right after a shell update fetches the modules instead of launching the old set', async () => {- const optional = await storeOnRenderer();- const quiet = createUpdater(optional.store, {fluxer_renderer: NEXT_RENDERER_SHA}, {platform: 'linux'});- const skipped = await quiet.updater.run();- assert.equal(skipped.status, 'launching');- assert.deepEqual(skipped.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(quiet.requests, []);-- const forced = await storeOnRenderer();- installModuleOnDisk(forced.storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer-two']]);- seedCachedPackage(forced.store, NEXT_RENDERER_SHA);- const {updater, requests} = createUpdater(- forced.store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {platform: 'linux', forceStartupUpdate: true},- );- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: NEXT_RENDERER_SHA});- assert.ok(requests.some((url) => String(url).endsWith('/modules.json')));- });-- test('a forced Linux boot with a transient package error launches the committed set', async () => {- const {store} = await storeOnRenderer();- const {updater, sleeps} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {- platform: 'linux',- forceStartupUpdate: true,- respond: async (url) => (String(url).endsWith('package.br') ? new Response('', {status: 503}) : null),- },- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(- sleeps,- [],- 'a package or deb upgrade never waits through the backoff for a module it can live without',- );- });-});--describe('ModuleUpdater explains why a launch is blocked', () => {- test('a first launch that cannot reach the feed blocks as unreachable rather than as a missing update', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const {updater} = createUpdater(store, {fluxer_renderer: RENDERER_SHA}, {respond: unreachableFeed()});-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'nothing-installed');- assert.equal(outcome.updateServerUnreachable, true);- });-- test('a package url the policy refuses names its cause in the block and in a report', async () => {- const userDataPath = createUserData();- const store = await openStore(userDataPath);- const url = `http://192.168.139.107:48780/desktop/canary/modules/fluxer_renderer/${RENDERER_SHA}/package.br`;- const {updater, reports} = createUpdater(- store,- {fluxer_renderer: RENDERER_SHA},- {bounds: {fluxer_renderer: {url}}},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-update-required');- assert.equal(outcome.reason, 'required-module-unavailable');- assert.equal(outcome.updateServerUnreachable, false);- assert.match(outcome.message, /not https: http:\/\/192\.168\.139\.107/u);- const rejected = reports.find((report) => report.type === 'package-rejected');- assert.equal(rejected?.module, 'fluxer_renderer');- assert.match(rejected?.message ?? '', /192\.168\.139\.107/u);- const blocked = reports.find((report) => report.type === 'blocked');- assert.notEqual(blocked?.error, null);- });-});--describe('ModuleUpdater after a crash-loop rollback', () => {- async function rollBackFrom(store, modules) {- for (let launch = 0; launch < 2; launch += 1) {- assert.equal((await createUpdater(store, modules).updater.run()).status, 'launching');- }- const reverted = await createUpdater(store, modules).updater.run();- assert.equal(reverted.rolledBack, true);- return reverted;- }-- test('the next boot keeps the reverted set instead of reinstalling the build that crashed', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer two']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- const modules = {fluxer_renderer: NEXT_RENDERER_SHA};- await rollBackFrom(store, modules);-- const {updater, requests} = createUpdater(store, modules);- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.equal(outcome.rolledBack, false);- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(- requests.filter((url) => String(url).endsWith('.br')),- [],- );- });-- test('a manifest that moves past the rejected build clears the rejection', async () => {- const userDataPath = createUserData();- const storeRoot = getModuleStoreRoot(userDataPath);- const store = await openStore(userDataPath);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']]);- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer two']]);- await store.commit({fluxer_renderer: RENDERER_SHA});- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- await rollBackFrom(store, {fluxer_renderer: NEXT_RENDERER_SHA});- assert.equal(store.isRejected('fluxer_renderer', NEXT_RENDERER_SHA), true);-- await createUpdater(store, {fluxer_renderer: OVERLAY_SHA}, {metadataVersion: 2, respond: missingPackages()})- .updater.run()- .catch(() => undefined);-- assert.equal(store.isRejected('fluxer_renderer', NEXT_RENDERER_SHA), false);- });-});--describe('ModuleUpdater with a renderer bundled in the shell', () => {- const OLDER_VERSION = '2026.822.9';-- async function storeWithOlderRenderer() {- const store = await openStore(createUserData());- installModuleOnDisk(store.root, 'fluxer_renderer', RENDERER_SHA, [['index.html', 'renderer one']], OLDER_VERSION);- await store.commit({fluxer_renderer: RENDERER_SHA});- await store.recordManifestFetch({- etag: null,- fetchedAt: new Date(NOW).toISOString(),- manifest: {- feed: {releaseChannel: RELEASE_CHANNEL, platform: PLATFORM, arch: ARCH},- metadataVersion: 1,- manifestSha256: 'c'.repeat(64),- },- floor: {fluxer_renderer: NEXT_RENDERER_SHA},- });- return store;- }-- test('a new shell over an older installed renderer launches the bundle with the feed down', async () => {- const store = await storeWithOlderRenderer();- const {updater, reports} = createUpdater(- store,- {},- {bundledRendererVersion: SHELL_VERSION, forceStartupUpdate: true, respond: unreachableFeed()},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'unreachable-launch');- assert.deepEqual(outcome.committed, {});- assert.deepEqual(store.getCommitted(), {});- assert.deepEqual(store.getState().previous, {});- assert.equal(- reports.some((report) => report.type === 'bundled-renderer-preferred'),- true,- );- assert.deepEqual((await updater.selectServedModules(outcome.committed)).renderer, {- source: 'bundled',- version: SHELL_VERSION,- bundledVersion: SHELL_VERSION,- });- });-- test('a feed renderer the bundle already covers is never downloaded', async () => {- const store = await storeWithOlderRenderer();- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {bundledRendererVersion: SHELL_VERSION, forceStartupUpdate: true, metadataVersion: 2},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {});- assert.equal(- requests.some((url) => String(url).endsWith('package.br')),- false,- );- assert.deepEqual(store.getState().floor, {});- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: SHELL_VERSION,- shellNewer: false,- modulesChanged: false,- });- });-- test('a feed renderer newer than the bundle is still fetched', async () => {- const store = await openStore(createUserData());- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {bundledRendererVersion: OLDER_VERSION, respond: missingPackages()},- );-- await updater.run();-- assert.equal(- requests.some((url) => String(url).endsWith(`${NEXT_RENDERER_SHA}/package.br`)),- true,- );- });-- test('a renderer module that keeps failing to boot is dropped for the bundle, never relaunched forever', async () => {- const store = await openStore(createUserData());- installModuleOnDisk(store.root, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.html', 'broken']], '2026.900.1');- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- const served = [];- for (let launch = 0; launch < 4; launch += 1) {- const {updater} = createUpdater(- store,- {},- {bundledRendererVersion: SHELL_VERSION, platform: 'linux', respond: unreachableFeed()},- );- const outcome = await updater.run();- served.push((await updater.selectServedModules(outcome.committed)).renderer.source);- }-- assert.deepEqual(served, ['module', 'module', 'bundled', 'bundled']);- assert.equal(store.isRejected('fluxer_renderer', NEXT_RENDERER_SHA), true);- });-- test('a committed on-demand module whose files are gone never blocks an offline launch', async () => {- for (const platform of ['darwin', 'linux']) {- const store = await openStore(createUserData());- const directory = installModuleOnDisk(store.root, 'fluxer_fonts_jp', OVERLAY_SHA, [['a.woff2', 'font']], '0.0.0');- await store.commit({fluxer_fonts_jp: OVERLAY_SHA});- await rm(directory, {recursive: true, force: true});- const {updater} = createUpdater(- store,- {},- {bundledRendererVersion: SHELL_VERSION, platform, respond: unreachableFeed()},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, platform === 'linux' ? 'launching' : 'unreachable-launch', platform);- assert.deepEqual(outcome.committed, {}, platform);- }- });-- test('a newer feed renderer whose package is missing launches the bundle instead of blocking', async () => {- const store = await openStore(createUserData());- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- {bundledRendererVersion: OLDER_VERSION, respond: missingPackages()},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {});- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: SHELL_VERSION,- shellNewer: false,- modulesChanged: true,- });- });-- test('a packaged bundle with no readable version still outranks an installed module', async () => {- const store = await openStore(createUserData());- installModuleOnDisk(store.root, 'fluxer_renderer', RENDERER_SHA, [['index.html', 'old']], OLDER_VERSION);- await store.commit({fluxer_renderer: RENDERER_SHA});- const updater = new ModuleUpdater({- store,- shellVersion: SHELL_VERSION,- releaseChannel: RELEASE_CHANNEL,- platform: 'linux',- arch: ARCH,- packageOrigin: PACKAGE_ORIGIN,- hasOfflineRenderer: true,- bundledRendererVersion: 'dev',- preferUnversionedBundle: true,- fetch: unreachableFeed(),- sleep: async () => {},- random: () => 0,- now: () => NOW,- });-- const outcome = await updater.run();-- assert.equal((await updater.selectServedModules(outcome.committed)).renderer.source, 'bundled');- assert.deepEqual(store.getCommitted(), {});- });-});--describe('ModuleUpdater keeps every shell on modules it can run', () => {- const REPORTER_SHELL = '2026.1008.32323';- const LIVE_SHELL = '2026.1009.45608';- const DICTIONARY_SHA = sha256('dictionary-one');- const NEXT_DICTIONARY_SHA = sha256('dictionary-two');- const FONT_SHA = sha256('font-one');- const AHEAD = {fluxer_renderer: {minimum_shell_version: LIVE_SHELL}};-- function feedAhead(overrides = {}) {- return {- shellVersion: REPORTER_SHELL,- shellLatest: LIVE_SHELL,- shellMinimum: '0.0.0',- buildVersion: LIVE_SHELL,- bounds: AHEAD,- ...overrides,- };- }-- async function storeFor(shellVersion = REPORTER_SHELL) {- const userDataPath = createUserData();- const store = await openStore(userDataPath, shellVersion);- return {store, storeRoot: getModuleStoreRoot(userDataPath)};- }-- test('a Linux shell below the renderer floor launches its bundled renderer instead of asking for a shell update', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_dict_en', DICTIONARY_SHA, [['en.dic', 'words']], LIVE_SHELL);- seedCachedPackage(store, DICTIONARY_SHA);- const statuses = [];- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_dict_en: DICTIONARY_SHA},- feedAhead({- platform: 'linux',- bundledRendererVersion: REPORTER_SHELL,- forceStartupUpdate: true,- onState: (state) => statuses.push(state.status),- }),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_dict_en: DICTIONARY_SHA});- assert.equal(- requests.some((url) => String(url).includes(NEXT_RENDERER_SHA)),- false,- );- assert.equal(statuses.includes('blocked-shell-update'), false);- assert.equal((await updater.selectServedModules(outcome.committed)).renderer.source, 'bundled');- });-- test('a Flatpak shell Flathub has not updated yet keeps its renderer and still takes compatible modules', async () => {- const flathubShell = '2026.1012.154028';- const liveShell = '2026.1013.15209';- const {store, storeRoot} = await storeFor(flathubShell);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], flathubShell);- installModuleOnDisk(storeRoot, 'fluxer_dict_en', DICTIONARY_SHA, [['en.dic', 'words']], flathubShell);- installModuleOnDisk(storeRoot, 'fluxer_dict_en', NEXT_DICTIONARY_SHA, [['en.dic', 'more words']], liveShell);- seedCachedPackage(store, NEXT_DICTIONARY_SHA);- await store.commit({fluxer_renderer: RENDERER_SHA, fluxer_dict_en: DICTIONARY_SHA});- const statuses = [];- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_dict_en: NEXT_DICTIONARY_SHA},- feedAhead({- shellVersion: flathubShell,- shellLatest: liveShell,- buildVersion: liveShell,- bounds: {fluxer_renderer: {minimum_shell_version: liveShell}},- platform: 'linux',- forceStartupUpdate: true,- required: ['fluxer_renderer'],- onState: (state) => statuses.push(state.status),- }),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_dict_en: NEXT_DICTIONARY_SHA, fluxer_renderer: RENDERER_SHA});- assert.equal(- requests.some((url) => String(url).includes(NEXT_RENDERER_SHA)),- false,- );- assert.equal(statuses.includes('blocked-shell-update'), false);- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: liveShell,- shellNewer: true,- modulesChanged: false,- });- });-- test('a Linux shell behind the floor keeps launching its committed compatible renderer', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({platform: 'linux', forceStartupUpdate: true}),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.equal(- requests.some((url) => String(url).endsWith('package.br')),- false,- );- });-- test('a renderer asset module is not replaced while the served renderer is older than the feed', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- installModuleOnDisk(storeRoot, 'fluxer_overlay', OVERLAY_SHA, [['overlay.js', 'overlay']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA, fluxer_overlay: OVERLAY_SHA});- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_overlay: NEXT_OVERLAY_SHA},- feedAhead({platform: 'linux', forceStartupUpdate: true, required: ['fluxer_renderer']}),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_overlay: OVERLAY_SHA, fluxer_renderer: RENDERER_SHA});- assert.equal(- requests.some((url) => String(url).endsWith('package.br')),- false,- );- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: LIVE_SHELL,- shellNewer: true,- modulesChanged: false,- });- });-- test('an on-demand renderer asset is unavailable while the served renderer is older than the feed', async () => {- const {store} = await storeFor();- const {updater, requests} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_fonts_jp: FONT_SHA},- feedAhead({platform: 'linux', bundledRendererVersion: REPORTER_SHELL, required: ['fluxer_renderer']}),- );-- assert.deepEqual(await updater.ensureModule('fluxer_fonts_jp'), {module: 'fluxer_fonts_jp', status: 'unavailable'});- assert.equal(- requests.some((url) => String(url).endsWith('package.br')),- false,- );- });-- test('a committed renderer asset stays installed while the served renderer is older than the feed', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- installModuleOnDisk(storeRoot, 'fluxer_fonts_jp', FONT_SHA, [['font.woff2', 'font']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA, fluxer_fonts_jp: FONT_SHA});- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_fonts_jp: sha256('font-two')},- feedAhead({platform: 'linux', required: ['fluxer_renderer']}),- );-- assert.deepEqual(await updater.ensureModule('fluxer_fonts_jp'), {- module: 'fluxer_fonts_jp',- status: 'already-installed',- });- });-- test('an on-demand dictionary installs while the renderer needs a newer shell', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_dict_en', DICTIONARY_SHA, [['en.dic', 'words']], LIVE_SHELL);- seedCachedPackage(store, DICTIONARY_SHA);- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_dict_en: DICTIONARY_SHA},- feedAhead({platform: 'linux', bundledRendererVersion: REPORTER_SHELL, required: ['fluxer_renderer']}),- );-- assert.deepEqual(await updater.ensureModule('fluxer_dict_en'), {module: 'fluxer_dict_en', status: 'installed'});- assert.deepEqual(store.getCommitted(), {fluxer_dict_en: DICTIONARY_SHA});- assert.deepEqual(store.getShellRange('fluxer_dict_en', DICTIONARY_SHA), {- minimum_shell_version: null,- maximum_shell_version: null,- });- });-- test('an AppImage updates its shell first on a forced boot and launches the compatible set when that fails', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA});- const attempts = [];- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({- platform: 'linux',- forceStartupUpdate: true,- selfUpdateShellFirst: async (latestVersion) => {- attempts.push(latestVersion);- return {reason: 'download-failed'};- },- }),- );-- const outcome = await updater.run();-- assert.deepEqual(attempts, [LIVE_SHELL]);- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- });-- test('a Windows shell below the floor launches the compatible set when the shell feed has no newer shell', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({platform: 'win32', selfUpdateShellFirst: async () => ({reason: 'no-update'})}),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.deepEqual(store.getState().floor, {});- });-- test('a Windows shell below the floor installs a compatible module and launches when the shell feed has no newer shell', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- installModuleOnDisk(storeRoot, 'fluxer_dict_en', DICTIONARY_SHA, [['en.dic', 'words']], LIVE_SHELL);- seedCachedPackage(store, DICTIONARY_SHA);- await store.commit({fluxer_renderer: RENDERER_SHA});- const attempts = [];- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_dict_en: DICTIONARY_SHA},- feedAhead({- platform: 'win32',- selfUpdateShellFirst: async (latestVersion) => {- attempts.push(latestVersion);- return {reason: 'no-update'};- },- }),- );-- const outcome = await updater.run();-- assert.deepEqual(attempts, [LIVE_SHELL]);- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_dict_en: DICTIONARY_SHA, fluxer_renderer: RENDERER_SHA});- });-- test('a Windows shell below the floor whose self update fails is blocked', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({platform: 'win32', selfUpdateShellFirst: async () => ({reason: 'download-failed'})}),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'blocked-shell-update');- assert.equal(outcome.latestVersion, LIVE_SHELL);- assert.deepEqual(store.getCommitted(), {fluxer_renderer: RENDERER_SHA});- });-- test('a Windows floor keeps the renderer it already enforced when the feed raises it past this shell', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- seedCachedPackage(store, RENDERER_SHA);- const first = createUpdater(- store,- {fluxer_renderer: RENDERER_SHA},- feedAhead({- platform: 'win32',- shellLatest: REPORTER_SHELL,- buildVersion: REPORTER_SHELL,- bounds: {},- required: ['fluxer_renderer'],- }),- );- assert.equal((await first.updater.run()).status, 'launching');- assert.deepEqual(store.getState().floor, {fluxer_renderer: RENDERER_SHA});- const raised = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({- platform: 'win32',- metadataVersion: 2,- required: ['fluxer_renderer'],- selfUpdateShellFirst: async () => ({reason: 'download-failed'}),- }),- );-- assert.equal((await raised.updater.run()).status, 'blocked-shell-update');- assert.deepEqual(store.getState().floor, {fluxer_renderer: RENDERER_SHA});- });-- test('a renderer installed for a newer shell is retired after a shell downgrade and the bundle serves', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer']], LIVE_SHELL);- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- await store.recordShellRanges([- {module: 'fluxer_renderer', sha256: NEXT_RENDERER_SHA, minimum: LIVE_SHELL, maximum: null},- ]);- const {updater, reports} = createUpdater(- store,- {},- {shellVersion: REPORTER_SHELL, platform: 'linux', bundledRendererVersion: REPORTER_SHELL},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {});- assert.deepEqual(- reports.filter((report) => report.type === 'shell-incompatible-retired').map((report) => report.module),- ['fluxer_renderer'],- );- assert.equal((await updater.selectServedModules(outcome.committed)).renderer.source, 'bundled');- });-- test('a renderer with no recorded range is retired when the cached manifest says this shell cannot run it', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'renderer']], LIVE_SHELL);- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- writeFileSync(- path.join(store.root, 'manifest.json'),- manifestBytes({fluxer_renderer: NEXT_RENDERER_SHA}, feedAhead({platform: 'linux'})),- );- const {updater, reports} = createUpdater(- store,- {},- {shellVersion: REPORTER_SHELL, platform: 'linux', bundledRendererVersion: REPORTER_SHELL},- );-- const outcome = await updater.run();-- assert.deepEqual(outcome.committed, {});- assert.equal(- reports.some((report) => report.type === 'shell-incompatible-retired'),- true,- );- });-- test('a crash-loop rollback never restores a renderer this shell cannot run', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', NEXT_RENDERER_SHA, [['index.js', 'ahead']], LIVE_SHELL);- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'current']], LIVE_SHELL);- await store.commit({fluxer_renderer: NEXT_RENDERER_SHA});- await store.commit({fluxer_renderer: RENDERER_SHA});- await store.recordShellRanges([- {module: 'fluxer_renderer', sha256: NEXT_RENDERER_SHA, minimum: LIVE_SHELL, maximum: null},- ]);- await store.recordLaunchAttempt();- await store.recordLaunchAttempt();- const {updater} = createUpdater(- store,- {},- {shellVersion: REPORTER_SHELL, platform: 'linux', bundledRendererVersion: REPORTER_SHELL},- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.equal(outcome.committed.fluxer_renderer, undefined);- assert.equal(store.getState().previous.fluxer_renderer, undefined);- assert.equal(store.isRejected('fluxer_renderer', RENDERER_SHA), true);- });-- test('a check offers compatible modules while the renderer needs a newer shell', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_dict_en', DICTIONARY_SHA, [['en.dic', 'words']], REPORTER_SHELL);- await store.commit({fluxer_dict_en: DICTIONARY_SHA});- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA, fluxer_dict_en: NEXT_DICTIONARY_SHA},- feedAhead({platform: 'linux', bundledRendererVersion: REPORTER_SHELL}),- );-- assert.deepEqual(await updater.checkForUpdate(), {- shellLatestVersion: LIVE_SHELL,- shellNewer: true,- modulesChanged: true,- });- });-- test('a Linux launch never blocks on linux_security_minimum in the manifest', async () => {- const {store, storeRoot} = await storeFor();- installModuleOnDisk(storeRoot, 'fluxer_renderer', RENDERER_SHA, [['index.js', 'renderer']], REPORTER_SHELL);- await store.commit({fluxer_renderer: RENDERER_SHA});- const {updater} = createUpdater(- store,- {fluxer_renderer: NEXT_RENDERER_SHA},- feedAhead({- platform: 'linux',- forceStartupUpdate: true,- shellMinimum: LIVE_SHELL,- extra: {linux_security_minimum: {version: LIVE_SHELL, required_modules: ['fluxer_renderer']}},- }),- );-- const outcome = await updater.run();-- assert.equal(outcome.status, 'launching');- assert.deepEqual(outcome.committed, {fluxer_renderer: RENDERER_SHA});- assert.equal(Object.hasOwn(updater.getLastState(), 'requiredSecurityUpdate'), false);- });-});diff --git a/fluxer_desktop/src/main/ModuleUpdatesSetting.test.mjs b/fluxer_desktop/src/main/ModuleUpdatesSetting.test.mjsdeleted file mode 100644index f26817c3e..000000000--- a/fluxer_desktop/src/main/ModuleUpdatesSetting.test.mjs+++ /dev/null@@ -1,134 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {getDesktopTroubleshootingSettings, loadDesktopConfig, setDesktopTroubleshootingSettings} = await import(- '../common/DesktopConfig.ts'-);-const {shouldDisableModuleUpdatesForLaunch} = await import('./LaunchOptions.ts');-const {isUpdateOnDemandLaunch, resolveEffectiveDesktopTroubleshootingSettings} = await import('./DesktopDebugInfo.ts');--function loadSettings(troubleshooting) {- const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-desktop-module-updates-setting-test-'));- fs.writeFileSync(path.join(userDataPath, 'settings.json'), JSON.stringify({troubleshooting}));- loadDesktopConfig(userDataPath);- return userDataPath;-}--function readPersisted(userDataPath) {- return JSON.parse(fs.readFileSync(path.join(userDataPath, 'settings.json'), 'utf8')).troubleshooting;-}--function withModuleUpdatesEnv(value, run) {- const previous = process.env.FLUXER_DISABLE_MODULE_UPDATES;- try {- if (value === undefined) {- delete process.env.FLUXER_DISABLE_MODULE_UPDATES;- } else {- process.env.FLUXER_DISABLE_MODULE_UPDATES = value;- }- run();- } finally {- if (previous === undefined) {- delete process.env.FLUXER_DISABLE_MODULE_UPDATES;- } else {- process.env.FLUXER_DISABLE_MODULE_UPDATES = previous;- }- }-}--describe('disabling module updates', () => {- test('reads the environment variable like the other FLUXER_DISABLE switches', () => {- withModuleUpdatesEnv(undefined, () => assert.equal(shouldDisableModuleUpdatesForLaunch([]), false));- for (const value of ['1', 'true', 'YES', 'on']) {- withModuleUpdatesEnv(value, () => assert.equal(shouldDisableModuleUpdatesForLaunch([]), true, value));- }- withModuleUpdatesEnv('0', () => assert.equal(shouldDisableModuleUpdatesForLaunch([]), false));- });-- test('honours the launch flag with or without the fluxer prefix', () => {- withModuleUpdatesEnv(undefined, () => {- for (const flag of [- '--disable-module-updates',- '--fluxer-disable-module-updates',- '--disable-module-updates=1',- ]) {- assert.equal(shouldDisableModuleUpdatesForLaunch([flag]), true, flag);- }- assert.equal(shouldDisableModuleUpdatesForLaunch(['--fluxer-update']), false);- });- });-- test('defaults to updating and drops values that are not booleans', () => {- loadSettings(undefined);- assert.equal(getDesktopTroubleshootingSettings().disableModuleUpdates, false);- for (const value of ['true', 1, null, {}]) {- loadSettings({disableModuleUpdates: value});- assert.equal(getDesktopTroubleshootingSettings().disableModuleUpdates, false, String(value));- }- });-- test('the launch flag or the persisted setting disables updates for the launch', () => {- withModuleUpdatesEnv(undefined, () => {- const settings = {disableHardwareAcceleration: false, disableModuleUpdates: false};- assert.equal(resolveEffectiveDesktopTroubleshootingSettings(settings, [], 'win32').disableModuleUpdates, false);- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings(settings, ['--disable-module-updates'], 'darwin')- .disableModuleUpdates,- true,- );- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings({...settings, disableModuleUpdates: true}, [], 'linux')- .disableModuleUpdates,- true,- );- });- });-- test('turning the setting back off restores updating without touching hardware acceleration', () => {- const userDataPath = loadSettings({disableHardwareAcceleration: true, disableModuleUpdates: true});- assert.equal(getDesktopTroubleshootingSettings().disableModuleUpdates, true);- setDesktopTroubleshootingSettings({disableModuleUpdates: false});- assert.deepEqual(readPersisted(userDataPath), {disableHardwareAcceleration: true, disableModuleUpdates: false});- loadDesktopConfig(userDataPath);- withModuleUpdatesEnv(undefined, () => {- assert.equal(- resolveEffectiveDesktopTroubleshootingSettings(getDesktopTroubleshootingSettings(), [], 'win32')- .disableModuleUpdates,- false,- );- });- });-- test('keeps the launch answer when the persisted setting changes without a restart', () => {- withModuleUpdatesEnv(undefined, () => {- loadSettings({disableModuleUpdates: true});- assert.equal(isUpdateOnDemandLaunch(), true);- setDesktopTroubleshootingSettings({disableModuleUpdates: false});- assert.equal(isUpdateOnDemandLaunch(), true);- });- });-- test('the persisted setting moves updates on demand and leaves the in-app update check on', () => {- withModuleUpdatesEnv(undefined, () => {- loadSettings({disableModuleUpdates: true});- assert.equal(isUpdateOnDemandLaunch(), true);- assert.equal(shouldDisableModuleUpdatesForLaunch([]), false);- });- });-- test('the environment variable turns updates off entirely, even with the setting on', () => {- withModuleUpdatesEnv('1', () => {- loadSettings({disableModuleUpdates: true});- assert.equal(isUpdateOnDemandLaunch(), false);- assert.equal(shouldDisableModuleUpdatesForLaunch([]), true);- });- });-});diff --git a/fluxer_desktop/src/main/ModuleVersion.test.mjs b/fluxer_desktop/src/main/ModuleVersion.test.mjsdeleted file mode 100644index 14a053ec3..000000000--- a/fluxer_desktop/src/main/ModuleVersion.test.mjs+++ /dev/null@@ -1,108 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import './LocalAppTestSupport.test.mjs';--const {ModuleVersionMalformedError, compareModuleVersions, parseModuleVersion} = await import(- '@electron/main/ModuleVersion'-);--function compare(left, right) {- return compareModuleVersions(parseModuleVersion(left, 'left version'), parseModuleVersion(right, 'right version'));-}--const ASCENDING = [- '1.0.0-0',- '1.0.0-1',- '1.0.0-11',- '1.0.0-alpha',- '1.0.0-alpha.1',- '1.0.0-alpha.beta',- '1.0.0-beta',- '1.0.0-beta.2',- '1.0.0-beta.11',- '1.0.0-rc.1',- '1.0.0',- '1.0.1-alpha',- '1.0.1',- '1.1.0',- '2.0.0',- '99999999999999999999.0.0',-];--describe('compareModuleVersions', () => {- test('a prerelease sorts below the release it leads to', () => {- assert.equal(compare('1.0.0-rc.1', '1.0.0'), -1);- assert.equal(compare('1.0.0', '1.0.0-rc.1'), 1);- assert.equal(compare('2026.823.1-canary', '2026.823.1'), -1);- assert.equal(compare('1.0.0', '1.0.0'), 0);- assert.equal(compare('1.0.0-rc.1', '1.0.0-rc.1'), 0);- });-- test('a prerelease does not lift a version over a higher release', () => {- assert.equal(compare('1.0.1-rc.1', '1.0.0'), 1);- assert.equal(compare('1.0.0-rc.1', '0.9.9'), 1);- });-- test('numeric prerelease identifiers sort below textual ones', () => {- assert.equal(compare('1.0.0-1', '1.0.0-alpha'), -1);- assert.equal(compare('1.0.0-alpha', '1.0.0-1'), 1);- assert.equal(compare('1.0.0-alpha.1', '1.0.0-alpha.beta'), -1);- assert.equal(compare('1.0.0-alpha.beta', '1.0.0-alpha.1'), 1);- });-- test('numeric prerelease identifiers compare by magnitude, not lexically', () => {- assert.equal(compare('1.0.0-beta.2', '1.0.0-beta.11'), -1);- assert.equal(compare('1.0.0-beta.11', '1.0.0-beta.2'), 1);- });-- test('a longer prerelease sorts above its own prefix', () => {- assert.equal(compare('1.0.0-alpha', '1.0.0-alpha.1'), -1);- assert.equal(compare('1.0.0-alpha.1', '1.0.0-alpha'), 1);- });-- test('the whole precedence chain is a total order', () => {- for (let left = 0; left < ASCENDING.length; left += 1) {- assert.equal(compare(ASCENDING[left], ASCENDING[left]), 0, `${ASCENDING[left]} equals itself`);- for (let right = left + 1; right < ASCENDING.length; right += 1) {- assert.equal(compare(ASCENDING[left], ASCENDING[right]), -1, `${ASCENDING[left]} < ${ASCENDING[right]}`);- assert.equal(compare(ASCENDING[right], ASCENDING[left]), 1, `${ASCENDING[right]} > ${ASCENDING[left]}`);- }- }- });-- test('a major beyond the safe integer range still orders by magnitude', () => {- assert.equal(compare('99999999999999999999.0.0', '99999999999999999998.0.0'), 1);- assert.equal(compare('99999999999999999998.0.0', '99999999999999999999.0.0'), -1);- });-- test('build metadata takes no part in precedence', () => {- assert.equal(compare('1.0.0+build.1', '1.0.0+build.2'), 0);- assert.equal(compare('1.0.0-alpha+build.1', '1.0.0-alpha'), 0);- });-});--describe('parseModuleVersion', () => {- test('keeps the source it parsed', () => {- const version = parseModuleVersion('2026.823.1-rc.2+sha.abc', 'shell version');- assert.equal(version.source, '2026.823.1-rc.2+sha.abc');- assert.equal(version.major, 2026n);- assert.equal(version.minor, 823n);- assert.equal(version.patch, 1n);- });-- for (const value of ['2026.08.23', '1.0', '', '1', '1.0.0.0', '1.0.0-01', 'v1.0.0', ' 1.0.0', '1.0.0 ']) {- test(`rejects ${JSON.stringify(value)}`, () => {- assert.throws(- () => parseModuleVersion(value, 'manifest shell.minimum_version'),- (error) => {- assert.ok(error instanceof ModuleVersionMalformedError);- assert.equal(error.name, 'ModuleVersionMalformedError');- assert.equal(error.message, `manifest shell.minimum_version is not a valid semantic version: ${value}`);- return true;- },- );- });- }-});diff --git a/fluxer_desktop/src/main/ShellSelfUpdate.test.mjs b/fluxer_desktop/src/main/ShellSelfUpdate.test.mjsdeleted file mode 100644index 8818fdbd5..000000000--- a/fluxer_desktop/src/main/ShellSelfUpdate.test.mjs+++ /dev/null@@ -1,669 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {tmpdir} from 'node:os';-import path from 'node:path';-import {beforeEach, describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const velopack = {- pendingRestart: null,- pendingRestartError: null,- checkResult: null,- checkError: null,- checkPromise: null,- downloadError: null,- downloadProgress: [],- downloadPromise: null,- installError: null,- currentVersion: '2026.800.0',- calls: [],- constructedWith: [],-};--class FakeUpdateManager {- constructor(urlOrPath) {- velopack.constructedWith.push(urlOrPath);- }-- getCurrentVersion() {- return velopack.currentVersion;- }-- getUpdatePendingRestart() {- velopack.calls.push('getUpdatePendingRestart');- if (velopack.pendingRestartError != null) throw velopack.pendingRestartError;- return velopack.pendingRestart;- }-- async checkForUpdatesAsync() {- velopack.calls.push('checkForUpdatesAsync');- if (velopack.checkPromise != null) return await velopack.checkPromise;- if (velopack.checkError != null) throw velopack.checkError;- return velopack.checkResult;- }-- async downloadUpdateAsync(_update, onProgress) {- velopack.calls.push('downloadUpdateAsync');- for (const percent of velopack.downloadProgress) {- onProgress(percent);- }- if (velopack.downloadPromise != null) return await velopack.downloadPromise;- if (velopack.downloadError != null) throw velopack.downloadError;- }-- waitExitThenApplyUpdate(update, silent, restart) {- velopack.calls.push(`waitExitThenApplyUpdate:${update.id}:${silent}:${restart}`);- if (velopack.installError != null) throw velopack.installError;- }-}--const requireFromHere = createRequire(import.meta.url);-const VELOPACK_PATH = requireFromHere.resolve('velopack');-requireFromHere.cache[VELOPACK_PATH] = {- id: VELOPACK_PATH,- filename: VELOPACK_PATH,- loaded: true,- exports: {UpdateManager: FakeUpdateManager},-};--class FakeAutoUpdater {- constructor() {- this.handlers = new Map();- this.feedUrls = [];- this.checks = 0;- this.installs = 0;- this.checkError = null;- this.installError = null;- }-- on(eventName, listener) {- const existing = this.handlers.get(eventName) ?? [];- existing.push(listener);- this.handlers.set(eventName, existing);- return this;- }-- removeListener(eventName, listener) {- const existing = this.handlers.get(eventName) ?? [];- this.handlers.set(- eventName,- existing.filter((entry) => entry !== listener),- );- return this;- }-- listenerCount(eventName) {- return (this.handlers.get(eventName) ?? []).length;- }-- totalListenerCount() {- let total = 0;- for (const listeners of this.handlers.values()) {- total += listeners.length;- }- return total;- }-- emit(eventName, ...args) {- for (const listener of [...(this.handlers.get(eventName) ?? [])]) {- listener(...args);- }- }-- setFeedURL(options) {- this.feedUrls.push(options);- }-- checkForUpdates() {- this.checks += 1;- if (this.checkError != null) throw this.checkError;- }-- quitAndInstall() {- this.installs += 1;- if (this.installError != null) throw this.installError;- }-}--const autoUpdater = new FakeAutoUpdater();-const quits = [];-const userDataPath = mkdtempSync(path.join(tmpdir(), 'fluxer-shell-self-update-'));-const applyStatePath = path.join(userDataPath, 'update-apply-state.json');-process.on('exit', () => {- rmSync(userDataPath, {recursive: true, force: true});-});--installElectronStub({- app: {- getVersion: () => '2026.800.0',- getPath: () => userDataPath,- quit: () => {- quits.push('quit');- },- },- autoUpdater,-});--const {- getElectronUpdateFeedUrl,- resetElectronUpdateSessionForTests,- runShellSelfUpdate,- SHELL_SELF_UPDATE_CHECK_TIMEOUT_MS,- SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS,-} = await import('@electron/main/ShellSelfUpdate');-const {getUpdateBaseUrl} = await import('@electron/main/ShellDownloadFormats');--function createHooks() {- const calls = [];- return {- calls,- hooks: {- onDownloading: (progress) => {- calls.push({hook: 'downloading', progress});- },- onRestarting: () => {- calls.push({hook: 'restarting'});- },- },- };-}--function settle() {- return new Promise((resolve) => {- setImmediate(resolve);- });-}--function selfUpdateTest(name, body) {- test(name, async () => {- const timers = [];- const originalSetTimeout = globalThis.setTimeout;- const originalClearTimeout = globalThis.clearTimeout;- globalThis.setTimeout = (callback, delayMs) => {- const timer = {- callback,- delayMs,- cleared: false,- unref() {- return this;- },- };- timers.push(timer);- return timer;- };- globalThis.clearTimeout = (timer) => {- if (timer != null && typeof timer === 'object') {- timer.cleared = true;- }- };- try {- await body({- timers,- start: (updater, hooks) => runShellSelfUpdate({capability: 'self-update', updater}, hooks),- fireTimer: (delayMs) => {- const timer = timers.find((entry) => entry.delayMs === delayMs);- assert.ok(timer != null, `no timer armed at ${delayMs}ms`);- assert.equal(timer.cleared, false, `the timer at ${delayMs}ms was already disarmed`);- timer.callback();- },- timerCleared: (delayMs) => timers.find((entry) => entry.delayMs === delayMs)?.cleared ?? null,- stillPending: async (promise) => {- let resolved = false;- void promise.then(() => {- resolved = true;- });- for (let turn = 0; turn < 8; turn += 1) {- await settle();- }- return !resolved;- },- });- } finally {- globalThis.setTimeout = originalSetTimeout;- globalThis.clearTimeout = originalClearTimeout;- }- });-}--beforeEach(() => {- velopack.pendingRestart = null;- velopack.pendingRestartError = null;- velopack.checkResult = null;- velopack.checkError = null;- velopack.checkPromise = null;- velopack.downloadError = null;- velopack.downloadProgress = [];- velopack.downloadPromise = null;- velopack.installError = null;- velopack.currentVersion = '2026.800.0';- velopack.calls.length = 0;- rmSync(applyStatePath, {force: true});- velopack.constructedWith.length = 0;- autoUpdater.handlers.clear();- resetElectronUpdateSessionForTests();- autoUpdater.feedUrls.length = 0;- autoUpdater.checks = 0;- autoUpdater.installs = 0;- autoUpdater.checkError = null;- autoUpdater.installError = null;- quits.length = 0;-});--describe('velopack self update', () => {- selfUpdateTest('talks to the same feed the in-app updater uses', async ({start}) => {- const {hooks} = createHooks();-- await start('velopack', hooks);-- assert.deepEqual(velopack.constructedWith, [getUpdateBaseUrl()]);- });-- selfUpdateTest('a feed with nothing newer resolves without ever touching the splash', async ({start}) => {- const {calls, hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {reason: 'no-update', detail: null});- assert.deepEqual(calls, []);- assert.deepEqual(velopack.calls, ['getUpdatePendingRestart', 'checkForUpdatesAsync']);- });-- selfUpdateTest('a failed check resolves with the reason so the caller can fall back', async ({start}) => {- velopack.checkError = new Error('the feed is a 404');- const {hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {reason: 'check-failed', detail: 'the feed is a 404'});- });-- selfUpdateTest('a failed staging probe never reaches the network', async ({start}) => {- velopack.pendingRestartError = new Error('the packages directory is unreadable');- const {hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {- reason: 'check-failed',- detail: 'the packages directory is unreadable',- });- assert.deepEqual(velopack.calls, ['getUpdatePendingRestart']);- });-- selfUpdateTest('a lost update lock resolves as a download failure rather than retrying forever', async ({start}) => {- velopack.checkResult = {id: 'v2'};- velopack.downloadProgress = [0, 40];- velopack.downloadError = new Error('another update operation is in progress');- const {calls, hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {- reason: 'download-failed',- detail: 'another update operation is in progress',- });- assert.deepEqual(calls, [- {hook: 'downloading', progress: 0},- {hook: 'downloading', progress: 0},- {hook: 'downloading', progress: 40},- ]);- });-- selfUpdateTest(- 'a downloaded update restarts the shell explicitly and never resolves',- async ({start, stillPending}) => {- velopack.checkResult = {id: 'v2'};- velopack.downloadProgress = [12, 100];- const {calls, hooks} = createHooks();-- assert.equal(await stillPending(start('velopack', hooks)), true);- assert.deepEqual(calls, [- {hook: 'downloading', progress: 0},- {hook: 'downloading', progress: 12},- {hook: 'downloading', progress: 100},- {hook: 'restarting'},- ]);- assert.deepEqual(velopack.calls, [- 'getUpdatePendingRestart',- 'checkForUpdatesAsync',- 'downloadUpdateAsync',- 'waitExitThenApplyUpdate:v2:true:true',- ]);- assert.deepEqual(- quits,- ['quit'],- 'the restart goes through app.quit so the will-quit cleanup checkpoints the app store',- );- },- );-- selfUpdateTest('an update already staged on disk skips straight to the restart', async ({start, stillPending}) => {- velopack.pendingRestart = {id: 'staged'};- const {calls, hooks} = createHooks();-- assert.equal(await stillPending(start('velopack', hooks)), true);- assert.deepEqual(calls, [{hook: 'restarting'}]);- assert.deepEqual(velopack.calls, ['getUpdatePendingRestart', 'waitExitThenApplyUpdate:staged:true:true']);- });-- selfUpdateTest('an apply that never landed falls back instead of applying it again', async ({start}) => {- writeFileSync(applyStatePath, JSON.stringify({version: '2026.900.0', attemptedAt: Date.now() - 60_000}));- velopack.pendingRestart = {id: 'staged', Version: '2026.900.0'};- const {calls, hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {- reason: 'install-failed',- detail: 'the last downloaded update was never installed',- });- assert.deepEqual(calls, []);- assert.deepEqual(velopack.calls, []);- assert.deepEqual(quits, []);- });-- selfUpdateTest(- 'an old apply that never landed retries from the feed instead of blocking every update',- async ({start, stillPending}) => {- writeFileSync(applyStatePath, JSON.stringify({version: '2026.900.0', attemptedAt: Date.now() - 3_600_000}));- velopack.pendingRestart = {id: 'staged', Version: '2026.900.0'};- velopack.checkResult = {id: 'v3', TargetFullRelease: {Version: '2026.950.0'}};- const {hooks} = createHooks();-- assert.equal(await stillPending(start('velopack', hooks)), true);- assert.deepEqual(velopack.calls, [- 'checkForUpdatesAsync',- 'downloadUpdateAsync',- 'waitExitThenApplyUpdate:v3:true:true',- ]);- assert.equal(JSON.parse(readFileSync(applyStatePath, 'utf8')).version, '2026.950.0');- },- );-- selfUpdateTest('an apply that landed is forgotten and the next one is recorded', async ({start, stillPending}) => {- writeFileSync(applyStatePath, JSON.stringify({version: '2026.800.0', attemptedAt: 1}));- velopack.pendingRestart = {id: 'staged', Version: '2026.900.0'};- const {hooks} = createHooks();-- assert.equal(await stillPending(start('velopack', hooks)), true);- assert.deepEqual(velopack.calls, ['getUpdatePendingRestart', 'waitExitThenApplyUpdate:staged:true:true']);- assert.equal(JSON.parse(readFileSync(applyStatePath, 'utf8')).version, '2026.900.0');- });-- selfUpdateTest(- 'an install that throws resolves instead of leaving the restart message up forever',- async ({start}) => {- velopack.pendingRestart = {id: 'staged'};- velopack.installError = new Error('the updater binary is missing');- const {hooks} = createHooks();-- assert.deepEqual(await start('velopack', hooks), {- reason: 'install-failed',- detail: 'the updater binary is missing',- });- assert.deepEqual(quits, []);- },- );-- selfUpdateTest('a check that never answers hits the check deadline', async ({start, fireTimer, timerCleared}) => {- let releaseCheck = () => {};- velopack.checkPromise = new Promise((resolve) => {- releaseCheck = () => {- resolve(null);- };- });- const {calls, hooks} = createHooks();- const promise = start('velopack', hooks);- await settle();-- fireTimer(SHELL_SELF_UPDATE_CHECK_TIMEOUT_MS);-- assert.deepEqual(await promise, {reason: 'timed-out', detail: 'the update check produced no answer'});-- releaseCheck();- await settle();-- assert.deepEqual(calls, []);- assert.equal(timerCleared(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS), true);- });-- selfUpdateTest(- 'a download that never finishes hits the total deadline, and the check deadline is already gone',- async ({start, fireTimer, timerCleared}) => {- velopack.checkResult = {id: 'v2'};- velopack.downloadPromise = new Promise(() => {});- const {hooks} = createHooks();- const promise = start('velopack', hooks);- await settle();-- assert.equal(timerCleared(SHELL_SELF_UPDATE_CHECK_TIMEOUT_MS), true);-- fireTimer(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS);-- assert.deepEqual(await promise, {reason: 'timed-out', detail: 'the update did not finish'});- },- );-- selfUpdateTest(- 'a late download failure after a deadline never re-settles the promise',- async ({start, fireTimer}) => {- velopack.checkResult = {id: 'v2'};- let failDownload = () => {};- velopack.downloadPromise = new Promise((_resolve, reject) => {- failDownload = () => {- reject(new Error('too late'));- };- });- const {calls, hooks} = createHooks();- const promise = start('velopack', hooks);- await settle();- fireTimer(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS);- const failure = await promise;-- failDownload();- await settle();-- assert.deepEqual(failure, {reason: 'timed-out', detail: 'the update did not finish'});- assert.deepEqual(await promise, failure);- assert.deepEqual(calls, [{hook: 'downloading', progress: 0}]);- },- );-});--describe('velopack self update across repeated clicks', () => {- selfUpdateTest(- 'a second run for the same version joins the download already in flight',- async ({start, fireTimer}) => {- velopack.checkResult = {id: 'v3', TargetFullRelease: {Version: '2026.900.0'}};- let finishDownload = () => {};- velopack.downloadPromise = new Promise((resolve) => {- finishDownload = resolve;- });- const first = start('velopack', createHooks().hooks);- await settle();- fireTimer(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS);- assert.deepEqual(await first, {reason: 'timed-out', detail: 'the update did not finish'});-- const {calls, hooks} = createHooks();- void start('velopack', hooks);- await settle();- finishDownload();- await settle();- await settle();-- assert.equal(velopack.calls.filter((call) => call === 'downloadUpdateAsync').length, 1);- assert.deepEqual(calls, [{hook: 'downloading', progress: 0}, {hook: 'restarting'}]);- assert.deepEqual(quits, ['quit']);- },- );-});--describe('electron self update', () => {- selfUpdateTest('points squirrel at the json feed with an identifying user agent', async ({start}) => {- const {hooks} = createHooks();- const promise = start('electron', hooks);- autoUpdater.emit('update-not-available');- await promise;-- assert.equal(getElectronUpdateFeedUrl(), `${getUpdateBaseUrl()}/RELEASES.json`);- assert.deepEqual(autoUpdater.feedUrls, [- {- url: getElectronUpdateFeedUrl(),- serverType: 'json',- headers: {'User-Agent': `Fluxer/2026.800.0 (${process.platform}: ${process.arch})`},- },- ]);- assert.equal(autoUpdater.checks, 1);- });-- selfUpdateTest('nothing newer resolves and later runs reuse the same four listeners', async ({start}) => {- const {calls, hooks} = createHooks();- const promise = start('electron', hooks);-- assert.equal(autoUpdater.totalListenerCount(), 4);-- autoUpdater.emit('update-not-available');-- assert.deepEqual(await promise, {reason: 'no-update', detail: null});- assert.deepEqual(calls, []);-- const again = start('electron', createHooks().hooks);- autoUpdater.emit('update-not-available');- await again;-- assert.equal(autoUpdater.totalListenerCount(), 4);- assert.equal(autoUpdater.checks, 2);- });-- selfUpdateTest(- 'a check that throws synchronously resolves rather than hanging on a feed that was never set',- async ({start}) => {- autoUpdater.checkError = new Error('Update URL is not set');- const {hooks} = createHooks();-- assert.deepEqual(await start('electron', hooks), {reason: 'check-failed', detail: 'Update URL is not set'});-- autoUpdater.checkError = null;- const retry = start('electron', createHooks().hooks);- autoUpdater.emit('update-not-available');- assert.deepEqual(await retry, {reason: 'no-update', detail: null});- assert.equal(autoUpdater.checks, 2);- },- );-- selfUpdateTest('an error before the download is a check failure, after it a download failure', async ({start}) => {- const first = start('electron', createHooks().hooks);- autoUpdater.emit('error', new Error('dns'));- assert.deepEqual(await first, {reason: 'check-failed', detail: 'dns'});-- const {calls, hooks} = createHooks();- const second = start('electron', hooks);- autoUpdater.emit('update-available');- autoUpdater.emit('error', new Error('the bundle is not signed'));-- assert.deepEqual(await second, {reason: 'download-failed', detail: 'the bundle is not signed'});- assert.deepEqual(calls, [{hook: 'downloading', progress: null}]);- });-- selfUpdateTest(- 'squirrel gives no progress, so the splash is told to keep its placeholder',- async ({start, stillPending, timerCleared}) => {- const {calls, hooks} = createHooks();- const promise = start('electron', hooks);-- autoUpdater.emit('update-available');-- assert.deepEqual(calls, [{hook: 'downloading', progress: null}]);- assert.equal(timerCleared(SHELL_SELF_UPDATE_CHECK_TIMEOUT_MS), true);- assert.equal(await stillPending(promise), true);- },- );-- selfUpdateTest('a downloaded update restarts the shell and never resolves', async ({start, stillPending}) => {- const {calls, hooks} = createHooks();- const promise = start('electron', hooks);-- autoUpdater.emit('update-available');- autoUpdater.emit('update-downloaded');-- assert.deepEqual(calls, [{hook: 'downloading', progress: null}, {hook: 'restarting'}]);- assert.equal(autoUpdater.installs, 1);- assert.equal(await stillPending(promise), true);- });-- selfUpdateTest(- 'an install that throws resolves instead of stranding the user on the restart message',- async ({start}) => {- autoUpdater.installError = new Error('the app is on a read only mount');- const {hooks} = createHooks();- const promise = start('electron', hooks);-- autoUpdater.emit('update-downloaded');-- assert.deepEqual(await promise, {reason: 'install-failed', detail: 'the app is on a read only mount'});- },- );-- selfUpdateTest(- 'a silent squirrel hits the check deadline and a late download installs on the next run',- async ({start, fireTimer, stillPending}) => {- const {hooks} = createHooks();- const promise = start('electron', hooks);-- fireTimer(SHELL_SELF_UPDATE_CHECK_TIMEOUT_MS);-- assert.deepEqual(await promise, {reason: 'timed-out', detail: 'the update check produced no answer'});-- autoUpdater.emit('update-downloaded');-- assert.equal(autoUpdater.installs, 0);-- const {calls, hooks: nextHooks} = createHooks();- const next = start('electron', nextHooks);-- assert.deepEqual(calls, [{hook: 'restarting'}]);- assert.equal(autoUpdater.installs, 1);- assert.equal(autoUpdater.checks, 1);- assert.equal(await stillPending(next), true);- },- );-- selfUpdateTest(- 'a second run while squirrel is still downloading joins it instead of asking squirrel again',- async ({start, fireTimer, stillPending}) => {- const first = start('electron', createHooks().hooks);- autoUpdater.emit('update-available');- fireTimer(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS);- assert.deepEqual(await first, {reason: 'timed-out', detail: 'the update did not finish'});-- const {calls, hooks} = createHooks();- const second = start('electron', hooks);-- assert.equal(autoUpdater.checks, 1);- assert.deepEqual(calls, [{hook: 'downloading', progress: null}]);- assert.equal(await stillPending(second), true);-- autoUpdater.emit('update-downloaded');-- assert.deepEqual(calls, [{hook: 'downloading', progress: null}, {hook: 'restarting'}]);- assert.equal(autoUpdater.installs, 1);- },- );-- selfUpdateTest(- 'two runs in flight both settle on one squirrel answer and squirrel is asked once',- async ({start}) => {- const first = start('electron', createHooks().hooks);- const second = start('electron', createHooks().hooks);-- autoUpdater.emit('error', new Error('dns'));-- assert.deepEqual(await first, {reason: 'check-failed', detail: 'dns'});- assert.deepEqual(await second, {reason: 'check-failed', detail: 'dns'});- assert.equal(autoUpdater.checks, 1);- },- );-- selfUpdateTest('a download that never finishes hits the total deadline', async ({start, fireTimer}) => {- const {hooks} = createHooks();- const promise = start('electron', hooks);-- autoUpdater.emit('update-available');- fireTimer(SHELL_SELF_UPDATE_TOTAL_TIMEOUT_MS);-- assert.deepEqual(await promise, {reason: 'timed-out', detail: 'the update did not finish'});- });-});diff --git a/fluxer_desktop/src/main/ShellUpdateCapability.test.mjs b/fluxer_desktop/src/main/ShellUpdateCapability.test.mjsdeleted file mode 100644index 9783b83f2..000000000--- a/fluxer_desktop/src/main/ShellUpdateCapability.test.mjs+++ /dev/null@@ -1,293 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const events = [];-const ipcRegistrations = [];-let openExternalFailure = null;--class FakeWebContents {- constructor() {- this.sent = [];- this.destroyed = false;- }-- on() {}-- setWindowOpenHandler() {}-- isDestroyed() {- return this.destroyed;- }-- send(channel, payload) {- this.sent.push({channel, payload});- }-}--class FakeBrowserWindow {- constructor() {- this.webContents = new FakeWebContents();- this.destroyed = false;- this.visible = false;- }-- on() {}-- once() {}-- isDestroyed() {- return this.destroyed;- }-- isVisible() {- return this.visible;- }-- show() {- this.visible = true;- }-- showInactive() {- this.visible = true;- }-- hide() {- this.visible = false;- }-- setSkipTaskbar() {}-- setAlwaysOnTop() {}-- close() {- this.destroyed = true;- }-- destroy() {- this.destroyed = true;- }-- loadURL() {- return Promise.resolve();- }-}--installElectronStub({- app: {- isPackaged: true,- isReady: () => true,- getAppPath: () => process.cwd(),- getPath: () => process.cwd(),- quit: () => {- events.push('quit');- },- },- BrowserWindow: FakeBrowserWindow,- ipcMain: {- on: (channel, handler) => {- ipcRegistrations.push({channel, handler});- },- },- shell: {- openExternal: async (url) => {- if (openExternalFailure != null) {- const failure = openExternalFailure;- openExternalFailure = null;- throw failure;- }- events.push(`open:${url}`);- },- },-});--const {openExternalDeduped, shouldOpenExternalUrl} = await import('@electron/main/OpenExternal');-const {openSplashWindow} = await import('@electron/main/SplashWindow');-const {getDesktopDownloadArch} = await import('@electron/main/ShellDownloadFormats');-const {BUILD_CHANNEL} = await import('@electron/common/BuildChannel');-const {decideShellUpdatePlan, resolveShellUpdatePlan} = await import('@electron/main/ShellUpdateCapability');-const {DOWNLOAD_PAGE_URL} = await import('@electron/main/UpdaterDownloads');-const {armBlockedShellUpdate} = await import('@electron/main/ShellUpdateSplash');--const APPIMAGE_TARGET = {- installedPath: '/home/user/Applications/Fluxer.AppImage',- directory: '/home/user/Applications',-};--function emitIpc(channel, event, payload) {- for (const registration of ipcRegistrations) {- if (registration.channel === channel) {- registration.handler(event, payload);- }- }-}--function settle() {- return new Promise((resolve) => {- setImmediate(resolve);- });-}--function planFor(runtime) {- return decideShellUpdatePlan({- channel: 'canary',- packaged: true,- portable: false,- flatpak: false,- appImage: null,- platform: 'linux',- ...runtime,- });-}--describe('shell update capability', () => {- test('every runtime signal picks one updater, first match wins', () => {- assert.deepEqual(planFor({packaged: false, platform: 'win32'}), {- capability: 'manual-download',- reason: 'unpackaged',- });- assert.deepEqual(planFor({portable: true, platform: 'win32'}), {capability: 'manual-download', reason: 'platform'});- assert.deepEqual(planFor({flatpak: true, platform: 'linux'}), {capability: 'managed-package'});- assert.deepEqual(planFor({platform: 'win32'}), {capability: 'self-update', updater: 'velopack'});- assert.deepEqual(planFor({platform: 'darwin'}), {capability: 'self-update', updater: 'electron'});- assert.deepEqual(planFor({platform: 'linux', appImage: APPIMAGE_TARGET}), {- capability: 'self-update',- updater: 'appimage',- target: APPIMAGE_TARGET,- });- assert.deepEqual(planFor({platform: 'linux'}), {capability: 'managed-package'});- assert.deepEqual(planFor({platform: 'freebsd'}), {capability: 'manual-download', reason: 'platform'});- });-- test('only a writable AppImage updates itself on Linux, every other install belongs to its package manager', () => {- assert.deepEqual(planFor({platform: 'linux', appImage: APPIMAGE_TARGET}).capability, 'self-update');- for (const runtime of [- {platform: 'linux'},- {platform: 'linux', portable: true},- {platform: 'linux', portable: true, appImage: APPIMAGE_TARGET},- {platform: 'linux', appImage: null},- {platform: 'linux', flatpak: true},- ]) {- assert.deepEqual(planFor(runtime), {capability: 'managed-package'}, JSON.stringify(runtime));- }- for (const platform of ['win32', 'darwin']) {- assert.deepEqual(planFor({platform, portable: true}), {capability: 'manual-download', reason: 'platform'});- }- });-- test('a development shell never self-updates, because no feed publishes development builds', () => {- for (const platform of ['darwin', 'win32', 'linux']) {- assert.deepEqual(planFor({channel: 'development', platform, appImage: APPIMAGE_TARGET}), {- capability: 'manual-download',- reason: 'unpackaged',- });- }- assert.deepEqual(planFor({channel: 'stable', platform: 'darwin'}), {- capability: 'self-update',- updater: 'electron',- });- });-- test('a store runtime outranks a portable marker, so a sandboxed install is never offered a deb or rpm it cannot apply', () => {- assert.deepEqual(planFor({portable: true, flatpak: true, platform: 'linux'}), {capability: 'managed-package'});- assert.deepEqual(planFor({portable: true, appImage: APPIMAGE_TARGET, platform: 'linux'}), {- capability: 'managed-package',- });- assert.deepEqual(planFor({packaged: false, flatpak: true, platform: 'linux'}), {- capability: 'manual-download',- reason: 'unpackaged',- });- });-- test('resolves the live runtime through the same decision', () => {- assert.deepEqual(- resolveShellUpdatePlan(),- decideShellUpdatePlan({- channel: BUILD_CHANNEL,- packaged: true,- portable: false,- flatpak: false,- appImage: null,- platform: process.platform,- }),- );- });-});--describe('blocked shell update states', () => {- test('the download page is a channel aware page, never an artifact', () => {- assert.equal(shouldOpenExternalUrl(DOWNLOAD_PAGE_URL), true);- assert.equal(new URL(DOWNLOAD_PAGE_URL).pathname, '/download');- });-- test('the download arch collapses to the two we publish', () => {- assert.equal(getDesktopDownloadArch('arm64'), 'arm64');- assert.equal(getDesktopDownloadArch('x64'), 'x64');- assert.equal(getDesktopDownloadArch('ia32'), 'x64');- assert.equal(getDesktopDownloadArch('ppc64'), 'x64');- });-});--describe('arming the blocked shell update', () => {- test('the download action opens the allowlisted page and then quits', async () => {- const window = openSplashWindow();- events.length = 0;-- armBlockedShellUpdate();-- assert.deepEqual(window.webContents.sent.at(-1), {- channel: 'desktop-splash:state',- payload: {- status: 'blocked-shell-update',- current: null,- total: null,- progress: null,- seconds: null,- receivedBytes: null,- totalBytes: null,- bytesPerSecond: null,- action: {kind: 'download', label: 'Download update'},- message: null,- },- });-- emitIpc('desktop-splash:open-download', {sender: window.webContents});- await settle();-- assert.deepEqual(events, [`open:${DOWNLOAD_PAGE_URL}`, 'quit']);- });-- test('a download that cannot be opened still resolves the screen instead of stranding the user', async () => {- const window = openSplashWindow();- armBlockedShellUpdate();- events.length = 0;- openExternalFailure = new Error('no handler for https');-- emitIpc('desktop-splash:open-download', {sender: window.webContents});- await settle();-- assert.deepEqual(events, ['quit']);- });-- test('a protocol outside the allowlist never reaches the shell', async () => {- events.length = 0;-- for (const url of [- 'file:///etc/passwd',- 'javascript:alert(1)',- 'vbscript:msgbox(1)',- 'data:text/html,hello',- 'about:blank',- 'chrome://settings',- 'shell:Startup',- 'ms-appinstaller:?source=https://example.com',- 'a:payload',- ]) {- await assert.rejects(openExternalDeduped(url), /External URL open request blocked/, url);- }-- assert.deepEqual(events, []);- });-});diff --git a/fluxer_desktop/src/main/UpdateServerRetry.test.mjs b/fluxer_desktop/src/main/UpdateServerRetry.test.mjsdeleted file mode 100644index a2103e2a0..000000000--- a/fluxer_desktop/src/main/UpdateServerRetry.test.mjs+++ /dev/null@@ -1,146 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {nextUpdateServerRetryDelay, UPDATE_SERVER_RETRY_BASE_MS, UPDATE_SERVER_RETRY_CAP_MS, UpdateServerRetry} =- await import('@electron/main/UpdateServerRetry');--function fakeClock() {- const timers = [];- return {- schedule: (callback, delayMs) => {- const timer = {callback, delayMs, cancelled: false};- timers.push(timer);- return timer;- },- cancel: (timer) => {- timer.cancelled = true;- },- fireLast: () => {- const timer = timers.at(-1);- if (!timer.cancelled) timer.callback();- },- timers,- };-}--function settled(promise) {- let done = false;- promise.then(() => {- done = true;- });- return async () => {- await new Promise((resolve) => setImmediate(resolve));- return done;- };-}--describe('update server retry delay', () => {- test('doubles from the base and stops at the cap', () => {- const delays = [0, 1, 2, 3, 4, 5, 9].map((attempt) => nextUpdateServerRetryDelay(attempt, () => 1));-- assert.deepEqual(delays, [- UPDATE_SERVER_RETRY_BASE_MS,- UPDATE_SERVER_RETRY_BASE_MS * 2,- UPDATE_SERVER_RETRY_BASE_MS * 4,- UPDATE_SERVER_RETRY_BASE_MS * 8,- UPDATE_SERVER_RETRY_BASE_MS * 16,- UPDATE_SERVER_RETRY_CAP_MS,- UPDATE_SERVER_RETRY_CAP_MS,- ]);- });-- test('jitters down to half so a fleet behind one outage does not return in step', () => {- assert.equal(- nextUpdateServerRetryDelay(0, () => 0),- UPDATE_SERVER_RETRY_BASE_MS / 2,- );- });-});--describe('update server retry', () => {- test('a blocked splash retries by itself after the backoff, each wait longer than the last', async () => {- const clock = fakeClock();- const retry = new UpdateServerRetry({random: () => 1, schedule: clock.schedule, cancel: clock.cancel});-- const first = settled(retry.holdUntilNextAttempt());- assert.equal(retry.holding, true);- assert.equal(await first(), false);- clock.fireLast();- assert.equal(await first(), true);-- const second = settled(retry.holdUntilNextAttempt());- clock.fireLast();- assert.equal(await second(), true);-- assert.deepEqual(- clock.timers.map((timer) => timer.delayMs),- [UPDATE_SERVER_RETRY_BASE_MS, UPDATE_SERVER_RETRY_BASE_MS * 2],- );- });-- test('the network coming back cuts the wait short and starts the backoff over', async () => {- const clock = fakeClock();- const retry = new UpdateServerRetry({random: () => 1, schedule: clock.schedule, cancel: clock.cancel});-- const first = settled(retry.holdUntilNextAttempt());- clock.fireLast();- await first();- const second = settled(retry.holdUntilNextAttempt());- retry.networkReturned();-- assert.equal(await second(), true);- assert.equal(clock.timers.at(-1).cancelled, true);-- void retry.holdUntilNextAttempt();- assert.equal(clock.timers.at(-1).delayMs, UPDATE_SERVER_RETRY_BASE_MS);- });-- test('the network coming back also cuts short the sleep between the updater’s own attempts', async () => {- const clock = fakeClock();- const retry = new UpdateServerRetry({schedule: clock.schedule, cancel: clock.cancel});-- const sleeping = settled(retry.sleep(16000));- assert.equal(await sleeping(), false);- retry.networkReturned();-- assert.equal(await sleeping(), true);- assert.equal(retry.holding, false);- });-- test('the unreachable screen stays up through the silent checks and yields to the first real progress', async () => {- const clock = fakeClock();- const retry = new UpdateServerRetry({schedule: clock.schedule, cancel: clock.cancel});-- assert.equal(retry.endsHold('downloading'), false);-- void retry.holdUntilNextAttempt();- for (const status of ['checking', 'retry-wait', 'blocked-update-required']) {- assert.equal(retry.endsHold(status), false, status);- assert.equal(retry.holding, true, status);- }-- assert.equal(retry.endsHold('downloading'), true);- assert.equal(retry.holding, false);- assert.equal(retry.endsHold('launching'), false);- });-- test('a server that answered starts the backoff over for the next outage', () => {- const clock = fakeClock();- const retry = new UpdateServerRetry({random: () => 1, schedule: clock.schedule, cancel: clock.cancel});-- void retry.holdUntilNextAttempt();- void retry.holdUntilNextAttempt();- retry.endsHold('launching');- void retry.holdUntilNextAttempt();-- assert.deepEqual(- clock.timers.map((timer) => timer.delayMs),- [UPDATE_SERVER_RETRY_BASE_MS, UPDATE_SERVER_RETRY_BASE_MS * 2, UPDATE_SERVER_RETRY_BASE_MS],- );- });-});diff --git a/fluxer_desktop/src/main/WindowUpdateTakeover.test.mjs b/fluxer_desktop/src/main/WindowUpdateTakeover.test.mjsdeleted file mode 100644index 85deb1d8d..000000000--- a/fluxer_desktop/src/main/WindowUpdateTakeover.test.mjs+++ /dev/null@@ -1,252 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const openWindows = [];--class FakeWindow {- constructor(name, {vetoUnload = false, closable = true} = {}) {- this.name = name;- this.vetoUnload = vetoUnload;- this.closable = closable;- this.visible = true;- this.destroyed = false;- this.listeners = new Map();- this.unloadListeners = [];- this.webContents = {- once: (event, listener) => {- if (event === 'will-prevent-unload') this.unloadListeners.push(listener);- },- };- openWindows.push(this);- }-- once(event, listener) {- this.listeners.set(event, listener);- }-- isDestroyed() {- return this.destroyed;- }-- isVisible() {- return this.visible;- }-- isClosable() {- return this.closable;- }-- hide() {- this.visible = false;- }-- show() {- this.visible = true;- }-- close() {- if (!this.closable) return;- if (this.vetoUnload) {- let prevented = false;- for (const listener of this.unloadListeners) {- listener({preventDefault: () => (prevented = true)});- }- if (!prevented) return;- }- this.destroy();- }-- destroy() {- this.destroyed = true;- this.visible = false;- this.listeners.get('closed')?.();- }-}--const noop = () => undefined;-const ipcHandlers = new Map();--class ElectronEmitterStub {- on() {- return this;- }-- once() {- return this;- }-- off() {- return this;- }-- removeListener() {- return this;- }-- removeAllListeners() {- return this;- }-- emit() {- return false;- }-}--installElectronStub({- app: Object.assign(new ElectronEmitterStub(), {- isReady: () => true,- isPackaged: false,- getPath: () => '/tmp/fluxer-desktop-test',- getAppPath: () => '/tmp/fluxer-desktop-test',- getVersion: () => '0.0.0',- getLocale: () => 'en-US',- setPath: noop,- exit: noop,- quit: noop,- whenReady: () => Promise.resolve(),- commandLine: {appendSwitch: noop, appendArgument: noop},- }),- BrowserWindow: class extends ElectronEmitterStub {- static fromWebContents() {- return null;- }-- static getAllWindows() {- return openWindows.filter((window) => !window.isDestroyed());- }-- static getFocusedWindow() {- return null;- }- },- Menu: {buildFromTemplate: () => ({}), setApplicationMenu: noop},- Notification: Object.assign(class extends ElectronEmitterStub {}, {isSupported: () => false}),- clipboard: {},- desktopCapturer: {},- dialog: {showMessageBoxSync: () => 0, showErrorBox: noop},- globalShortcut: {},- ipcMain: Object.assign(new ElectronEmitterStub(), {- handle: (channel, handler) => {- ipcHandlers.set(channel, handler);- },- removeHandler: noop,- }),- nativeImage: {createFromPath: () => ({isEmpty: () => true})},- nativeTheme: new ElectronEmitterStub(),- net: {fetch: () => Promise.reject(new Error('outbound network is not available in tests'))},- powerMonitor: new ElectronEmitterStub(),- powerSaveBlocker: {start: () => 0, stop: noop, isStarted: () => false},- protocol: {registerSchemesAsPrivileged: noop, handle: noop, unhandle: noop, isProtocolHandled: () => false},- safeStorage: {isEncryptionAvailable: () => false},- screen: Object.assign(new ElectronEmitterStub(), {- getPrimaryDisplay: () => ({workAreaSize: {width: 1920, height: 1080}}),- getAllDisplays: () => [],- }),- session: {defaultSession: {}},- shell: {openExternal: noop, showItemInFolder: noop},- systemPreferences: {},-});--const {- beginMainWindowTakeover,- closeAppWindowsForUpdate,- endMainWindowTakeover,- hideAppWindowsForUpdate,- onMainWindowTakeoverEnded,- restoreAppWindowsAfterUpdate,- isMainWindowTakenOver,- showWindow,-} = await import('@electron/main/Window');--describe('the update takes the app windows over', () => {- test('the windows hide at once and only the splash stays on screen', () => {- openWindows.length = 0;- const splash = new FakeWindow('splash');- const main = new FakeWindow('main');- const popout = new FakeWindow('voice popout');-- hideAppWindowsForUpdate(splash);-- assert.equal(splash.isVisible(), true);- assert.equal(main.isVisible(), false);- assert.equal(popout.isVisible(), false);- });-- test('a check that finds nothing gives back exactly the windows it hid', () => {- openWindows.length = 0;- const splash = new FakeWindow('splash');- const main = new FakeWindow('main');- const trayHidden = new FakeWindow('hidden popout');- trayHidden.hide();-- const hidden = hideAppWindowsForUpdate(splash);- restoreAppWindowsAfterUpdate(hidden);-- assert.deepEqual(hidden, [main]);- assert.equal(main.isVisible(), true);- assert.equal(trayHidden.isVisible(), false, 'a window the user had hidden stays hidden');- });-- test('a window that cannot be closed is destroyed at once instead of holding the update back', async () => {- openWindows.length = 0;- const splash = new FakeWindow('splash');- const guard = new FakeWindow('screen capture guard', {closable: false});- const startedAt = Date.now();-- await closeAppWindowsForUpdate(splash);-- assert.equal(guard.isDestroyed(), true);- assert.ok(Date.now() - startedAt < 1000, 'the 5 second close deadline never came into it');- });-- test('ending the takeover tells its listeners once', () => {- let ended = 0;- const stop = onMainWindowTakeoverEnded(() => {- ended += 1;- });- beginMainWindowTakeover(() => undefined);- endMainWindowTakeover();- endMainWindowTakeover();- stop();-- assert.equal(ended, 1);- });-- test('the windows really close, past a renderer that would veto the unload', async () => {- openWindows.length = 0;- const splash = new FakeWindow('splash');- const main = new FakeWindow('main', {vetoUnload: true});- const popout = new FakeWindow('theme studio');-- await closeAppWindowsForUpdate(splash);-- assert.equal(main.isDestroyed(), true);- assert.equal(popout.isDestroyed(), true);- assert.equal(splash.isDestroyed(), false);- });-- test('showing the app during the update raises the splash instead of a window that is gone', () => {- let focused = 0;- beginMainWindowTakeover(() => {- focused += 1;- });- assert.equal(isMainWindowTakenOver(), true);-- showWindow();-- assert.equal(focused, 1);- endMainWindowTakeover();- assert.equal(isMainWindowTakenOver(), false);- showWindow();- assert.equal(focused, 1);- });-- test('close to hide never swallows the close the update asks for', () => {- const source = readFileSync(new URL('./Window.ts', import.meta.url), 'utf8');- assert.match(source, /if \(!isQuitting && !closingMainWindowForUpdate && shouldHideMainWindowOnClose\(\)\) \{/);- });-});