A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(desktop): retire node:test suite for windows, storage, IPC
Hampus8f4271f79da0
diff --git a/fluxer_desktop/src/common/BuilderShellVersion.test.mjs b/fluxer_desktop/src/common/BuilderShellVersion.test.mjsdeleted file mode 100644index fcf813d13..000000000--- a/fluxer_desktop/src/common/BuilderShellVersion.test.mjs+++ /dev/null@@ -1,68 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import {createRequire} from 'node:module';-import os from 'node:os';-import path from 'node:path';-import {after, describe, test} from 'node:test';--const require = createRequire(import.meta.url);-const DESKTOP_DIR = path.resolve(import.meta.dirname, '..', '..');-const PREFLIGHT_MODULES = path.join('src', 'main', 'NativeModulePreflightModules.json');-const temporaryRoots = [];--after(() => {- for (const root of temporaryRoots) {- fs.rmSync(root, {recursive: true, force: true});- }-});--function loadMetadataVersion({version, rendererVersionJson}) {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'builder-shell-version-'));- temporaryRoots.push(root);- fs.copyFileSync(- path.join(DESKTOP_DIR, 'electron-builder.config.cjs'),- path.join(root, 'electron-builder.config.cjs'),- );- fs.mkdirSync(path.join(root, 'src', 'main'), {recursive: true});- fs.copyFileSync(path.join(DESKTOP_DIR, PREFLIGHT_MODULES), path.join(root, PREFLIGHT_MODULES));- if (rendererVersionJson != null) {- fs.mkdirSync(path.join(root, 'dist', 'renderer'), {recursive: true});- fs.writeFileSync(path.join(root, 'dist', 'renderer', 'version.json'), rendererVersionJson);- }- const previous = process.env.VERSION;- if (version == null) {- delete process.env.VERSION;- } else {- process.env.VERSION = version;- }- try {- return require(path.join(root, 'electron-builder.config.cjs')).extraMetadata.version;- } finally {- if (previous === undefined) {- delete process.env.VERSION;- } else {- process.env.VERSION = previous;- }- }-}--describe('the packaged shell version', () => {- test('comes from VERSION whenever it is set', () => {- assert.equal(- loadMetadataVersion({version: '2026.1014.2', rendererVersionJson: '{"version":"2026.1014.9"}'}),- '2026.1014.2',- );- });-- test('falls back to the bundled renderer version when VERSION is unset', () => {- assert.equal(loadMetadataVersion({rendererVersionJson: '{"version":"2026.1014.9"}'}), '2026.1014.9');- });-- test('keeps the package.json version when the renderer has no numeric version', () => {- assert.equal(loadMetadataVersion({rendererVersionJson: '{"version":"dev"}'}), undefined);- assert.equal(loadMetadataVersion({rendererVersionJson: 'null'}), undefined);- assert.equal(loadMetadataVersion({}), undefined);- });-});diff --git a/fluxer_desktop/src/common/ChannelIsolation.test.mjs b/fluxer_desktop/src/common/ChannelIsolation.test.mjsdeleted file mode 100644index f39951e03..000000000--- a/fluxer_desktop/src/common/ChannelIsolation.test.mjs+++ /dev/null@@ -1,75 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import {createRequire} from 'node:module';-import path from 'node:path';-import {describe, test} from 'node:test';--const require = createRequire(import.meta.url);-const DESKTOP_DIR = path.resolve(import.meta.dirname, '..', '..');-const CONFIG_PATH = path.join(DESKTOP_DIR, 'electron-builder.config.cjs');-const CHANNELS = ['stable', 'canary', 'development'];--function loadBuilderConfig(channel) {- const previous = process.env.BUILD_CHANNEL;- process.env.BUILD_CHANNEL = channel;- try {- delete require.cache[CONFIG_PATH];- return require(CONFIG_PATH);- } finally {- delete require.cache[CONFIG_PATH];- if (previous === undefined) {- delete process.env.BUILD_CHANNEL;- } else {- process.env.BUILD_CHANNEL = previous;- }- }-}--const configs = Object.fromEntries(CHANNELS.map((channel) => [channel, loadBuilderConfig(channel)]));--function assertDistinct(label, select) {- const values = CHANNELS.map((channel) => select(configs[channel]));- assert.equal(new Set(values).size, values.length, `two channels share a ${label}: ${JSON.stringify(values)}`);-}--describe('installed channels stay apart', () => {- test('each channel installs under its own bundle id, product name, package name and icon set', () => {- assertDistinct('bundle id', (config) => config.appId);- assertDistinct('product name', (config) => config.productName);- assertDistinct('package name', (config) => config.extraMetadata.name);- assertDistinct('mac icon', (config) => config.mac.icon);- assertDistinct('protocol registration name', (config) => config.protocols[0].name);- });-- test('the development app registers its own deep link scheme instead of fluxer://', () => {- const schemes = configs.development.protocols.flatMap((protocol) => protocol.schemes);- assert.deepEqual(schemes, ['fluxer-development']);- assert.equal(configs.development.linux.desktop.entry.MimeType, 'x-scheme-handler/fluxer-development;');- for (const channel of ['stable', 'canary']) {- assert.deepEqual(- configs[channel].protocols.flatMap((protocol) => protocol.schemes),- ['fluxer'],- );- }- });-- test('the development app signs without notarization or a provisioning profile it does not have', () => {- const mac = configs.development.mac;- assert.equal(mac.notarize, false);- assert.equal(mac.sign.provisioningProfile, undefined);- const entitlements = fs.readFileSync(path.join(DESKTOP_DIR, mac.sign.entitlements), 'utf8');- assert.doesNotMatch(entitlements, /com\.apple\.developer\.|com\.apple\.application-identifier/u);- assert.ok(fs.existsSync(path.join(DESKTOP_DIR, mac.icon)), `missing ${mac.icon}`);- });-});--describe('running channels stay apart', () => {- test('each channel keeps its own profile directory, so locks, logs, stores and caches never collide', () => {- const source = fs.readFileSync(path.join(DESKTOP_DIR, 'src/common/UserDataPath.ts'), 'utf8');- const map = /channelStorageDirectoryMap: ChannelStorageDirectoryMap = \{([^}]+)\}/u.exec(source)?.[1] ?? '';- const directories = CHANNELS.map((channel) => new RegExp(`${channel}: '([^']+)'`, 'u').exec(map)?.[1]);- assert.deepEqual(directories, ['fluxer', 'fluxercanary', 'fluxerdevelopment']);- });-});diff --git a/fluxer_desktop/src/main/AppLoadRetry.test.mjs b/fluxer_desktop/src/main/AppLoadRetry.test.mjsdeleted file mode 100644index 73d14a3ea..000000000--- a/fluxer_desktop/src/main/AppLoadRetry.test.mjs+++ /dev/null@@ -1,166 +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('./AppLoadRetry.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadAppLoadRetry() {- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--const APP_URL = 'fluxer-app://app/channels/@me';-const silentLogger = {info() {}, warn() {}, error() {}};--function createHarness() {- const listeners = new Map();- const timers = [];- const loads = [];- const prompts = [];- let commits = 0;- let outcome = 'dns-failure';- const webContents = {- on(event, listener) {- listeners.set(event, [...(listeners.get(event) ?? []), listener]);- },- emit(event, ...args) {- for (const listener of listeners.get(event) ?? []) listener({}, ...args);- },- isDestroyed: () => false,- isLoadingMainFrame: () => false,- loadURL(url) {- loads.push(url);- if (outcome === 'ok') {- webContents.emit('did-navigate', url, 200, 'OK');- webContents.emit('did-finish-load');- return Promise.resolve();- }- if (outcome === 'aborted') {- return Promise.reject(new Error(`ERR_ABORTED (-3) loading '${url}'`));- }- webContents.emit('did-fail-load', -105, 'ERR_NAME_NOT_RESOLVED', url, true);- webContents.emit('did-finish-load');- return Promise.reject(new Error(`ERR_NAME_NOT_RESOLVED (-105) loading '${url}'`));- },- };- const {createAppLoadRetry} = loadAppLoadRetry();- const retry = createAppLoadRetry({- webContents,- appUrl: APP_URL,- logger: silentLogger,- isTrustedUrl: () => true,- onRepeatedFailure: (failure) => prompts.push(failure),- onCommitted: () => {- commits += 1;- },- setTimer: (callback, delay) => {- const timer = {callback, delay, cleared: false};- timers.push(timer);- return timer;- },- clearTimer: (timer) => {- timer.cleared = true;- },- });- const settle = () => new Promise((resolve) => setImmediate(resolve));- return {- retry,- loads,- prompts,- get commits() {- return commits;- },- setOutcome(next) {- outcome = next;- },- pendingDelays: () => timers.filter((timer) => !timer.cleared && !timer.fired).map((timer) => timer.delay),- async fireNextTimer() {- const timer = timers.find((candidate) => !candidate.cleared && !candidate.fired);- assert.ok(timer, 'expected a pending retry timer');- timer.fired = true;- timer.callback();- await settle();- return timer.delay;- },- settle,- };-}--describe('AppLoadRetry', () => {- test('backs off on a DNS failure even though the error page fires did-finish-load', async () => {- const harness = createHarness();- harness.retry.start();- await harness.settle();-- const delays = [];- for (let i = 0; i < 8; i += 1) {- assert.equal(harness.pendingDelays().length, 1);- delays.push(await harness.fireNextTimer());- }-- assert.deepEqual(delays, [1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000]);- assert.equal(harness.loads.length, 9);- assert.ok(harness.loads.every((url) => url === APP_URL));- });-- test('resets the backoff and dismisses the prompt once the app commits', async () => {- const harness = createHarness();- harness.retry.start();- await harness.settle();- await harness.fireNextTimer();- await harness.fireNextTimer();- assert.equal(harness.prompts.length, 1);-- harness.setOutcome('ok');- await harness.fireNextTimer();- assert.equal(harness.commits, 1);- assert.deepEqual(harness.pendingDelays(), []);-- harness.setOutcome('dns-failure');- harness.retry.retryNow();- await harness.settle();- assert.deepEqual(harness.pendingDelays(), [1000]);- });-- test('asks the user only after three consecutive failures', async () => {- const harness = createHarness();- harness.retry.start();- await harness.settle();- await harness.fireNextTimer();- assert.equal(harness.prompts.length, 0);-- await harness.fireNextTimer();- assert.equal(harness.prompts.length, 1);- assert.equal(harness.prompts[0].errorCode, -105);- assert.equal(harness.prompts[0].url, APP_URL);- });-- test('does not schedule a retry for an aborted load', async () => {- const harness = createHarness();- harness.setOutcome('aborted');- harness.retry.start();- await harness.settle();-- assert.deepEqual(harness.pendingDelays(), []);- });-});diff --git a/fluxer_desktop/src/main/BootstrapEntry.test.mjs b/fluxer_desktop/src/main/BootstrapEntry.test.mjsdeleted file mode 100644index 93d121401..000000000--- a/fluxer_desktop/src/main/BootstrapEntry.test.mjs+++ /dev/null@@ -1,277 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync} from 'node:fs';-import path from 'node:path';-import {describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';--const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'Bootstrap.ts'), 'utf8');--describe('Bootstrap entry point', () => {- test('never top level awaits the module bootstrap', () => {- assert.doesNotMatch(- source,- /^\t*await runModuleBootstrap\(\)/m,- 'Electron emits ready only after the entry module finishes evaluating. Top level awaiting runModuleBootstrap, which itself awaits app.whenReady(), deadlocks: ready cannot fire until evaluation completes and evaluation cannot complete until ready fires. The splash never opens and no module is ever fetched. Keep it detached.',- );- });-- test('detaches the module bootstrap and still handles its rejection', () => {- assert.match(source, /void runModuleBootstrap\(\)\.catch\(/);- });-- test('never awaits app.whenReady at the top level either', () => {- assert.doesNotMatch(- source,- /^await app\.whenReady\(\)/m,- 'Awaiting ready at module scope deadlocks for the same reason. Inside an async function that is not top level awaited it is correct.',- );- });-- test('the flag off branch imports the main app directly only when the asar still carries a renderer', () => {- assert.match(- source,- /case ModuleSystemLaunchDecision\.DISABLED_BY_REQUEST:\n\t\tif \(HAS_OFFLINE_RENDERER\) \{\n\t\t\tawait import\(MAIN_PROCESS_ENTRY_URL\);/,- );- });-- test('every MainApp import site is gated on a launch permit or on an offline renderer', () => {- const sites = source.split('\n').filter((line) => line.includes('import(MAIN_PROCESS_ENTRY_URL)'));- assert.equal(- sites.length,- 2,- 'a new MainApp import site must be justified here before it is added. The two are: the launch permit and the flag off branch.',- );- });-- test('an ignored disable override is logged rather than silently swallowed', () => {- assert.match(- source,- /if \(MODULE_SYSTEM_LAUNCH\.kind === ModuleSystemLaunchDecision\.ENABLED_WITH_IGNORED_DISABLE_REQUEST\) \{/,- );- });-- test('the deliberate floor bypass on the rollback path reaches the log', () => {- assert.match(source, /if \(permit\.belowFloor\.length > 0\) \{\n\t+logger\.warn\(/);- assert.match(- source,- /logger\.warn\(\n\t+'Launching a module set the persisted floor forbids[^']*',\n\t+\{modules: permit\.belowFloor\},\n\t+\);/,- 'The launch permit only carries belowFloor on the rollback path, so the module names are the whole point of the warning. Without them the log says a floor was bypassed and never says which modules did it.',- );- });-- test('a required shell update never blocks on a retry the platform cannot satisfy', () => {- assert.doesNotMatch(- source,- /blockUntilRelaunch\('blocked-shell-update'\)/,- 'Relaunching runs the same binary, refetches the same manifest and blocks again. On Linux, portable and Flatpak the shell cannot self update at all, so a retry is an unescapable loop.',- );- assert.match(source, /const shellUpdatePlan = resolveShellUpdatePlan\(\);/);- assert.match(source, /armBlockedShellUpdate\(\);/);- });- test('a shell that can update itself tries to before the modules, and the block only arms the download page', () => {- assert.match(- source,- /shellUpdatePlan\.capability === ShellUpdateCapability\.SELF_UPDATE\n\t+\? async \(latestVersion\) => \{/,- );- assert.match(source, /return await runShellSelfUpdate\(shellUpdatePlan, \{/);- assert.match(- source,- /capability: shellUpdatePlan\.capability,\n\t{5}\}\);\n\t{5}openSplashWindow\(\);\n\t{5}armBlockedShellUpdate\(\);/,- 'The updater already attempted the self update before it returned the block, so the block must not try again.',- );- assert.doesNotMatch(source, /The shell self update failed, falling back to a manual download/);- });- test('the self update is imported inside the update loop, never at the top level', () => {- assert.doesNotMatch(- source,- /^(const \{runShellSelfUpdate\}|await import\('@electron\/main\/ShellSelfUpdate'\))/m,- 'Importing the self update at module scope would pull electron and velopack into the entry evaluation, which is exactly what deadlocks ready.',- );- assert.match(source, /\t+const \{runShellSelfUpdate\} = await import\('@electron\/main\/ShellSelfUpdate'\);/);- });-- test('the self update paints its own progress rather than leaving the checking screen up', () => {- assert.match(source, /setSplashState\(\{status: 'shell-update-downloading', progress\}\);/);- assert.match(source, /setSplashState\(\{status: 'shell-update-restarting'\}\);/);- assert.match(source, /const result = await runShellSelfUpdateOnSplash\(\);/);- });- test('the retry affordance still belongs to the module update block', () => {- assert.match(source, /setSplashState\(\{status, action: SplashAction\.RETRY, message\}\);/);- assert.match(source, /return await blockUntilRelaunch\('blocked-update-required'\);/);- });-- test('the retry listener is registered once, beside the quit listener, never inside the block helper', () => {- assert.equal(source.split('\n').filter((line) => line.includes('onSplashRetry(')).length, 1);- assert.match(- source,- /onSplashQuit\(\(\) => \{\n\t\t\tlogger\.info\('The splash requested a quit'\);\n\t\t\tapp\.quit\(\);\n\t\t\}\);\n\t\tonSplashRetry\(/,- 'Two reachable blockUntilRelaunch calls would otherwise register two listeners and one click would relaunch twice.',- );- assert.doesNotMatch(- source,- /const blockUntilRelaunch = [^\n]*\n[^\n]*armSplashActions\(\)/,- 'The splash forgets its listeners when it closes, so the update splash arms them again, but the block helper never does.',- );- });- test('refusing to start never top level awaits either', () => {- assert.doesNotMatch(source, /^await refuseUnsupportedBuild\(/m);- assert.match(source, /void refuseUnsupportedBuild\(/);- });-- test('the single instance lock is taken before the bootstrap touches anything a second process could corrupt', () => {- const bootstrap = source.slice(source.indexOf('async function runModuleBootstrap()'));- const lock = bootstrap.indexOf('app.requestSingleInstanceLock()');- assert.notEqual(- lock,- -1,- 'index.ts only requests the lock once the whole bootstrap has finished, and the blocked update paths never reach index.ts at all. Until the lock moves up here two processes race ModuleStore.open, each burn a boot attempt against the shared state and two of those roll the next cold start back to the older module set.',- );- assert.ok(- lock > bootstrap.indexOf('configureUserDataPath()'),- 'The lock is keyed on the user data directory, so requesting it before that directory is configured would lock the wrong profile.',- );- assert.ok(lock < bootstrap.indexOf('await app.whenReady()'));- assert.ok(lock < bootstrap.indexOf('openSplashWindow()'));- assert.ok(lock < bootstrap.indexOf('ModuleStore.open('));- });-- test('a second instance quits instead of stranding its launch on a splash that never resolves', () => {- assert.match(- source,- /if \(!app\.requestSingleInstanceLock\(\)\) \{\n\t+logger\.info\([^\n]*\);\n\t+app\.quit\(\);\n\t+return;\n\t\}/,- 'blockUntilRelaunch and the blocked-shell-update branch both return a promise that never settles, so a second launch that meets a required update manifest would sit on a splash forever with its argv and its deep link never forwarded.',- );- });-- test('the lock that keeps the second process out also arms the forwarding of its launch', () => {- const bootstrap = source.slice(source.indexOf('async function runModuleBootstrap()'));- const lock = bootstrap.indexOf('app.requestSingleInstanceLock()');- const arm = bootstrap.indexOf('armSecondInstanceForwarding()');- assert.notEqual(- arm,- -1,- 'Electron discards a forwarded second-instance launch when nothing is listening, and index.ts only attaches the real handler once the update loop has resolved. Without a listener armed here every deep link, jump list task and plain focus that arrives during the splash is dropped, permanently so on the blocked paths that never reach index.ts at all.',- );- assert.ok(- arm > lock,- 'Arming before the lock is granted would attach a listener in the process that is about to quit.',- );- assert.ok(arm < bootstrap.indexOf('await app.whenReady()'));- assert.ok(arm < bootstrap.indexOf('openSplashWindow()'));- });-- test('a splash that will never launch still raises itself when a second launch is forwarded', () => {- assert.match(- source,- /setSplashState\(\{status, action: SplashAction\.RETRY, message\}\);\n\t+setSecondInstanceSink\(focusSplashWindow\);/,- 'blockUntilRelaunch never settles, so index.ts never installs handleSecondInstance and the buffered launches would sit there forever. Pointing the sink at the splash is the only response left.',- );- assert.match(source, /armBlockedShellUpdate\(\);\n\t+setSecondInstanceSink\(focusSplashWindow\);/);- });- test('an unreachable update server is retried in process instead of waiting for a click', () => {- const bootstrap = source.slice(source.indexOf('async function runModuleBootstrap()'));- assert.match(- bootstrap,- /if \(outcome\.updateServerUnreachable\) \{\n\t+showBlockedSplash\('blocked-update-unreachable', UPDATE_SERVER_UNREACHABLE_MESSAGE\);\n\t+await updateServerRetry\.holdUntilNextAttempt\(\);\n[^\n]*\n\t+return null;/,- 'blockUntilRelaunch never settles, so a splash that reached it while the network was down stayed there after the network came back until the user pressed Retry now.',- );- assert.match(bootstrap, /onSplashNetworkOnline\(\(\) => \{\n[^\n]*\n\t+updateServerRetry\.networkReturned\(\);/);- assert.match(- bootstrap,- /sleep: updateServerRetry\.sleep,/,- 'The updater sleeps between its own attempts, and a network that returns during that sleep has to cut it short.',- );- assert.match(- bootstrap,- /if \(updateServerRetry\.holding\) \{\n\t+if \(!updateServerRetry\.endsHold\(state\.status\)\) \{\n\t+return;\n\t+\}\n\t+releaseSplashAffordance\(\);/,- 'The splash latches the unreachable screen, so the retry has to release it once the server answers or the download would run behind a screen that says the server cannot be reached.',- );- });-- test('the update poll only checks, it never downloads or reloads underneath the user', () => {- const poll = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'DesktopUpdatePoll.ts'), 'utf8');- assert.match(source, /check: \(\) => checkDesktopUpdateNow\(\),/);- assert.doesNotMatch(- poll,- /installPending|reloadIgnoringCache|refreshModuleRoots|activateMergedForRendererReload/,- 'A background poll that downloads the renderer and commits it makes the update look like it already happened, then the click reloads in place while the shell update still waits. The poll only publishes whether an update exists.',- );- assert.doesNotMatch(source, /reloadIgnoringCache/);- });-- test('a reload of the renderer checks for an update right away', () => {- assert.match(source, /observeRendererLaunchConfirmed\(wakeDesktopUpdatePoll\);/);- });-- test('a minimized login launch converges the modules without flashing the splash', () => {- const bootstrap = source.slice(source.indexOf('async function runModuleBootstrap()'));- assert.match(- bootstrap,- /await app\.whenReady\(\);\n\n\tif \(isStartMinimizedLaunch\(\)\) \{\n\t\tlogger\.info\([^\n]*\);\n\t\} else \{\n\t\topenSplashWindow\(\);\n\t\}\n\tsetSplashState\(\{status: 'checking-for-updates'\}\);/,- 'index.ts starts the main window hidden on an autostart launch with start minimized, so a splash opened here unconditionally flashes on every login anyway.',- );- assert.ok(bootstrap.indexOf('loadDesktopConfig(userDataConfig.base)') < bootstrap.indexOf('await app.whenReady()'));- assert.match(source, /const \{isStartMinimizedLaunch\} = await import\('@electron\/main\/AutostartLaunch'\);/);- assert.doesNotMatch(- source,- /import\('@electron\/main\/Autostart'\)/,- 'Autostart.ts pulls the main process i18n and the Linux portals in. The bootstrap only needs the launch check, which is in the light AutostartLaunch module.',- );- });-- test('a quiet launch still surfaces the splash for every state that needs the user', () => {- assert.match(- source,- /const showBlockedSplash = \(status: SplashStatus, message: string \| null = null\): void => \{\n\t\topenSplashWindow\(\);\n\t\tsetSplashState\(\{status, action: SplashAction\.RETRY, message\}\);/,- 'A blocked or failed boot never reaches the main window, so a minimized login launch would otherwise sit invisible forever with nothing in the tray to bring it back.',- );- assert.match(source, /openSplashWindow\(\);\n\t+armBlockedShellUpdate\(\);/);- });-- test('the update splash hides the app only once it is on screen, in its own theme', () => {- const bootstrap = source.slice(source.indexOf('async function runModuleBootstrap()'));- assert.match(bootstrap, /openSplashWindow\(\{darkThemeOnShow: true\}\)/);- assert.match(- bootstrap,- /focusSplashWindow\(\);\n\t+takeoverHidden = windows\.hideAppWindowsForUpdate\(splash\);/,- 'A deadline that wins before the splash preload reports ready would otherwise hide the app with nothing on screen.',- );- assert.match(- bootstrap,- /splashOpenedAt = Date\.now\(\);/,- 'Copy diagnostics counts from the update, not from boot.',- );- });-- test('the main window that closes for an update never takes the update splash with it', () => {- assert.match(- source,- /window\.once\('closed', closeSplashWithWindow\);\n\t+onMainWindowReady\(\(\) => \{\n\t+window\.removeListener\('closed', closeSplashWithWindow\);/,- );- });- test('the pre-ready Chromium configuration runs before the bootstrap waits for ready', () => {- const configure = source.indexOf('applyPreReadyChromiumConfiguration(userDataConfig.channel, process.argv);');- const gpuWorkaround = source.indexOf('await appendWindowsGpuDriverWorkaroundSwitches();');- const ready = source.indexOf('await app.whenReady();\n\n\tif (isStartMinimizedLaunch())');- assert.ok(configure > 0 && ready > 0 && gpuWorkaround > 0);- assert.ok(- configure < ready && gpuWorkaround < ready,- 'disableHardwareAcceleration throws after ready, and switches or feature flags appended after ready never reach the GPU process or the FeatureList',- );- assert.ok(source.indexOf('loadDesktopConfig(userDataConfig.base);') < configure);- });-- test('open-url is claimed at module evaluation, before any await can let ready pass', () => {- assert.match(source, /^armOpenUrlForwarding\(\);$/m);- assert.ok(source.indexOf('armOpenUrlForwarding();') < source.indexOf('switch (MODULE_SYSTEM_LAUNCH.kind)'));- });-- test('the Windows taskbar identity is set before the splash or any other window exists', () => {- assert.match(- source,- /repairWindowsShortcuts\(\);\n\telectronApp\.setToastActivatorCLSID\(WINDOWS_TOAST_ACTIVATOR_CLSID\);\n\telectronApp\.setAppUserModelId\(WINDOWS_APP_USER_MODEL_ID\);\n\}/,- );- });-});diff --git a/fluxer_desktop/src/main/BrowserHandoff.test.mjs b/fluxer_desktop/src/main/BrowserHandoff.test.mjsdeleted file mode 100644index eee997982..000000000--- a/fluxer_desktop/src/main/BrowserHandoff.test.mjs+++ /dev/null@@ -1,505 +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 {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {DesktopBrowserHandoff} = await import('./BrowserHandoff.ts');-const {RendererDocumentOwnerFactory} = await import('./RendererDocumentOwner.ts');-const {createBrowserHandoffPreloadAPI} = await import('../preload/BrowserHandoffPreload.ts');-const {DESKTOP_HANDOFF_CHANNELS} = await import('../../../packages/desktop_ipc/src/BrowserHandoffContract.ts');--const APP_ORIGIN = 'https://web.fluxer.app';-const INSTANCE = Object.freeze({- apiEndpoint: 'https://self.hosted.example/api',- apiVersion: 1,- webAppEndpoint: 'https://self.hosted.example',-});-const CODE = 'ABCDEF-123456';-const COMPLETED_USER = {- id: '42',- username: 'ada',- discriminator: '0001',- global_name: 'Ada',- avatar: 'hash',- email: '[email protected]',-};--function futureTimestamp(offsetMs = 300_000) {- return new Date(Date.now() + offsetMs).toISOString();-}--function createDocument({url = `${APP_ORIGIN}/channels/@me`, privileged = true} = {}) {- const listeners = new Map();- const frame = {url, detached: false, parent: null, send: () => {}};- const sender = {- privileged,- destroyed: false,- isDestroyed: () => sender.destroyed,- isLoadingMainFrame: () => false,- mainFrame: frame,- on: (event, listener) => {- const list = listeners.get(event) ?? [];- list.push(listener);- listeners.set(event, list);- },- once: (event, listener) => sender.on(event, listener),- removeListener: (event, listener) => {- const list = listeners.get(event) ?? [];- const index = list.indexOf(listener);- if (index >= 0) list.splice(index, 1);- listeners.set(event, list);- },- emit: (event, ...args) => {- for (const listener of [...(listeners.get(event) ?? [])]) listener(...args);- },- listenerCount: (event) => (listeners.get(event) ?? []).length,- };- frame.top = frame;- frame.owner = sender;- return {frame, sender, event: {sender, senderFrame: frame}};-}--function jsonResponse(status, payload) {- const body = payload == null ? null : Buffer.from(JSON.stringify(payload), 'utf8');- return {body, headers: {}, ok: status >= 200 && status < 300, status, statusText: 'stub'};-}--function createInstanceClient(routes) {- const requests = [];- return {- requests,- client: {- fetch: async (request) => {- const path = new URL(request.url).pathname;- let body = null;- if (request.body != null) {- body = JSON.parse(Buffer.from(request.body).toString('utf8'));- }- requests.push({- expectedOrigin: request.expectedOrigin,- headers: request.headers,- method: request.method,- path,- body,- url: request.url,- });- const route = routes[`${request.method} ${path}`];- if (route == null) {- return jsonResponse(404, {message: 'unknown route'});- }- return route(requests.length);- },- },- };-}--function createHandoff(routes, {privileged = true, returnUri = null} = {}) {- const document = createDocument({privileged});- const instance = createInstanceClient(routes);- const warnings = [];- const handoff = new DesktopBrowserHandoff({- logger: {warn: (message, ...args) => warnings.push({message, args})},- rendererDocumentOwners: new RendererDocumentOwnerFactory({- policy: {isPrivilegedRendererDocument: ({sender}) => sender.privileged === true},- onWatcherFailure: (error, reason) => warnings.push({message: reason, args: [error]}),- }),- selectedInstanceClient: instance.client,- returnUri: () => returnUri,- });- return {document, handoff, requests: instance.requests, routes: handoff.ipcRoutes(), warnings};-}--const INITIATE_PATH = '/api/v1/auth/handoff/initiate';-const STATUS_PATH = `/api/v1/auth/handoff/${encodeURIComponent(CODE)}/status`;--function initiateRoute({pollSecret = 'poll-secret-value', returnMethod} = {}) {- return () =>- jsonResponse(200, {- code: CODE,- expires_at: futureTimestamp(),- poll_secret: pollSecret,- ...(returnMethod == null ? {} : {return_method: returnMethod}),- });-}--const RETURN_URI = 'fluxer://handoff';-const GRANT = 'grant-value_42';--function completedStatus() {- return jsonResponse(200, {status: 'completed', token: 'token-42', user_id: '42', user: COMPLETED_USER});-}--describe('the main-process browser handoff transport', () => {- test('falls back to GET status against a server that only implements the deployed route', async () => {- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(404, {message: 'unknown route'}),- [`GET ${STATUS_PATH}`]: () => completedStatus(),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- const result = await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.equal(session.code, CODE);- assert.deepEqual(session.instance, INSTANCE);- assert.deepEqual(- requests.map((request) => `${request.method} ${request.path}`),- [`POST ${INITIATE_PATH}`, `POST ${STATUS_PATH}`, `GET ${STATUS_PATH}`],- );- assert.deepEqual(result, {- status: 'completed',- token: 'token-42',- userId: '42',- user: {- username: 'ada',- discriminator: '0001',- global_name: 'Ada',- avatar: 'hash',- email: '[email protected]',- },- });- });-- test('stops retrying POST status once the instance answered 405 for this session', async () => {- let pending = true;- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(405, {message: 'method not allowed'}),- [`GET ${STATUS_PATH}`]: () => {- if (pending) {- pending = false;- return jsonResponse(200, {status: 'pending'});- }- return completedStatus();- },- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);- await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.deepEqual(- requests.map((request) => `${request.method} ${request.path}`),- [`POST ${INITIATE_PATH}`, `POST ${STATUS_PATH}`, `GET ${STATUS_PATH}`, `GET ${STATUS_PATH}`],- );- });-- test('presents the poll secret to an upgraded instance and never leaks it to the renderer', async () => {- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => completedStatus(),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- const result = await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.equal(result.status, 'completed');- assert.deepEqual(- requests.map((request) => `${request.method} ${request.path}`),- [`POST ${INITIATE_PATH}`, `POST ${STATUS_PATH}`],- );- assert.deepEqual(requests[1].body, {poll_secret: 'poll-secret-value'});- assert.equal(JSON.stringify(session).includes('poll-secret-value'), false);- assert.equal(requests[0].expectedOrigin, 'https://self.hosted.example');- });-- test('polls with GET only when the instance returned no poll secret', async () => {- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute({pollSecret: null}),- [`GET ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- const result = await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.deepEqual(result, {status: 'pending'});- assert.deepEqual(- requests.map((request) => `${request.method} ${request.path}`),- [`POST ${INITIATE_PATH}`, `GET ${STATUS_PATH}`],- );- });-- test('refuses a status request for a code this renderer document never initiated', async () => {- const {document, routes} = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute()});-- await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, 'ZZZZZZ-999999'),- /not active for this renderer document/,- );- });-- test('drops the session when the renderer document navigates away', async () => {- const {document, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- document.sender.emit('did-start-navigation', {isMainFrame: true, isSameDocument: false});-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code),- /not active for this renderer document/,- );- assert.equal(document.sender.listenerCount('did-start-navigation'), 0);- });-- test('releases the session once the instance reports a terminal status', async () => {- const {document, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'expired'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- assert.deepEqual(await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code), {status: 'expired'});-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code),- /not active for this renderer document/,- );- });-- test('keeps the newest session when a stale poll from a replaced session finishes late', async () => {- let release = () => {};- const gate = new Promise((resolve) => {- release = resolve;- });- const {document, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: async (call) => {- if (call === 2) {- await gate;- return jsonResponse(200, {status: 'expired'});- }- return jsonResponse(200, {status: 'pending'});- },- });-- const first = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- const stalePoll = routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, first.code);- const second = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- release();- assert.deepEqual(await stalePoll, {status: 'expired'});-- assert.deepEqual(await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, second.code), {status: 'pending'});- });-- test('refuses an instance descriptor that is not an absolute HTTP endpoint', async () => {- const {document, routes} = createHandoff({});-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, {...INSTANCE, apiEndpoint: '/api'}),- /instance.apiEndpoint is invalid/,- );- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, {...INSTANCE, apiVersion: 0}),- /instance.apiVersion is invalid/,- );- });-- test('refuses to serve a renderer document that is not the privileged main frame', async () => {- const {document, routes} = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute()}, {privileged: false});-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE),- /requires the current privileged main-frame renderer document/,- );- });-- test('cleanup drops every session and its renderer watcher', async () => {- const {document, handoff, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- handoff.cleanup();-- assert.equal(document.sender.listenerCount('did-start-navigation'), 0);- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code),- /not active for this renderer document/,- );- });-});--describe('the main-process handoff return through the deep link', () => {- test('asks for a deep link return only when the app can receive one', async () => {- const registered = createHandoff(- {[`POST ${INITIATE_PATH}`]: initiateRoute({returnMethod: 'deep_link'})},- {returnUri: RETURN_URI},- );- const unregistered = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute({returnMethod: 'code'})});-- const linked = await registered.routes[DESKTOP_HANDOFF_CHANNELS.initiate](registered.document.event, INSTANCE);- const typed = await unregistered.routes[DESKTOP_HANDOFF_CHANNELS.initiate](unregistered.document.event, INSTANCE);-- assert.deepEqual(registered.requests[0].body, {return_uri: RETURN_URI});- assert.equal(linked.returnMethod, 'deep_link');- assert.equal(unregistered.requests[0].body, null);- assert.equal(typed.returnMethod, 'code');- });-- test('falls back to the code when the instance does not confirm the deep link return', async () => {- const {document, routes} = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute()}, {returnUri: RETURN_URI});-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);-- assert.equal(session.returnMethod, 'code');- });-- test('presents the grant from the return link with the poll secret and never hands it to the renderer', async () => {- const {document, handoff, routes, requests} = createHandoff(- {- [`POST ${INITIATE_PATH}`]: initiateRoute({returnMethod: 'deep_link'}),- [`POST ${STATUS_PATH}`]: (call) => (call === 2 ? jsonResponse(200, {status: 'pending'}) : completedStatus()),- },- {returnUri: RETURN_URI},- );-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- assert.deepEqual(await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code), {status: 'pending'});- handoff.acceptReturnLink(new URL(`${RETURN_URI}?code=${CODE.toLowerCase()}&grant=${GRANT}`));- const result = await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.equal(result.status, 'completed');- assert.deepEqual(requests[1].body, {poll_secret: 'poll-secret-value'});- assert.deepEqual(requests[2].body, {poll_secret: 'poll-secret-value', grant: GRANT});- assert.equal(JSON.stringify(result).includes(GRANT), false);- });-- test('ignores a return link for a request this app is not waiting on', async () => {- const {document, handoff, routes, requests, warnings} = createHandoff(- {- [`POST ${INITIATE_PATH}`]: initiateRoute({returnMethod: 'deep_link'}),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- },- {returnUri: RETURN_URI},- );-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- handoff.acceptReturnLink(new URL(`${RETURN_URI}?code=ZZZZZZ-999999&grant=${GRANT}`));- handoff.acceptReturnLink(new URL(`${RETURN_URI}?code=${CODE}&grant=not%20valid`));- await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.deepEqual(requests[1].body, {poll_secret: 'poll-secret-value'});- assert.equal(warnings.length, 2);- });-- test('reports a request the browser declined and releases the session', async () => {- const {document, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'denied'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, INSTANCE);- assert.deepEqual(await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code), {status: 'denied'});-- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code),- /not active for this renderer document/,- );- });-});--describe('the browser handoff preload bridge', () => {- test('reaches the two registered main-process channels and nothing else', async () => {- const {document, routes} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => completedStatus(),- });- const invoked = [];- const api = createBrowserHandoffPreloadAPI({- invoke: (channel, ...args) => {- invoked.push(channel);- const handler = routes[channel];- if (handler == null) {- throw new Error(`No main-process handler is registered for ${channel}`);- }- return handler(document.event, ...args);- },- });-- assert.deepEqual(Object.keys(api), ['desktopHandoff']);- assert.ok(Object.isFrozen(api.desktopHandoff));- const session = await api.desktopHandoff.initiate(INSTANCE);- const result = await api.desktopHandoff.status(session.code);-- assert.equal(result.status, 'completed');- assert.deepEqual(invoked, [DESKTOP_HANDOFF_CHANNELS.initiate, DESKTOP_HANDOFF_CHANNELS.status]);- });-});--describe('the main-process handoff sends the browser Origin the instance demands', () => {- const ORIGIN_INSTANCE = Object.freeze({- apiEndpoint: 'https://web.canary.fluxer.app/api',- apiVersion: 1,- webAppEndpoint: 'https://web.canary.fluxer.app',- });-- test('a POST carries the origin of the web app endpoint, and a GET carries none', async () => {- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute({pollSecret: null}),- [`GET ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, ORIGIN_INSTANCE);- await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.deepEqual(- requests.map((request) => [request.method, request.headers.Origin ?? null]),- [- ['POST', 'https://web.canary.fluxer.app'],- ['GET', null],- ],- );- assert.equal(Object.hasOwn(requests[1].headers, 'Origin'), false);- });-- test('the polled POST status carries the same origin as the initiation', async () => {- const {document, routes, requests} = createHandoff({- [`POST ${INITIATE_PATH}`]: initiateRoute(),- [`POST ${STATUS_PATH}`]: () => jsonResponse(200, {status: 'pending'}),- });-- const session = await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, ORIGIN_INSTANCE);- await routes[DESKTOP_HANDOFF_CHANNELS.status](document.event, session.code);-- assert.deepEqual(- requests.map((request) => request.headers.Origin),- ['https://web.canary.fluxer.app', 'https://web.canary.fluxer.app'],- );- });-- test('the origin is the web app endpoint, not the API endpoint it posts to', async () => {- const {document, routes, requests} = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute()});-- await routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, {- ...ORIGIN_INSTANCE,- apiEndpoint: 'https://api.canary.fluxer.app/api',- webAppEndpoint: 'https://web.canary.fluxer.app/app',- });-- assert.equal(requests[0].expectedOrigin, 'https://api.canary.fluxer.app');- assert.equal(requests[0].headers.Origin, 'https://web.canary.fluxer.app');- });-- test('a web app endpoint that has no usable origin is refused before any request is sent', async () => {- const {document, routes, requests} = createHandoff({[`POST ${INITIATE_PATH}`]: initiateRoute()});-- for (const webAppEndpoint of ['/app', 'not a url', 'javascript:alert(1)', 'https://user:[email protected]']) {- await assert.rejects(- () => routes[DESKTOP_HANDOFF_CHANNELS.initiate](document.event, {...ORIGIN_INSTANCE, webAppEndpoint}),- /instance.webAppEndpoint is invalid/,- webAppEndpoint,- );- }- assert.deepEqual(requests, []);- });-});diff --git a/fluxer_desktop/src/main/DesktopAppStorage.test.mjs b/fluxer_desktop/src/main/DesktopAppStorage.test.mjsdeleted file mode 100644index 3f06c7c2d..000000000--- a/fluxer_desktop/src/main/DesktopAppStorage.test.mjs+++ /dev/null@@ -1,476 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readdirSync, readFileSync, writeFileSync} from 'node:fs';-import nodePath from 'node:path';-import {describe, test} from 'node:test';-import {createAppStoreBoundary} from './AppStoreNativeBoundary.ts';-import {- createFakeAppStoreBinding,- createTemporaryUserData,- readDesktopAppStorageSource,-} from './DesktopAppStorageHarness.mjs';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {- DESKTOP_APP_STORE_DERIVATION_VERSION,- DESKTOP_APP_STORE_FILE_NAME,- DesktopAppStorage,- DesktopAppStoreCapacityError,- DesktopAppStoreRequestError,- DesktopAppStoreShutdownError,- DesktopAppStoreUnavailableError,- DesktopAppStoreWriteRefusedError,-} = await import('./DesktopAppStorage.ts');--const ACCOUNT_KEY = 'https://self.hosted.example/api::42';--function accountRecord(overrides = {}) {- return {- userId: '42',- token: 'token-42',- lastActive: 1_755_000_000_000,- instance: {apiEndpoint: 'https://self.hosted.example/api'},- ...overrides,- };-}--function createStorage({userDataPath = createTemporaryUserData(), binding = createFakeAppStoreBinding()} = {}) {- const storage = new DesktopAppStorage({- userDataPath,- createBoundary: (options) => createAppStoreBoundary(options, binding.FakeAppStore),- });- return {storage, userDataPath, observed: binding.observed};-}--describe('DesktopAppStorage', () => {- test('derives the single store file from the user data directory it was constructed with', () => {- const {storage, userDataPath, observed} = createStorage();- const opened = storage.open();-- assert.equal(opened.status.available, true);- assert.equal(opened.storeFile, nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME));- assert.equal(observed.constructed.length, 1);- assert.deepEqual(observed.constructed[0], {- path: nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME),- derivationVersion: DESKTOP_APP_STORE_DERIVATION_VERSION,- });- storage.close();- });-- test('never reaches a dialog when it recovers a store', () => {- assert.equal(/dialog|showErrorBox|showMessageBox/.test(readDesktopAppStorageSource()), false);- });-- test('round-trips an account, a scoped entry and a known instance', async () => {- const {storage} = createStorage();- storage.open();-- await storage.upsertAccount({storageKey: ACCOUNT_KEY, record: accountRecord()});- assert.deepEqual(await storage.getAccount(ACCOUNT_KEY), {storageKey: ACCOUNT_KEY, record: accountRecord()});- assert.deepEqual(await storage.getAllAccounts(), [{storageKey: ACCOUNT_KEY, record: accountRecord()}]);-- await storage.setEntry(ACCOUNT_KEY, 'Theme', '{"theme":"dark"}');- assert.equal((await storage.getEntry(ACCOUNT_KEY, 'Theme')).value, '{"theme":"dark"}');- assert.deepEqual(- (await storage.loadEntries(ACCOUNT_KEY)).map((entry) => entry.key),- ['Theme'],- );-- await storage.upsertKnownInstance({- instanceKey: 'https://self.hosted.example/api',- domain: 'self.hosted.example',- displayName: 'Self Hosted',- lastUsed: 1_755_000_000_001,- });- assert.deepEqual(await storage.getAllKnownInstances(), [- {- instanceKey: 'https://self.hosted.example/api',- domain: 'self.hosted.example',- displayName: 'Self Hosted',- lastUsed: 1_755_000_000_001,- },- ]);-- await storage.deleteAccount(ACCOUNT_KEY);- assert.equal(await storage.getAccount(ACCOUNT_KEY), null);- storage.close();- });-- test('an account record written by a newer renderer round-trips with its unknown fields intact', async () => {- const {storage} = createStorage();- storage.open();- const record = accountRecord({futureField: {nested: [1, 2, 3]}, presenceIntent: null});-- await storage.upsertAccount({storageKey: ACCOUNT_KEY, record});- assert.deepEqual((await storage.getAccount(ACCOUNT_KEY)).record, record);- storage.close();- });-- test('refuses malformed requests before they reach the store', async () => {- const {storage} = createStorage();- storage.open();-- await assert.rejects(() => storage.getAccount(42), DesktopAppStoreRequestError);- await assert.rejects(() => storage.getAccount(''), /must be a non-empty NUL-free string/);- await assert.rejects(() => storage.getEntry('bad\0scope', 'k'), /NUL-free/);- await assert.rejects(() => storage.setEntry('scope', 'key', 'x'.repeat(9 * 1024 * 1024)), /at most/);- await assert.rejects(() => storage.upsertAccount({storageKey: ACCOUNT_KEY, record: []}), /must be an object/);- await assert.rejects(- () => storage.pruneAccounts({knownStorageKeys: [], listIsAuthoritative: 'yes'}),- /must be a boolean/,- );- await assert.rejects(- () =>- storage.compareAndSwapAccount({- expected: {storageKey: ACCOUNT_KEY, record: accountRecord()},- replacement: {storageKey: `${ACCOUNT_KEY}9`, record: accountRecord({userId: '429'})},- }),- /must use the same storageKey/,- );- storage.close();- });-- test('serialises operations in call order even when the store answers out of order', async () => {- let release = () => {};- const gate = new Promise((resolve) => {- release = resolve;- });- const binding = createFakeAppStoreBinding({delays: new Map([['setEntry', gate]])});- const {storage, observed} = createStorage({binding});- storage.open();-- const slow = storage.setEntry('scope', 'key', 'first');- const fast = storage.deleteEntry('scope', 'key');- release();- await Promise.all([slow, fast]);-- assert.deepEqual(- observed.calls.filter((name) => name === 'setEntry' || name === 'deleteEntry'),- ['setEntry', 'deleteEntry'],- );- assert.equal(await storage.getEntry('scope', 'key'), null);- storage.close();- });-- test('stamps every write with a strictly increasing value so newest-wins arbitration is total', async () => {- const {storage} = createStorage();- storage.open();-- await storage.setEntry('scope', 'key', 'one');- const first = await storage.getEntry('scope', 'key');- await storage.setEntry('scope', 'key', 'two');- const second = await storage.getEntry('scope', 'key');-- assert.ok(second.updatedAt > first.updatedAt);- storage.close();- });-- test('an imported stamp from the web backend never lets a later desktop write look older', async () => {- const {storage} = createStorage();- storage.open();- const future = Date.now() + 60_000;-- await storage.importEntries({- entries: [{scope: 'scope', key: 'key', value: 'imported', updatedAt: future}],- marker: {key: 'import.phase', value: 'entries'},- });- await storage.setEntry('scope', 'key', 'written-after');- const entry = await storage.getEntry('scope', 'key');-- assert.equal(entry.value, 'written-after');- assert.ok(entry.updatedAt > future);- assert.equal(await storage.getMarker('import.phase'), 'entries');- storage.close();- });-- test('setMany writes every entry in one batch and honours ifAbsent against what is already stored', async () => {- const {storage} = createStorage();- storage.open();-- await storage.setEntry('scope', 'kept', 'original');- await storage.setManyEntries([- {scope: 'scope', key: 'kept', value: 'replacement', ifAbsent: true},- {scope: 'scope', key: 'fresh', value: 'new'},- ]);-- assert.equal((await storage.getEntry('scope', 'kept')).value, 'original');- assert.equal((await storage.getEntry('scope', 'fresh')).value, 'new');- storage.close();- });-- test('reports a refused batch write instead of pretending every entry landed', async () => {- const binding = createFakeAppStoreBinding({maxValueBytes: 8});- const {storage} = createStorage({binding});- storage.open();-- await assert.rejects(- () => storage.setManyEntries([{scope: 'scope', key: 'key', value: 'far too long to store'}]),- DesktopAppStoreWriteRefusedError,- );- storage.close();- });-- test('clearAllForScope and clearAllExcept leave every other scope and retained key alone', async () => {- const {storage} = createStorage();- storage.open();-- await storage.setManyEntries([- {scope: 'a', key: 'keep', value: '1'},- {scope: 'a', key: 'drop', value: '2'},- {scope: 'b', key: 'keep', value: '3'},- ]);-- await storage.clearAllForScope('b');- assert.deepEqual(await storage.loadEntries('b'), []);- assert.equal((await storage.loadEntries('a')).length, 2);-- await storage.clearAllExcept(['keep']);- assert.deepEqual(- (await storage.loadEntries('a')).map((entry) => entry.key),- ['keep'],- );- storage.close();- });-- test('prune refuses a list that is not authoritative and keeps every account row', async () => {- const {storage} = createStorage();- storage.open();- await storage.upsertAccount({storageKey: ACCOUNT_KEY, record: accountRecord()});-- const refused = await storage.pruneAccounts({knownStorageKeys: [], listIsAuthoritative: false});- assert.equal(refused.refusedReason, 'the known account list was not authoritative');- assert.equal((await storage.getAllAccounts()).length, 1);- storage.close();- });-- test('refuses new work past the concurrent operation budget instead of queueing without bound', async () => {- let release = () => {};- const gate = new Promise((resolve) => {- release = resolve;- });- const binding = createFakeAppStoreBinding({delays: new Map([['getMetadata', gate]])});- const {storage} = createStorage({binding});- storage.open();-- const inFlight = [];- for (let index = 0; index < 64; index += 1) {- inFlight.push(storage.getMarker('import.phase'));- }- await assert.rejects(() => storage.getMarker('import.phase'), DesktopAppStoreCapacityError);- release();- await Promise.all(inFlight);- storage.close();- });-});--describe('DesktopAppStorage recovery', () => {- test('an identity mismatch renames the store, opens a fresh one and lets the renderer re-seed it', async () => {- const userDataPath = createTemporaryUserData();- writeFileSync(- nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME),- JSON.stringify({- metadata: {'derivation.version': 'a-previous-derivation', 'import.phase': 'done'},- accounts: {[ACCOUNT_KEY]: {recordJson: JSON.stringify(accountRecord()), lastActive: 1}},- knownInstances: {},- entries: {},- }),- 'utf8',- );-- const {storage} = createStorage({userDataPath});- const opened = storage.open();-- assert.equal(opened.status.available, true);- assert.equal(opened.status.quarantined, true);- assert.equal(opened.status.quarantineReason, 'derivation');- assert.ok(opened.quarantinedFile != null);-- const quarantined = readdirSync(userDataPath).filter((name) => name.includes('derivation-'));- assert.equal(quarantined.length, 1);- const preserved = JSON.parse(readFileSync(nodePath.join(userDataPath, quarantined[0]), 'utf8'));- assert.ok(preserved.accounts[ACCOUNT_KEY] != null, 'the quarantined store still holds the account row');-- const recovery = await storage.recover();- assert.equal(recovery.reseedRequired, true);- assert.equal(recovery.status.available, true);-- assert.deepEqual(await storage.getAllAccounts(), []);- assert.equal(await storage.getMarker('import.phase'), null);-- const report = await storage.importAccounts({- records: [{storageKey: ACCOUNT_KEY, record: accountRecord()}],- marker: {key: 'import.phase', value: 'accounts'},- });- assert.equal(report.imported, 1);- assert.deepEqual(await storage.getAllAccounts(), [{storageKey: ACCOUNT_KEY, record: accountRecord()}]);- assert.equal(await storage.getMarker('import.phase'), 'accounts');- storage.close();- });-- test('a corrupt store file is renamed rather than unlinked and never blocks startup', async () => {- const userDataPath = createTemporaryUserData();- writeFileSync(nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME), 'this is not a database', 'utf8');-- const {storage} = createStorage({userDataPath});- const opened = storage.open();-- assert.equal(opened.status.available, true);- assert.equal(opened.status.quarantineReason, 'corrupt');- const quarantined = readdirSync(userDataPath).filter((name) => name.includes('corrupt-'));- assert.equal(quarantined.length, 1);- assert.equal(readFileSync(nodePath.join(userDataPath, quarantined[0]), 'utf8'), 'this is not a database');-- await storage.upsertAccount({storageKey: ACCOUNT_KEY, record: accountRecord()});- assert.equal((await storage.getAllAccounts()).length, 1);- storage.close();- });-- test('a store that cannot open at all reports itself unavailable instead of throwing at startup', async () => {- const storage = new DesktopAppStorage({- userDataPath: createTemporaryUserData(),- createBoundary: () => {- throw new Error('SQLITE_CANTOPEN: unable to open database file');- },- });- const opened = storage.open();-- assert.equal(opened.status.available, false);- assert.match(opened.status.unavailableReason, /SQLITE_CANTOPEN/);- await assert.rejects(() => storage.getAllAccounts(), DesktopAppStoreUnavailableError);- assert.deepEqual(await storage.getStoreStatus(), opened.status);- });-- test('a missing addon leaves the store unavailable and the renderer free to serve the web backend', async () => {- const storage = new DesktopAppStorage({- userDataPath: createTemporaryUserData(),- createBoundary: () => null,- });- const opened = storage.open();-- assert.equal(opened.status.available, false);- assert.equal(opened.status.unavailableReason, 'the app store addon did not load');- assert.equal((await storage.getStoreStatus()).available, false);- });-- test('a known load failure is reported instead of the generic addon message', async () => {- const storage = new DesktopAppStorage({- userDataPath: createTemporaryUserData(),- createBoundary: () => null,- describeLoadFailure: () => 'safety probe terminated by signal SIGKILL',- });- const opened = storage.open();-- assert.equal(opened.status.available, false);- assert.equal(opened.status.unavailableReason, 'safety probe terminated by signal SIGKILL');- });-});--describe('DesktopAppStorage shutdown', () => {- test('closing checkpoints everything already committed and closes the native store exactly once', async () => {- const {storage, userDataPath, observed} = createStorage();- storage.open();- await storage.upsertAccount({storageKey: ACCOUNT_KEY, record: accountRecord()});- await storage.setEntry(ACCOUNT_KEY, 'Theme', '{"theme":"dark"}');-- storage.close();-- assert.equal(observed.closed, 1);- const persisted = JSON.parse(readFileSync(nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME), 'utf8'));- assert.ok(persisted.accounts[ACCOUNT_KEY] != null);- assert.equal(Object.keys(persisted.entries).length, 1);- });-- test('a queued import phase that never committed is refused at shutdown so it re-runs on the next launch', async () => {- let release = () => {};- const gate = new Promise((resolve) => {- release = resolve;- });- const binding = createFakeAppStoreBinding({delays: new Map([['getMetadata', gate]])});- const {storage, userDataPath} = createStorage({binding});- storage.open();-- await storage.setMarker('import.phase', 'accounts');- const inFlight = storage.getMarker('import.phase');- const queued = storage.importEntries({- entries: [{scope: 'scope', key: 'key', value: 'value', updatedAt: 1}],- marker: {key: 'import.phase', value: 'entries'},- });-- storage.close();- release();-- await assert.rejects(() => inFlight, /closed|shutting down/);- await assert.rejects(() => queued, DesktopAppStoreShutdownError);-- const persisted = JSON.parse(readFileSync(nodePath.join(userDataPath, DESKTOP_APP_STORE_FILE_NAME), 'utf8'));- assert.equal(persisted.metadata['import.phase'], 'accounts');- assert.equal(Object.keys(persisted.entries).length, 0);- });-- test('operations issued after shutdown are refused rather than reopening the store', async () => {- const {storage} = createStorage();- storage.open();- storage.close();-- await assert.rejects(() => storage.getAllAccounts(), /the desktop app store is closed/);- });-});--describe('DesktopAppStorage authority sentinel', () => {- const AUTHORITY_KEY = 'legacy_import.authority';- const AUTHORITY_VALUE = 'committed.v1';- const sentinelPath = (userDataPath) => nodePath.join(userDataPath, 'desktop-app-authority-v1');-- test('a fresh install expects no authority and writes no sentinel', () => {- const {storage, userDataPath} = createStorage();- assert.equal(storage.open().status.authorityExpected, false);- assert.equal(readdirSync(userDataPath).includes('desktop-app-authority-v1'), false);- storage.close();- });-- test('committing authority records the marker before the sentinel that witnesses it', async () => {- const {storage, userDataPath, observed} = createStorage();- storage.open();-- await storage.setMarker(AUTHORITY_KEY, AUTHORITY_VALUE);-- assert.equal(readFileSync(sentinelPath(userDataPath), 'utf8'), '1\n');- assert.equal((await storage.getStoreStatus()).authorityExpected, true);- assert.ok(observed.calls.includes('setMetadata'), 'the authority marker reached the store');- storage.close();- });-- test('a store that cannot take the marker leaves no sentinel claiming authority', async () => {- const {storage, userDataPath} = createStorage();- await assert.rejects(() => storage.setMarker(AUTHORITY_KEY, AUTHORITY_VALUE));- assert.equal(readdirSync(userDataPath).includes('desktop-app-authority-v1'), false);- assert.equal((await storage.getStoreStatus()).authorityExpected, false);- });-- test('clearing authority removes the sentinel and the expectation together', async () => {- const {storage, userDataPath} = createStorage();- storage.open();- await storage.setMarker(AUTHORITY_KEY, AUTHORITY_VALUE);- assert.equal((await storage.getStoreStatus()).authorityExpected, true);-- await storage.setMarker(AUTHORITY_KEY, '');-- assert.equal(readdirSync(userDataPath).includes('desktop-app-authority-v1'), false);- assert.equal((await storage.getStoreStatus()).authorityExpected, false);- storage.close();- });-- test('a sentinel left by an earlier launch makes the next one expect authority', () => {- const {storage, userDataPath} = createStorage();- storage.open();- writeFileSync(sentinelPath(userDataPath), '1\n');- storage.close();-- const next = createStorage({userDataPath});- assert.equal(next.storage.open().status.authorityExpected, true);- next.storage.close();- });-});diff --git a/fluxer_desktop/src/main/DesktopAppStorageHarness.mjs b/fluxer_desktop/src/main/DesktopAppStorageHarness.mjsdeleted file mode 100644index 97356af85..000000000--- a/fluxer_desktop/src/main/DesktopAppStorageHarness.mjs+++ /dev/null@@ -1,382 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {mkdtempSync, readFileSync, renameSync, writeFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {tmpdir} from 'node:os';-import nodePath from 'node:path';-import {fileURLToPath, pathToFileURL} from 'node:url';--const require = createRequire(import.meta.url);-const esbuild = require('esbuild');--const DESKTOP_ROOT = nodePath.resolve(fileURLToPath(new URL('../..', import.meta.url)));--const ENTRY = [- "export {createAppStoreBoundary} from './src/main/AppStoreNativeBoundary.ts';",- "export {DesktopAppStorage} from './src/main/DesktopAppStorage.ts';",- "export {createDesktopAppStorageIpcRoutes} from './src/main/DesktopAppStorageIpc.ts';",- "export {createDesktopStoragePreloadAPI} from './src/preload/DesktopStoragePreload.ts';",-].join('\n');--let loaded = null;--export async function loadDesktopStorageIpcBundle() {- if (loaded != null) {- return loaded;- }- const bundle = esbuild.buildSync({- absWorkingDir: DESKTOP_ROOT,- stdin: {contents: ENTRY, resolveDir: DESKTOP_ROOT, loader: 'ts', sourcefile: 'DesktopStorageIpcBundle.ts'},- bundle: true,- format: 'esm',- platform: 'node',- target: 'node20',- write: false,- tsconfig: 'tsconfig.json',- });- const directory = mkdtempSync(nodePath.join(tmpdir(), 'fluxer-app-store-bundle-'));- const file = nodePath.join(directory, 'DesktopStorageIpcBundle.mjs');- writeFileSync(file, bundle.outputFiles[0].text, 'utf8');- loaded = await import(pathToFileURL(file).href);- return loaded;-}--export function readDesktopAppStorageSource() {- return readFileSync(nodePath.join(DESKTOP_ROOT, 'src/main/DesktopAppStorage.ts'), 'utf8');-}--const SIDECAR_SUFFIXES = ['', '-journal', '-wal', '-shm'];--function emptyState() {- return {metadata: {}, accounts: {}, knownInstances: {}, entries: {}};-}--function quarantine(storeFile, reason) {- const quarantined = `${storeFile}.${reason}-${Date.now()}`;- for (const suffix of SIDECAR_SUFFIXES) {- try {- renameSync(`${storeFile}${suffix}`, `${quarantined}${suffix}`);- } catch (error) {- if (error.code !== 'ENOENT') {- throw error;- }- }- }- return quarantined;-}--function entryAddress(store, scope, key) {- return JSON.stringify([store, scope, key]);-}--function lookupKeyIsUsable(value) {- return typeof value === 'string' && value.length > 0 && !value.includes('\0') && Buffer.byteLength(value) <= 1024;-}--export function createFakeAppStoreBinding({delays = new Map(), maxValueBytes = 8 * 1024 * 1024} = {}) {- const observed = {constructed: [], closed: 0, calls: []};-- class FakeAppStore {- #file;- #state;- #open = true;- #initialization;-- constructor(options) {- observed.constructed.push(options);- this.#file = options.path;- let quarantinedPath = null;- let quarantineReason = null;- let state = null;- let raw = null;- try {- raw = readFileSync(this.#file, 'utf8');- } catch (error) {- if (error.code !== 'ENOENT') {- throw error;- }- }- if (raw != null) {- try {- state = JSON.parse(raw);- } catch {- quarantineReason = 'corrupt';- }- }- if (state != null && options.derivationVersion != null) {- const recorded = state.metadata['derivation.version'];- if (recorded != null && recorded !== options.derivationVersion) {- quarantineReason = 'derivation';- state = null;- }- }- if (quarantineReason != null) {- quarantinedPath = quarantine(this.#file, quarantineReason);- state = null;- }- this.#state = state ?? emptyState();- if (options.derivationVersion != null) {- this.#state.metadata['derivation.version'] ??= options.derivationVersion;- }- this.#state.metadata['schema.version'] ??= '1';- this.#flush();- this.#initialization = JSON.stringify({- path: this.#file,- schemaVersion: 1,- previousSchemaVersion: state == null ? 0 : 1,- appliedMigrations: state == null ? 1 : 0,- quarantinedPath,- quarantineReason,- });- }-- get initialization() {- return this.#initialization;- }-- close() {- observed.closed += 1;- this.#open = false;- this.#flush();- }-- #flush() {- writeFileSync(this.#file, JSON.stringify(this.#state), 'utf8');- }-- async #run(name, work) {- observed.calls.push(name);- const delay = delays.get(name);- if (delay != null) {- await delay;- }- if (!this.#open) {- throw new Error('app store is closed');- }- const result = work();- this.#flush();- return result;- }-- getMetadata(key) {- return this.#run('getMetadata', () => JSON.stringify(this.#state.metadata[key] ?? null));- }-- setMetadata(key, value) {- return this.#run('setMetadata', () => {- this.#state.metadata[key] = value;- });- }-- getAllAccounts() {- return this.#run('getAllAccounts', () =>- JSON.stringify(- Object.entries(this.#state.accounts)- .sort((left, right) => (right[1].lastActive ?? 0) - (left[1].lastActive ?? 0))- .map(([storageKey, stored]) => ({storageKey, record: JSON.parse(stored.recordJson)})),- ),- );- }-- getAccount(storageKey) {- return this.#run('getAccount', () => {- const stored = this.#state.accounts[storageKey];- return JSON.stringify(stored == null ? null : {storageKey, record: JSON.parse(stored.recordJson)});- });- }-- #writeAccount(entry) {- if (!lookupKeyIsUsable(entry.storageKey)) {- return 'account storage key is unusable';- }- if (entry.record == null || typeof entry.record !== 'object' || Array.isArray(entry.record)) {- return 'account record must be a JSON object';- }- this.#state.accounts[entry.storageKey] = {- recordJson: JSON.stringify(entry.record),- lastActive: typeof entry.record.lastActive === 'number' ? entry.record.lastActive : 0,- };- return null;- }-- upsertAccount(payload) {- return this.#run('upsertAccount', () => {- const refusal = this.#writeAccount(JSON.parse(payload));- if (refusal != null) {- throw new Error(refusal);- }- });- }-- deleteAccount(storageKey) {- return this.#run('deleteAccount', () => {- delete this.#state.accounts[storageKey];- });- }-- importAccounts(payload) {- return this.#run('importAccounts', () => {- const request = JSON.parse(payload);- const report = {imported: 0, skipped: [], unusableInstances: []};- for (const entry of request.records) {- const refusal = this.#writeAccount(entry);- if (refusal == null) {- report.imported += 1;- } else {- report.skipped.push({key: entry.storageKey, reason: refusal});- }- }- if (request.marker != null) {- this.#state.metadata[request.marker.key] = request.marker.value;- }- return JSON.stringify(report);- });- }-- getAllKnownInstances() {- return this.#run('getAllKnownInstances', () =>- JSON.stringify(- Object.entries(this.#state.knownInstances)- .sort((left, right) => right[1].lastUsed - left[1].lastUsed)- .map(([key, stored]) => ({key, record: JSON.parse(stored.recordJson)})),- ),- );- }-- upsertKnownInstance(payload) {- return this.#run('upsertKnownInstance', () => {- const entry = JSON.parse(payload);- if (!lookupKeyIsUsable(entry.key)) {- throw new Error('known instance key is unusable');- }- this.#state.knownInstances[entry.key] = {- recordJson: JSON.stringify(entry.record),- lastUsed: typeof entry.record.lastUsed === 'number' ? entry.record.lastUsed : 0,- };- });- }-- deleteKnownInstance(key) {- return this.#run('deleteKnownInstance', () => {- delete this.#state.knownInstances[key];- });- }-- getEntries(store, scope) {- return this.#run('getEntries', () =>- JSON.stringify(- Object.values(this.#state.entries)- .filter((entry) => entry.store === store && entry.scope === scope)- .sort((left, right) => (left.key < right.key ? -1 : 1)),- ),- );- }-- getEntry(store, scope, key) {- return this.#run('getEntry', () => JSON.stringify(this.#state.entries[entryAddress(store, scope, key)] ?? null));- }-- #writeEntry(entry) {- if (!lookupKeyIsUsable(entry.store) || !lookupKeyIsUsable(entry.scope) || !lookupKeyIsUsable(entry.key)) {- return 'scoped storage key is unusable';- }- if (Buffer.byteLength(entry.value) > maxValueBytes) {- return 'scoped storage value is too large';- }- this.#state.entries[entryAddress(entry.store, entry.scope, entry.key)] = entry;- return null;- }-- setEntry(payload) {- return this.#run('setEntry', () => {- const refusal = this.#writeEntry(JSON.parse(payload));- if (refusal != null) {- throw new Error(refusal);- }- });- }-- deleteEntry(store, scope, key) {- return this.#run('deleteEntry', () => {- delete this.#state.entries[entryAddress(store, scope, key)];- });- }-- clearScope(scope) {- return this.#run('clearScope', () => {- for (const [address, entry] of Object.entries(this.#state.entries)) {- if (entry.scope === scope) {- delete this.#state.entries[address];- }- }- });- }-- clearStoreExcept(payload) {- return this.#run('clearStoreExcept', () => {- const request = JSON.parse(payload);- const keep = new Set(request.keysToKeep);- for (const [address, entry] of Object.entries(this.#state.entries)) {- if (entry.store === request.store && !keep.has(entry.key)) {- delete this.#state.entries[address];- }- }- });- }-- importEntries(payload) {- return this.#run('importEntries', () => {- const request = JSON.parse(payload);- const report = {imported: 0, skipped: []};- for (const entry of request.entries) {- const refusal = this.#writeEntry(entry);- if (refusal == null) {- report.imported += 1;- } else {- report.skipped.push({key: `${entry.store}/${entry.scope}/${entry.key}`, reason: refusal});- }- }- if (request.marker != null) {- this.#state.metadata[request.marker.key] = request.marker.value;- }- return JSON.stringify(report);- });- }-- prune(payload) {- return this.#run('prune', () => {- const request = JSON.parse(payload);- if (!request.listIsAuthoritative) {- return JSON.stringify({pruned: [], refusedReason: 'the known account list was not authoritative'});- }- const known = new Set(request.knownStorageKeys);- const pruned = [];- for (const storageKey of Object.keys(this.#state.accounts)) {- if (!known.has(storageKey)) {- pruned.push(storageKey);- delete this.#state.accounts[storageKey];- }- }- return JSON.stringify({pruned, refusedReason: null});- });- }- }-- return {FakeAppStore, observed};-}--export function createTemporaryUserData() {- return mkdtempSync(nodePath.join(tmpdir(), 'fluxer-user-data-'));-}--export function createInvoker(routes) {- return {- invoke: async (channel, ...args) => {- const handler = routes[channel];- if (handler == null) {- throw new Error(`No main-process handler is registered for ${channel}`);- }- return handler(...structuredClone(args));- },- };-}diff --git a/fluxer_desktop/src/main/DesktopAppStorageIpc.test.mjs b/fluxer_desktop/src/main/DesktopAppStorageIpc.test.mjsdeleted file mode 100644index 7961ceea5..000000000--- a/fluxer_desktop/src/main/DesktopAppStorageIpc.test.mjs+++ /dev/null@@ -1,128 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {- createFakeAppStoreBinding,- createInvoker,- createTemporaryUserData,- loadDesktopStorageIpcBundle,-} from './DesktopAppStorageHarness.mjs';--const {createAppStoreBoundary, createDesktopAppStorageIpcRoutes, createDesktopStoragePreloadAPI, DesktopAppStorage} =- await loadDesktopStorageIpcBundle();--const ACCOUNT_KEY = 'https://self.hosted.example/api::42';--const ACCOUNT_RECORD = {- userId: '42',- token: 'token-42',- lastActive: 1_755_000_000_000,- instance: {apiEndpoint: 'https://self.hosted.example/api'},-};--function createBridge() {- const binding = createFakeAppStoreBinding();- const storage = new DesktopAppStorage({- userDataPath: createTemporaryUserData(),- createBoundary: (options) => createAppStoreBoundary(options, binding.FakeAppStore),- });- storage.open();- const routes = createDesktopAppStorageIpcRoutes(storage);- return {storage, routes, api: createDesktopStoragePreloadAPI(createInvoker(routes))};-}--describe('desktop app store IPC', () => {- test('exposes exactly the three account, storage and known-instance namespaces', () => {- const {storage, api} = createBridge();- assert.deepEqual(Object.keys(api).sort(), ['desktopAccounts', 'desktopKnownInstances', 'desktopStorage']);- assert.ok(Object.isFrozen(api.desktopAccounts));- assert.ok(Object.isFrozen(api.desktopStorage));- assert.ok(Object.isFrozen(api.desktopKnownInstances));- storage.close();- });-- test('no channel names a filesystem path and every preload call reaches a registered handler', async () => {- const {storage, routes} = createBridge();- for (const channel of Object.keys(routes)) {- assert.equal(/path/i.test(channel), false, `${channel} must not name a filesystem path`);- }- const invoked = [];- const probe = createDesktopStoragePreloadAPI({- invoke: (channel, ...args) => {- invoked.push(channel);- return createInvoker(routes).invoke(channel, ...args);- },- });- await probe.desktopStorage.getStatus();- await probe.desktopAccounts.getAll();- await probe.desktopKnownInstances.getAll();- assert.deepEqual(invoked, [- 'desktop-storage:get-status',- 'desktop-accounts:get-all',- 'desktop-known-instances:get-all',- ]);- storage.close();- });-- test('round-trips an account and a scoped entry through the whole preload and channel path', async () => {- const {storage, api} = createBridge();-- await api.desktopAccounts.upsert({storageKey: ACCOUNT_KEY, record: ACCOUNT_RECORD});- assert.deepEqual(await api.desktopAccounts.get(ACCOUNT_KEY), {- storageKey: ACCOUNT_KEY,- record: ACCOUNT_RECORD,- });-- await api.desktopStorage.set(ACCOUNT_KEY, 'Theme', '{"theme":"dark"}');- const entry = await api.desktopStorage.get(ACCOUNT_KEY, 'Theme');- assert.equal(entry.value, '{"theme":"dark"}');- assert.equal(typeof entry.updatedAt, 'number');- assert.deepEqual(- (await api.desktopStorage.load(ACCOUNT_KEY)).map((row) => row.key),- ['Theme'],- );-- await api.desktopKnownInstances.upsert({- instanceKey: 'https://self.hosted.example/api',- domain: 'self.hosted.example',- displayName: 'Self Hosted',- lastUsed: 1_755_000_000_001,- });- assert.equal((await api.desktopKnownInstances.getAll()).length, 1);-- assert.deepEqual(await api.desktopStorage.getStatus(), {- available: true,- authorityExpected: false,- schemaVersion: 1,- quarantined: false,- quarantineReason: null,- unavailableReason: null,- });- storage.close();- });-- test('carries the import request and its phase marker over one channel call', async () => {- const {storage, api} = createBridge();-- const accounts = await api.desktopAccounts.import({- records: [{storageKey: ACCOUNT_KEY, record: ACCOUNT_RECORD}],- marker: {key: 'import.phase', value: 'accounts'},- });- assert.deepEqual(accounts, {imported: 1, skipped: [], unusableInstances: []});-- const entries = await api.desktopStorage.import({- entries: [{scope: ACCOUNT_KEY, key: 'Theme', value: 'dark', updatedAt: 7}],- marker: {key: 'import.phase', value: 'entries'},- });- assert.deepEqual(entries, {imported: 1, skipped: []});- assert.equal(await api.desktopStorage.getMarker('import.phase'), 'entries');- storage.close();- });-- test('surfaces a rejected request to the renderer rather than resolving with a wrong value', async () => {- const {storage, api} = createBridge();- await assert.rejects(() => api.desktopAccounts.get(''), /must be a non-empty NUL-free string/);- storage.close();- });-});diff --git a/fluxer_desktop/src/main/DesktopAppStoreHealth.test.mjs b/fluxer_desktop/src/main/DesktopAppStoreHealth.test.mjsdeleted file mode 100644index 8c9129fc9..000000000--- a/fluxer_desktop/src/main/DesktopAppStoreHealth.test.mjs+++ /dev/null@@ -1,85 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {readFileSync, writeFileSync} from 'node:fs';-import {describe, test} from 'node:test';-import {createTemporaryUserData} from './DesktopAppStorageHarness.mjs';-import {- DESKTOP_APP_STORE_STATE_FILE_NAME,- DesktopAppStoreHealth,- desktopAppStoreStateFile,- evaluateDesktopAppStoreHealth,- readDesktopAppStoreState,- recordDesktopAppStoreSuccess,-} from './DesktopAppStoreHealth.ts';--describe('DesktopAppStoreHealth', () => {- test('names the state file the plan requires, beside the store', () => {- const userDataPath = createTemporaryUserData();- assert.equal(DESKTOP_APP_STORE_STATE_FILE_NAME, 'account-store-state-v1.json');- assert.equal(desktopAppStoreStateFile(userDataPath).endsWith(DESKTOP_APP_STORE_STATE_FILE_NAME), true);- });-- test('an addon that never worked here falls back silently rather than reporting a regression', () => {- const userDataPath = createTemporaryUserData();- assert.equal(readDesktopAppStoreState(userDataPath), null);- assert.equal(- evaluateDesktopAppStoreHealth({available: false, state: readDesktopAppStoreState(userDataPath)}),- DesktopAppStoreHealth.UNPROVEN,- );- });-- test('a store that worked yesterday and cannot open today is a regression', () => {- const userDataPath = createTemporaryUserData();- recordDesktopAppStoreSuccess({userDataPath, now: 1_755_000_000_000, schemaVersion: 1});- assert.equal(- evaluateDesktopAppStoreHealth({available: false, state: readDesktopAppStoreState(userDataPath)}),- DesktopAppStoreHealth.REGRESSED,- );- });-- test('records the first success once and moves the last success forward', () => {- const userDataPath = createTemporaryUserData();- const first = recordDesktopAppStoreSuccess({userDataPath, now: 1_755_000_000_000, schemaVersion: 1});- const second = recordDesktopAppStoreSuccess({userDataPath, now: 1_755_000_600_000, schemaVersion: 2});-- assert.deepEqual(first, {- version: 1,- firstSuccessAt: 1_755_000_000_000,- lastSuccessAt: 1_755_000_000_000,- lastSchemaVersion: 1,- });- assert.deepEqual(second, {- version: 1,- firstSuccessAt: 1_755_000_000_000,- lastSuccessAt: 1_755_000_600_000,- lastSchemaVersion: 2,- });- assert.deepEqual(readDesktopAppStoreState(userDataPath), second);- assert.equal(- evaluateDesktopAppStoreHealth({available: true, state: readDesktopAppStoreState(userDataPath)}),- DesktopAppStoreHealth.HEALTHY,- );- });-- test('an unreadable or foreign state file reads as never having worked', () => {- const userDataPath = createTemporaryUserData();- writeFileSync(desktopAppStoreStateFile(userDataPath), 'not json', 'utf8');- assert.equal(readDesktopAppStoreState(userDataPath), null);-- writeFileSync(- desktopAppStoreStateFile(userDataPath),- JSON.stringify({version: 99, firstSuccessAt: 1, lastSuccessAt: 2, lastSchemaVersion: 1}),- 'utf8',- );- assert.equal(readDesktopAppStoreState(userDataPath), null);- });-- test('never removes or truncates the store and only writes its own state file', () => {- const userDataPath = createTemporaryUserData();- recordDesktopAppStoreSuccess({userDataPath, now: 1_755_000_000_000, schemaVersion: 1});- const source = readFileSync(new URL('./DesktopAppStoreHealth.ts', import.meta.url), 'utf8');-- assert.equal(/unlinkSync|rmSync|rimraf|dialog|showErrorBox|showMessageBox/.test(source), false);- });-});diff --git a/fluxer_desktop/src/main/DesktopLastRoute.test.mjs b/fluxer_desktop/src/main/DesktopLastRoute.test.mjsdeleted file mode 100644index 2c795ac7b..000000000--- a/fluxer_desktop/src/main/DesktopLastRoute.test.mjs+++ /dev/null@@ -1,137 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {existsSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';-import {tmpdir} from 'node:os';-import nodePath from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();--const {- recordDesktopLastRoute,- resolveDesktopLandingUrl,- desktopLastRouteFilePath,- seedDesktopLastRouteFromLegacyStorage,-} = await import('./DesktopLastRoute.ts');-const {isRestorableDesktopRoutePath} = await import('@fluxer/desktop_ipc/src/LastRouteContract');--const DEFAULT_LANDING = 'fluxer-app://app/channels/@me';--function withTempUserData(run) {- const dir = mkdtempSync(nodePath.join(tmpdir(), 'fluxer-last-route-'));- try {- run(dir);- } finally {- rmSync(dir, {recursive: true, force: true});- }-}--describe('DesktopLastRoute', () => {- test('falls back to the default landing url when nothing is stored', () => {- withTempUserData((dir) => {- assert.equal(resolveDesktopLandingUrl(dir), DEFAULT_LANDING);- });- });-- test('round-trips a recorded route into a same-origin landing url', () => {- withTempUserData((dir) => {- recordDesktopLastRoute(dir, '/channels/123/456');- assert.equal(resolveDesktopLandingUrl(dir), 'fluxer-app://app/channels/123/456');- });- });-- test('ignores an unsafe stored path and uses the default', () => {- withTempUserData((dir) => {- writeFileSync(desktopLastRouteFilePath(dir), JSON.stringify({path: '//evil.example'}));- assert.equal(resolveDesktopLandingUrl(dir), DEFAULT_LANDING);- });- });-- test('refuses to persist an unsafe route', () => {- withTempUserData((dir) => {- recordDesktopLastRoute(dir, 'https://evil.example');- assert.equal(resolveDesktopLandingUrl(dir), DEFAULT_LANDING);- });- });-- test('tolerates a corrupt store file', () => {- withTempUserData((dir) => {- writeFileSync(desktopLastRouteFilePath(dir), 'not json');- assert.equal(resolveDesktopLandingUrl(dir), DEFAULT_LANDING);- });- });-});--describe('seedDesktopLastRouteFromLegacyStorage', () => {- const LEGACY_SESSION = {token: 'legacy-token', userId: '1555292173950255104'};-- function legacyLocation(lastLocation) {- return JSON.stringify({lastLocation, lastMobileLayoutState: null, __mps__: {version: 1}});- }-- test('lands the first migrated boot on the last location of the old client', () => {- withTempUserData((dir) => {- seedDesktopLastRouteFromLegacyStorage(dir, {- ...LEGACY_SESSION,- Location: legacyLocation('/channels/@me/1555292173950255104'),- });- assert.equal(resolveDesktopLandingUrl(dir), 'fluxer-app://app/channels/@me/1555292173950255104');- });- });-- test('keeps a route the new client already recorded', () => {- withTempUserData((dir) => {- recordDesktopLastRoute(dir, '/channels/123/456');- seedDesktopLastRouteFromLegacyStorage(dir, {...LEGACY_SESSION, Location: legacyLocation('/channels/@me/789')});- assert.equal(resolveDesktopLandingUrl(dir), 'fluxer-app://app/channels/123/456');- });- });-- test('does not seed a route for a signed-out old client', () => {- withTempUserData((dir) => {- seedDesktopLastRouteFromLegacyStorage(dir, {Location: legacyLocation('/channels/@me/789')});- seedDesktopLastRouteFromLegacyStorage(dir, {token: '', userId: '', Location: legacyLocation('/channels/1/2')});- assert.equal(existsSync(desktopLastRouteFilePath(dir)), false);- });- });-- test('ignores a missing, corrupt or unsafe legacy location', () => {- withTempUserData((dir) => {- seedDesktopLastRouteFromLegacyStorage(dir, LEGACY_SESSION);- seedDesktopLastRouteFromLegacyStorage(dir, {...LEGACY_SESSION, Location: 'not json'});- seedDesktopLastRouteFromLegacyStorage(dir, {...LEGACY_SESSION, Location: 'null'});- seedDesktopLastRouteFromLegacyStorage(dir, {...LEGACY_SESSION, Location: legacyLocation(null)});- seedDesktopLastRouteFromLegacyStorage(dir, {...LEGACY_SESSION, Location: legacyLocation('https://evil.example')});- assert.equal(existsSync(desktopLastRouteFilePath(dir)), false);- });- });-});--describe('isRestorableDesktopRoutePath', () => {- test('accepts ordinary in-app routes', () => {- for (const value of ['/channels/@me', '/channels/123/456', '/channels/@me/789?jump=1', '/discover']) {- assert.equal(isRestorableDesktopRoutePath(value), true, value);- }- });-- test('rejects unsafe or non-string values', () => {- for (const value of [- null,- undefined,- 42,- '',- 'channels/@me',- '//evil.example',- 'https://evil.example',- '/foo://bar',- '/a/../../etc/passwd',- '/a\\b',- '/a\nb',- `/${'a'.repeat(600)}`,- ]) {- assert.equal(isRestorableDesktopRoutePath(value), false, String(value));- }- });-});diff --git a/fluxer_desktop/src/main/DesktopTaskbarBadgeSetting.test.mjs b/fluxer_desktop/src/main/DesktopTaskbarBadgeSetting.test.mjsdeleted file mode 100644index ef1261580..000000000--- a/fluxer_desktop/src/main/DesktopTaskbarBadgeSetting.test.mjs+++ /dev/null@@ -1,52 +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 {getDesktopWindowBehaviorSettings, loadDesktopConfig, setDesktopWindowBehaviorSettings} = await import(- '../common/DesktopConfig.ts'-);--function loadSettings(windowBehavior) {- const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-desktop-taskbar-badge-setting-test-'));- fs.writeFileSync(path.join(userDataPath, 'settings.json'), JSON.stringify({window_behavior: windowBehavior}));- loadDesktopConfig(userDataPath);- return userDataPath;-}--function readPersisted(userDataPath) {- return JSON.parse(fs.readFileSync(path.join(userDataPath, 'settings.json'), 'utf8')).window_behavior;-}--describe('dark taskbar badge setting', () => {- test('defaults to the red badge for existing and new configs', () => {- loadSettings(undefined);- assert.equal(getDesktopWindowBehaviorSettings().darkTaskbarBadge, false);- loadSettings({showTrayIcon: true, coloredTrayIcon: true});- assert.equal(getDesktopWindowBehaviorSettings().darkTaskbarBadge, false);- });-- test('drops values that are not booleans', () => {- for (const value of ['true', 1, null, {}]) {- loadSettings({darkTaskbarBadge: value});- assert.equal(getDesktopWindowBehaviorSettings().darkTaskbarBadge, false, String(value));- }- });-- test('persists and reloads the choice without touching the tray settings', () => {- const userDataPath = loadSettings({showTrayIcon: false, coloredTrayIcon: true});- assert.equal(setDesktopWindowBehaviorSettings({darkTaskbarBadge: true}).darkTaskbarBadge, true);- assert.equal(readPersisted(userDataPath).darkTaskbarBadge, true);- loadDesktopConfig(userDataPath);- const settings = getDesktopWindowBehaviorSettings();- assert.equal(settings.darkTaskbarBadge, true);- assert.equal(settings.showTrayIcon, false);- assert.equal(settings.coloredTrayIcon, true);- });-});diff --git a/fluxer_desktop/src/main/DesktopTrayIcon.test.mjs b/fluxer_desktop/src/main/DesktopTrayIcon.test.mjsdeleted file mode 100644index 698224307..000000000--- a/fluxer_desktop/src/main/DesktopTrayIcon.test.mjs+++ /dev/null@@ -1,149 +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, installTestModuleStub} from './LocalAppTestSupport.test.mjs';-import {fakeNativeImageModule, pixel} from './TrayIconTestSupport.test.mjs';--const resourcesPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-desktop-tray-icon-test-'));-fs.mkdirSync(path.join(resourcesPath, 'icons'));-fs.writeFileSync(path.join(resourcesPath, 'icons', '16x16.png'), '');-Object.defineProperty(process, 'resourcesPath', {value: resourcesPath, configurable: true});-Object.defineProperty(process, 'platform', {value: 'win32', configurable: true});--const settings = {showTrayIcon: true, coloredTrayIcon: false};-globalThis.__fluxerDesktopTrayIconTestSettings__ = settings;--installTestModuleStub(- '@electron/common/DesktopConfig',- 'export const getDesktopWindowBehaviorSettings = () => ({...globalThis.__fluxerDesktopTrayIconTestSettings__});',-);-installTestModuleStub(- '@electron/main/DesktopUpdatePrompt',- 'export const checkForUpdatesFromShell = async () => {}; export const startDesktopUpdateFromShell = () => {};',-);-installTestModuleStub('@electron/main/LinuxLaunchPath', 'export const relaunchStableLaunchPath = () => {};');--const trays = [];--class FakeTray {- constructor(image) {- this.images = [image];- this.toolTips = [];- this.destroyed = false;- trays.push(this);- }-- get image() {- return this.images.at(-1);- }-- setImage(image) {- this.images.push(image);- }-- setToolTip(toolTip) {- this.toolTips.push(toolTip);- }-- setContextMenu() {}-- on() {}-- removeAllListeners() {}-- isDestroyed() {- return this.destroyed;- }-- destroy() {- this.destroyed = true;- }-}--const themeListeners = [];-const nativeTheme = {- shouldUseDarkColorsForSystemIntegratedUI: true,- on: (event, listener) => {- if (event === 'updated') themeListeners.push(listener);- },-};--installElectronStub({- nativeImage: fakeNativeImageModule,- nativeTheme,- Tray: FakeTray,- Menu: {buildFromTemplate: () => ({})},- clipboard: {},- app: {getPath: () => resourcesPath},-});--const {applyDesktopWindowBehaviorSettings, initializeDesktopTray, setDesktopTrayUnreadBadge} = await import(- './DesktopTray.ts'-);--const controller = {- createWindow: () => null,- getMainWindow: () => null,- isMainWindowTakenOver: () => false,- hideWindow: () => {},- setQuitting: () => {},- showWindow: () => {},-};--function topRight(image) {- return pixel(image.toBitmap(), 16, 12, 3);-}--describe('desktop tray icon state', () => {- test('follows the unread badge, theme and colored setting, and survives tray recreation', () => {- initializeDesktopTray(controller);- const [tray] = trays;- const plainWhite = tray.image;- assert.deepEqual(topRight(plainWhite), [0xff, 0xff, 0xff, 0xff], 'white glyph on a dark taskbar');- assert.match(tray.toolTips.at(-1), /^Fluxer[^-]*$/);-- setDesktopTrayUnreadBadge(3);- assert.equal(tray.images.length, 2);- assert.deepEqual(topRight(tray.image), [0x00, 0x00, 0xdd, 0xff], 'red dot');- assert.match(tray.toolTips.at(-1), / - Unread messages: 3$/);-- const dotted = tray.image;- setDesktopTrayUnreadBadge(4);- setDesktopTrayUnreadBadge(4);- setDesktopTrayUnreadBadge(-1);- assert.equal(tray.images.length, 2, 'the image is only set when the dot appears or disappears');- assert.match(tray.toolTips.at(-1), / - Unread messages$/);-- setDesktopTrayUnreadBadge(0);- assert.equal(tray.image, plainWhite, 'clearing reuses the cached plain image');- setDesktopTrayUnreadBadge(2);- assert.equal(tray.image, dotted, 'the dotted image is cached too');-- nativeTheme.shouldUseDarkColorsForSystemIntegratedUI = false;- for (const listener of themeListeners) listener();- assert.deepEqual(topRight(tray.image), [0x00, 0x00, 0xdd, 0xff]);- assert.deepEqual(pixel(tray.image.toBitmap(), 16, 2, 8), [0x1c, 0x1c, 0x1c, 0xff], 'dark glyph on a light taskbar');-- settings.coloredTrayIcon = true;- applyDesktopWindowBehaviorSettings();- assert.deepEqual(pixel(tray.image.toBitmap(), 16, 2, 8), [0xd9, 0x41, 0x46, 0xff], 'colored icon');- assert.deepEqual(topRight(tray.image), [0x00, 0x00, 0xdd, 0xff], 'the dot stays on the colored icon');-- settings.showTrayIcon = false;- applyDesktopWindowBehaviorSettings();- assert.equal(tray.destroyed, true);- setDesktopTrayUnreadBadge(0);- settings.showTrayIcon = true;- applyDesktopWindowBehaviorSettings();- assert.equal(trays.length, 2);- assert.deepEqual(trays[1].images.length, 1);- assert.deepEqual(pixel(trays[1].image.toBitmap(), 16, 2, 8), [0xd9, 0x41, 0x46, 0xff]);- assert.notDeepEqual(topRight(trays[1].image), [0x00, 0x00, 0xdd, 0xff], 'a recreated tray shows the current state');- setDesktopTrayUnreadBadge(1);- assert.deepEqual(topRight(trays[1].image), [0x00, 0x00, 0xdd, 0xff]);- });-});diff --git a/fluxer_desktop/src/main/DesktopTrayIconSetting.test.mjs b/fluxer_desktop/src/main/DesktopTrayIconSetting.test.mjsdeleted file mode 100644index efcf5ec06..000000000--- a/fluxer_desktop/src/main/DesktopTrayIconSetting.test.mjs+++ /dev/null@@ -1,51 +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 {getDesktopWindowBehaviorSettings, loadDesktopConfig, setDesktopWindowBehaviorSettings} = await import(- '../common/DesktopConfig.ts'-);--function loadSettings(windowBehavior) {- const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-desktop-tray-setting-test-'));- fs.writeFileSync(path.join(userDataPath, 'settings.json'), JSON.stringify({window_behavior: windowBehavior}));- loadDesktopConfig(userDataPath);- return userDataPath;-}--function readPersisted(userDataPath) {- return JSON.parse(fs.readFileSync(path.join(userDataPath, 'settings.json'), 'utf8')).window_behavior;-}--describe('colored tray icon setting', () => {- test('defaults to the monochrome icon for existing and new configs', () => {- loadSettings(undefined);- assert.equal(getDesktopWindowBehaviorSettings().coloredTrayIcon, false);- loadSettings({showTrayIcon: true});- assert.equal(getDesktopWindowBehaviorSettings().coloredTrayIcon, false);- });-- test('drops values that are not booleans', () => {- for (const value of ['true', 1, null, {}]) {- loadSettings({coloredTrayIcon: value});- assert.equal(getDesktopWindowBehaviorSettings().coloredTrayIcon, false, String(value));- }- });-- test('persists and reloads the choice without touching the tray visibility', () => {- const userDataPath = loadSettings({showTrayIcon: false});- assert.equal(setDesktopWindowBehaviorSettings({coloredTrayIcon: true}).coloredTrayIcon, true);- assert.equal(readPersisted(userDataPath).coloredTrayIcon, true);- loadDesktopConfig(userDataPath);- const settings = getDesktopWindowBehaviorSettings();- assert.equal(settings.coloredTrayIcon, true);- assert.equal(settings.showTrayIcon, false);- });-});diff --git a/fluxer_desktop/src/main/GlobalShortcutMatcher.test.mjs b/fluxer_desktop/src/main/GlobalShortcutMatcher.test.mjsdeleted file mode 100644index b9c80b5af..000000000--- a/fluxer_desktop/src/main/GlobalShortcutMatcher.test.mjs+++ /dev/null@@ -1,255 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {loadTsModule} from './fixtures/TsModuleLoader.mjs';--const {GlobalShortcutMatcher, bindingFromCombo} = loadTsModule('@electron/main/GlobalShortcutMatcher');--function combo(overrides) {- return {key: '', ctrl: false, alt: false, shift: false, meta: false, ...overrides};-}--function key(type, code, {key = null, raw, ctrl = false, alt = false, shift = false, meta = false} = {}) {- return {type, code, key, rawKeycode: raw, ctrlKey: ctrl, altKey: alt, shiftKey: shift, metaKey: meta};-}--function mouse(type, button, mods = {}) {- return {- type,- button,- ctrlKey: mods.ctrl === true,- altKey: mods.alt === true,- shiftKey: mods.shift === true,- metaKey: mods.meta === true,- };-}--function matcherWith(...entries) {- const matcher = new GlobalShortcutMatcher();- matcher.setBindings(entries.map(([sourceId, action, value]) => bindingFromCombo(sourceId, action, combo(value))));- return matcher;-}--function phases(transitions) {- return transitions.map((transition) => `${transition.phase}:${transition.sourceId}`);-}--describe('GlobalShortcutMatcher modifiers', () => {- test('bindings with modifiers need an exact modifier match', () => {- const matcher = matcherWith(['custom:a', 'voice_toggle_mute', {key: 'F5', code: 'F5', ctrl: true}]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'F5', {raw: 63, ctrl: true, shift: true}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'F5', {raw: 63}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'F5', {raw: 63, ctrl: true}), true)), ['press:custom:a']);- });-- test('bindings without modifiers fire with extra modifiers held, for toggles and holds alike', () => {- const matcher = matcherWith(- ['custom:toggle', 'voice_toggle_mute', {key: 'F6', code: 'F6'}],- ['custom:hold', 'voice_push_to_talk', {key: 'F7', code: 'F7'}],- );- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'F6', {raw: 64, shift: true}), true)), [- 'press:custom:toggle',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'F7', {raw: 65, ctrl: true, alt: true}), true)), [- 'press:custom:hold',- ]);- });-- test('release follows the main key regardless of modifier order', () => {- const matcher = matcherWith(['custom:a', 'voice_push_to_talk', {key: ' ', code: 'Space', ctrl: true}]);- matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29}), true);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'Space', {raw: 57, ctrl: true}), true)), [- 'press:custom:a',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'ControlLeft', {raw: 29}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'Space', {raw: 57}), true)), ['release:custom:a']);- });-- test('autorepeat never emits a second press', () => {- const matcher = matcherWith(['custom:a', 'voice_push_to_talk', {key: 'F8', code: 'F8'}]);- assert.equal(matcher.handleKey(key('keydown', 'F8', {raw: 66}), true).length, 1);- assert.equal(matcher.handleKey(key('keydown', 'F8', {raw: 66}), true).length, 0);- assert.equal(matcher.handleKey(key('keyup', 'F8', {raw: 66}), true).length, 1);- });-});--describe('GlobalShortcutMatcher modifier-only combos', () => {- test('presses when every required modifier is down and releases when one goes up', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'Control', code: 'ControlLeft', ctrl: true, alt: true, modifierOnly: true},- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'AltRight', {raw: 100, ctrl: true}), true)), [- 'press:custom:a',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'AltRight', {raw: 100}), true)), ['release:custom:a']);- });-- test('bothSides requires the left and right key of the modifier', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'Shift', code: 'ShiftLeft', shift: true, modifierOnly: true, bothSides: true},- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ShiftLeft', {raw: 42}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ShiftRight', {raw: 54, shift: true}), true)), [- 'press:custom:a',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'ShiftLeft', {raw: 42, shift: true}), true)), [- 'release:custom:a',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'ShiftRight', {raw: 54}), true)), []);- });-- test('a modifier release reported as a keydown still releases once the flags clear', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'Shift', code: 'ShiftLeft', shift: true, modifierOnly: true},- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ShiftLeft', {raw: 0x38, shift: true}), true)), [- 'press:custom:a',- ]);- matcher.handleKey(key('keydown', 'ShiftRight', {raw: 0x3c, shift: true}), true);- matcher.handleKey(key('keydown', 'ShiftRight', {raw: 0x3c, shift: true}), true);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'ShiftLeft', {raw: 0x38}), true)), ['release:custom:a']);- });-- test('a lost modifier keyup is recovered from the flags of the next event', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'Control', code: 'ControlLeft', ctrl: true, modifierOnly: true},- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29}), true)), ['press:custom:a']);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'KeyA', {raw: 30}), true)), ['release:custom:a']);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29}), true)), ['press:custom:a']);- assert.deepEqual(phases(matcher.handleMouse(mouse('mousedown', 1), true)), ['release:custom:a']);- });-- test('a modifier code the backend cannot flag is kept until its own key-up', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'AltGraph', code: 'AltRight', modifierOnly: true},- ]);- const unflaggedModifierCodes = ['AltRight'];- assert.deepEqual(- phases(matcher.handleKey({...key('keydown', 'AltRight', {raw: 108}), unflaggedModifierCodes}, true)),- ['press:custom:a'],- );- assert.deepEqual(phases(matcher.handleMouse({...mouse('mousedown', 0), unflaggedModifierCodes}, true)), []);- assert.deepEqual(- phases(matcher.handleKey({...key('keydown', 'KeyQ', {raw: 24}), unflaggedModifierCodes}, true)),- [],- );- assert.deepEqual(phases(matcher.handleKey({...key('keyup', 'KeyQ', {raw: 24}), unflaggedModifierCodes}, true)), []);- assert.deepEqual(- phases(matcher.handleKey({...key('keyup', 'AltRight', {raw: 108}), unflaggedModifierCodes}, true)),- ['release:custom:a'],- );- });-- test('AltGr reported with Ctrl and Alt flags keeps a Right Alt hold', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'AltGraph', code: 'AltRight', modifierOnly: true},- ]);- matcher.handleKey(key('keydown', 'ControlLeft', {raw: 0x1d}), true);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'AltRight', {raw: 0xe038, ctrl: true}), true)), [- 'press:custom:a',- ]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'KeyQ', {raw: 0x10, ctrl: true, alt: true}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'AltRight', {raw: 0xe038, ctrl: true, alt: true}), true)), [- 'release:custom:a',- ]);- });-- test('a stuck modifier no longer satisfies a combined modifier-only binding', () => {- const matcher = matcherWith([- 'custom:a',- 'voice_push_to_talk',- {key: 'Alt', code: 'AltLeft', ctrl: true, alt: true, modifierOnly: true},- ]);- matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29, ctrl: true}), true);- matcher.handleKey(key('keydown', 'KeyL', {raw: 38, meta: true}), true);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'AltLeft', {raw: 56, alt: true}), true)), []);- });-});--describe('GlobalShortcutMatcher modifier-only kinds', () => {- test('the trigger key counts as a required modifier alongside the flags', () => {- const binding = bindingFromCombo(- 'custom:a',- 'voice_push_to_talk',- combo({key: 'Shift', code: 'ShiftLeft', ctrl: true, modifierOnly: true}),- );- assert.deepEqual(binding.trigger, {kind: 'modifier-only', modifiers: ['ctrl', 'shift'], bothSides: false});- const matcher = new GlobalShortcutMatcher();- matcher.setBindings([binding]);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ControlLeft', {raw: 29, ctrl: true}), true)), []);- assert.deepEqual(phases(matcher.handleKey(key('keydown', 'ShiftLeft', {raw: 42, ctrl: true, shift: true}), true)), [- 'press:custom:a',- ]);- });-});--describe('GlobalShortcutMatcher mouse buttons', () => {- test('match by button with the same modifier rule and release on mouseup', () => {- const matcher = matcherWith(['custom:a', 'voice_push_to_talk', {key: '', mouseButton: 4}]);- assert.deepEqual(phases(matcher.handleMouse(mouse('mousedown', 3), true)), []);- assert.deepEqual(phases(matcher.handleMouse(mouse('mousedown', 4, {shift: true}), true)), ['press:custom:a']);- assert.deepEqual(phases(matcher.handleMouse(mouse('mouseup', 4), true)), ['release:custom:a']);- });-});--describe('GlobalShortcutMatcher lifecycle', () => {- test('a paused press is never recorded, so no release follows', () => {- const matcher = matcherWith(['custom:a', 'voice_push_to_talk', {key: 'F9', code: 'F9'}]);- assert.deepEqual(matcher.handleKey(key('keydown', 'F9', {raw: 67}), false), []);- assert.deepEqual(matcher.handleKey(key('keyup', 'F9', {raw: 67}), true), []);- });-- test('releases still flow while paused', () => {- const matcher = matcherWith(['custom:a', 'voice_push_to_talk', {key: 'F9', code: 'F9'}]);- matcher.handleKey(key('keydown', 'F9', {raw: 67}), true);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'F9', {raw: 67}), false)), ['release:custom:a']);- });-- test('sync keeps unchanged pressed sources and releases removed or changed ones', () => {- const matcher = new GlobalShortcutMatcher();- const kept = bindingFromCombo('custom:kept', 'voice_push_to_talk', combo({key: 'F1', code: 'F1'}));- const changed = bindingFromCombo('custom:changed', 'voice_push_to_mute', combo({key: 'F2', code: 'F2'}));- const removed = bindingFromCombo('custom:removed', 'voice_toggle_mute', combo({key: 'F3', code: 'F3'}));- matcher.setBindings([kept, changed, removed]);- matcher.handleKey(key('keydown', 'F1', {raw: 59}), true);- matcher.handleKey(key('keydown', 'F2', {raw: 60}), true);- matcher.handleKey(key('keydown', 'F3', {raw: 61}), true);- const released = matcher.setBindings([- bindingFromCombo('custom:kept', 'voice_push_to_talk', combo({key: 'F1', code: 'F1'})),- bindingFromCombo('custom:changed', 'voice_push_to_mute', combo({key: 'F4', code: 'F4'})),- ]);- assert.deepEqual(phases(released).sort(), ['release:custom:changed', 'release:custom:removed']);- assert.deepEqual(phases(matcher.handleKey(key('keyup', 'F1', {raw: 59}), true)), ['release:custom:kept']);- });-- test('releaseAll releases every pressed source', () => {- const matcher = matcherWith(- ['custom:a', 'voice_push_to_talk', {key: 'F1', code: 'F1'}],- ['custom:b', 'voice_push_to_mute', {key: '', mouseButton: 3}],- );- matcher.handleKey(key('keydown', 'F1', {raw: 59}), true);- matcher.handleMouse(mouse('mousedown', 3), true);- assert.deepEqual(phases(matcher.releaseAll()).sort(), ['release:custom:a', 'release:custom:b']);- assert.deepEqual(matcher.releaseAll(), []);- });-- test('combos without any key identity are dropped', () => {- assert.equal(bindingFromCombo('custom:a', 'voice_push_to_talk', combo({key: ''})), null);- assert.equal(bindingFromCombo('custom:a', 'voice_push_to_talk', combo({key: '', modifierOnly: true})), null);- });-});diff --git a/fluxer_desktop/src/main/GlobalShortcutsEngine.test.mjs b/fluxer_desktop/src/main/GlobalShortcutsEngine.test.mjsdeleted file mode 100644index 509918083..000000000--- a/fluxer_desktop/src/main/GlobalShortcutsEngine.test.mjs+++ /dev/null@@ -1,975 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {loadTsModule} from './fixtures/TsModuleLoader.mjs';--const legacyHandlers = new Map();-const legacyStubs = {- electron: {ipcMain: {handle: (channel, handler) => legacyHandlers.set(channel, handler)}},- '@electron/main/PrivilegedRendererDocuments': {requirePrivilegedRendererDocumentSender: () => {}},-};-const engineModule = loadTsModule('@electron/main/GlobalShortcutsEngine');-const {GlobalShortcutsEngine, sanitizeGlobalShortcutsSyncPayload, portalDefinitionsFromStored, storedActionsFromSync} =- engineModule;-const {LinuxPortalShortcutsManager} = loadTsModule('@electron/main/LinuxGlobalShortcutsPortal');-const legacy = loadTsModule('@electron/main/LegacyGlobalKeyHookIpc', {stubs: legacyStubs});-const {GLOBAL_SHORTCUT_ACTIONS} = loadTsModule('@electron/common/GlobalShortcutActions');-const {bindingFromCombo, GlobalShortcutMatcher} = loadTsModule('@electron/main/GlobalShortcutMatcher');-const native = loadTsModule('@electron/main/GlobalShortcutsNative', {- stubs: {- 'node:module': {createRequire: () => () => ({})},- '@electron/common/Logger': {createChildLogger: () => ({info: () => {}, warn: () => {}})},- '@electron/main/MacTcc': {getTccStatus: () => 'granted'},- },-});--function combo(overrides) {- return {key: '', ctrl: false, alt: false, shift: false, meta: false, ...overrides};-}--function keyEvent(type, code, raw, mods = {}, native = {keycode: raw, keyName: code}) {- return {- type,- code,- key: null,- rawKeycode: raw,- ctrlKey: mods.ctrl === true,- altKey: mods.alt === true,- shiftKey: mods.shift === true,- metaKey: mods.meta === true,- native,- };-}--class FakeHook {- constructor(kind, harness) {- this.kind = kind;- this.harness = harness;- this.stopped = false;- }-- async start(onEvent) {- this.harness.started.push(this.kind);- this.pendingOnEvent = onEvent;- const result = await (this.harness.startResults.shift() ?? 'ok');- if (result === 'ok') this.onEvent = onEvent;- return result;- }-- stop() {- this.stopped = true;- this.harness.stopped.push(this.kind);- }-}--function createSettings(initial = {}) {- const state = {directInputEnabled: false, migrated: false, lastActions: [], ...initial};- return {- state,- getDirectInputEnabled: () => state.directInputEnabled,- setDirectInputEnabled: (enabled) => {- state.directInputEnabled = enabled;- },- isMigrated: () => state.migrated,- setMigrated: () => {- state.migrated = true;- },- getLastActions: () => state.lastActions,- setLastActions: (actions) => {- state.lastActions = actions;- },- };-}--function createEngine({- platform = 'linux',- session = 'x11',- inputHookMode = 'auto',- keyboardReadable = false,- settings = createSettings(),- portalConsent = 'unset',- portalOpen = {version: 2, appIdSource: 'registered', uniqueName: ':1.9', listed: []},-} = {}) {- const harness = {- started: [],- stopped: [],- startResults: [],- hooks: [],- sent: [],- portals: [],- timers: [],- deviceWatches: [],- consent: portalConsent,- };- const schedule = (callback, delayMs) => {- const timer = {callback, delayMs, cancelled: false, cancel: () => (timer.cancelled = true)};- harness.timers.push(timer);- return timer;- };- harness.keyboardReadable = keyboardReadable;- let engine = null;- const linux = platform === 'linux' ? {session, sandboxed: false, desktop: 'gnome', inputHookMode} : null;- const portal =- linux !== null && session === 'wayland'- ? new LinuxPortalShortcutsManager({- createPortal: (onEvent) => {- const fake = {- onEvent,- closed: false,- open: async () => portalOpen,- bind: async () => ({- outcome: 'bound',- shortcuts: GLOBAL_SHORTCUT_ACTIONS.map((id) => ({id, description: id, triggerDescription: 'F13'})),- }),- configure: async () => {},- close: () => {- fake.closed = true;- },- };- harness.portals.push(fake);- return fake;- },- desktop: 'gnome',- plasma5: false,- portalAppId: 'app.fluxer.FluxerDesktop',- getConsent: () => harness.consent,- setConsent: (consent) => {- harness.consent = consent;- },- getDefinitions: () => [],- getParentWindow: () => '',- onShortcut: (action, phase) => engine?.handlePortalShortcut(action, phase),- onStatusChanged: () => engine?.notifyStatus(),- schedule: () => ({cancel: () => {}}),- now: () => 0,- log: () => {},- })- : null;- engine = new GlobalShortcutsEngine({- platform,- linux,- settings,- portal,- createHookBackend: (kind) => {- const hook = new FakeHook(kind, harness);- harness.hooks.push(hook);- return hook;- },- isDirectInputAvailable: () => harness.keyboardReadable,- watchInputDevices: (onChange) => {- const watch = {onChange, closed: false, close: () => (watch.closed = true)};- harness.deviceWatches.push(watch);- return watch;- },- schedule,- log: () => {},- });- harness.engine = engine;- harness.settings = settings;- harness.portal = portal;- harness.attach = (id) => engine.attachClient(id, (channel, payload) => harness.sent.push({id, channel, payload}));- harness.events = (id) =>- harness.sent- .filter((entry) => entry.id === id && entry.channel === 'global-shortcut-event')- .map((entry) => `${entry.payload.phase}:${entry.payload.sourceId}`);- harness.captured = (id) =>- harness.sent- .filter((entry) => entry.id === id && entry.channel === 'global-shortcuts:capture')- .map((entry) => entry.payload);- harness.activeHook = () => harness.hooks.find((hook) => hook.onEvent && !hook.stopped);- return harness;-}--function syncPayload(bindings, actions = []) {- return sanitizeGlobalShortcutsSyncPayload({bindings, actions});-}--async function settle() {- for (let index = 0; index < 20; index += 1) await Promise.resolve();-}--describe('sanitizeGlobalShortcutsSyncPayload', () => {- test('accepts well formed payloads and filters unknown actions', () => {- const payload = sanitizeGlobalShortcutsSyncPayload({- bindings: [- {- sourceId: 'default:voice_toggle_mute',- action: 'voice_toggle_mute',- combo: combo({key: 'm', ctrl: true}),- },- ],- actions: [- {- action: 'voice_toggle_mute',- description: 'Toggle mute',- preferredCombo: combo({key: 'm', ctrl: true}),- },- {action: 'not_global', description: 'Nope', preferredCombo: null},- {action: 'voice_push_to_talk', description: ' ', preferredCombo: null},- ],- });- assert.equal(payload.bindings.length, 1);- assert.deepEqual(- payload.actions.map((entry) => entry.action),- ['voice_toggle_mute'],- );- assert.deepEqual(storedActionsFromSync(payload.actions), [- {action: 'voice_toggle_mute', description: 'Toggle mute', preferredTrigger: 'CTRL+m'},- ]);- });-- test('ignores fields it does not know so older renderers still sync', () => {- const payload = sanitizeGlobalShortcutsSyncPayload({- bindings: [- {sourceId: 'custom:a', action: 'voice_push_to_talk', hold: true, extra: 1, combo: combo({key: 'F13'})},- ],- actions: [{action: 'voice_push_to_talk', description: 'Push to talk', hold: true, preferredCombo: null}],- version: 3,- });- assert.deepEqual(payload, {- bindings: [{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13'})}],- actions: [{action: 'voice_push_to_talk', description: 'Push to talk', preferredCombo: null}],- });- });-- test('rejects malformed bindings', () => {- assert.equal(sanitizeGlobalShortcutsSyncPayload(null), null);- assert.equal(sanitizeGlobalShortcutsSyncPayload({bindings: {}, actions: []}), null);- assert.equal(- sanitizeGlobalShortcutsSyncPayload({bindings: [{sourceId: 'a', action: 'b', combo: {key: 1}}], actions: []}),- null,- );- assert.equal(- sanitizeGlobalShortcutsSyncPayload({- bindings: [{sourceId: 'a', action: 'b', combo: combo({key: '', mouseButton: 99})}],- actions: [],- }),- null,- );- });-});--describe('portalDefinitionsFromStored safety', () => {- test('never sends blank descriptions, duplicates or malformed triggers', () => {- const definitions = portalDefinitionsFromStored([- {action: 'voice_toggle_mute', description: ' ', preferredTrigger: 'CTRL+,'},- {action: 'voice_toggle_mute', description: 'Again', preferredTrigger: 'F1'},- {action: 'voice_disconnect', description: 'Leave', preferredTrigger: 'NUM+KP_1'},- {action: 'voice_push_to_talk', description: 'Talk', preferredTrigger: 'SHIFT+F13'},- ]);- const ids = definitions.map((entry) => entry.id);- assert.equal(new Set(ids).size, GLOBAL_SHORTCUT_ACTIONS.length);- assert.ok(definitions.every((entry) => entry.description.trim().length > 0));- const byId = Object.fromEntries(definitions.map((entry) => [entry.id, entry]));- assert.equal(byId.voice_disconnect.preferredTrigger, undefined);- assert.equal(byId.voice_push_to_talk.preferredTrigger, 'SHIFT+F13');- assert.equal(byId.voice_toggle_mute.description.trim().length > 0, true);- });-});--describe('GlobalShortcutsEngine hook backends', () => {- test('starts the hook only once a client has bindings and emits press/release to that client', async () => {- const harness = createEngine({session: 'x11', settings: createSettings({migrated: true})});- harness.attach(1);- harness.attach(2);- await harness.engine.refreshHooks();- assert.deepEqual(harness.started, []);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- assert.deepEqual(harness.started, ['x11']);- assert.equal(harness.engine.getStatus().hooksActive, true);- const hook = harness.activeHook();- hook.onEvent(keyEvent('keydown', 'F13', 191));- hook.onEvent(keyEvent('keyup', 'F13', 191));- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a']);- assert.deepEqual(harness.events(2), []);- });-- test('pause suppresses presses only', async () => {- const harness = createEngine({session: 'x11', settings: createSettings({migrated: true})});- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- const hook = harness.activeHook();- hook.onEvent(keyEvent('keydown', 'F13', 191));- harness.engine.setPaused(1, true);- hook.onEvent(keyEvent('keyup', 'F13', 191));- hook.onEvent(keyEvent('keydown', 'F13', 191));- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a']);- });-- test('removing a binding mid-hold releases it and stops the idle hook', async () => {- const harness = createEngine({session: 'x11', settings: createSettings({migrated: true})});- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- harness.activeHook().onEvent(keyEvent('keydown', 'F13', 191));- harness.engine.sync(1, syncPayload([]));- await settle();- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a']);- assert.deepEqual(harness.stopped, ['x11']);- assert.equal(harness.engine.getStatus().hooksActive, false);- });-- test('a failed start is reported and retried on the next sync', async () => {- const harness = createEngine({platform: 'macos'});- harness.startResults.push('permission');- harness.attach(1);- const payload = syncPayload([- {sourceId: 'custom:a', action: 'voice_toggle_mute', combo: combo({key: 'm', meta: true})},- ]);- harness.engine.sync(1, payload);- await settle();- assert.equal(harness.engine.getStatus().hookError, 'permission');- assert.equal(harness.engine.getStatus().backend, 'macos');- harness.engine.sync(1, payload);- await settle();- assert.deepEqual(harness.started, ['macos', 'macos']);- assert.equal(harness.engine.getStatus().hookError, null);- assert.equal(harness.engine.getStatus().hooksActive, true);- });-- test('a backend dropped after its start resolves releases the presses it already sent', async () => {- const harness = createEngine({session: 'x11', keyboardReadable: true, settings: createSettings({migrated: true})});- let resolveStart;- harness.startResults.push(new Promise((resolve) => (resolveStart = resolve)));- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F9', code: 'F9'})}]),- );- await settle();- assert.deepEqual(harness.started, ['x11']);- harness.hooks[0].pendingOnEvent(keyEvent('keydown', 'F9', 75));- assert.deepEqual(harness.events(1), ['press:custom:a']);- harness.engine.setDirectInputEnabled(true);- resolveStart('ok');- await settle();- assert.deepEqual(harness.stopped, ['x11']);- assert.deepEqual(harness.started, ['x11', 'evdev']);- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a']);- });-- test('detaching a client stops the hook without touching other clients', async () => {- const harness = createEngine({platform: 'windows'});- harness.attach(1);- harness.attach(2);- const binding = [{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}];- harness.engine.sync(1, syncPayload(binding));- harness.engine.sync(2, syncPayload(binding));- await settle();- harness.engine.detachClient(1);- await settle();- assert.deepEqual(harness.stopped, []);- harness.activeHook().onEvent(keyEvent('keydown', 'F13', 0x64));- assert.deepEqual(harness.events(2), ['press:custom:a']);- assert.deepEqual(harness.events(1), []);- });-});--describe('GlobalShortcutsEngine Linux backend selection', () => {- test('Wayland uses the portal and never starts a hook', async () => {- const harness = createEngine({session: 'wayland', settings: createSettings({migrated: true})});- harness.engine.start();- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- const status = harness.engine.getStatus();- assert.equal(status.backend, 'portal');- assert.equal(status.linux.portal.state, 'not-set-up');- assert.equal(status.supportsMouseButtons, false);- assert.deepEqual(harness.started, []);- });-- test('the first sync migrates readable keyboards to direct input and closes the portal', async () => {- const harness = createEngine({session: 'wayland', keyboardReadable: true, portalConsent: 'granted'});- harness.engine.start();- harness.attach(1);- await settle();- assert.equal(harness.portals.length, 1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: '', mouseButton: 3})}]),- );- await settle();- assert.equal(harness.settings.state.migrated, true);- assert.equal(harness.settings.state.directInputEnabled, true);- assert.equal(harness.portals[0].closed, true);- assert.equal(harness.engine.getStatus().backend, 'evdev');- assert.deepEqual(harness.started, ['evdev']);- });-- test('migration only marks itself done when no keyboard is readable', async () => {- const harness = createEngine({session: 'wayland', keyboardReadable: false});- harness.engine.start();- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- assert.equal(harness.settings.state.migrated, true);- assert.equal(harness.settings.state.directInputEnabled, false);- assert.equal(harness.engine.getStatus().backend, 'portal');- });-});--describe('GlobalShortcutsEngine release on suspend', () => {- test('releaseAllPressed releases hook holds without stopping the hook', async () => {- const harness = createEngine({session: 'x11', settings: createSettings({migrated: true})});- harness.attach(1);- harness.engine.sync(- 1,- syncPayload([{sourceId: 'custom:a', action: 'voice_push_to_talk', combo: combo({key: 'F13', code: 'F13'})}]),- );- await settle();- const hook = harness.activeHook();- hook.onEvent(keyEvent('keydown', 'F13', 191));- harness.engine.releaseAllPressed();- hook.onEvent(keyEvent('keyup', 'F13', 191));- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a']);- assert.deepEqual(harness.stopped, []);- hook.onEvent(keyEvent('keydown', 'F13', 191));- assert.deepEqual(harness.events(1), ['press:custom:a', 'release:custom:a', 'press:custom:a']);- });-- test('releaseAllPressed releases portal holds', async () => {- const harness = createEngine({- session: 'wayland',- portalConsent: 'granted',- settings: createSettings({migrated: true}),- });- harness.engine.start();- harness.attach(1);- await settle();- harness.portals[0].onEvent({type: 'activated', id: 'voice_push_to_talk'});- harness.engine.releaseAllPressed();- harness.portals[0].onEvent({type: 'deactivated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.events(1), ['press:portal:voice_push_to_talk', 'release:portal:voice_push_to_talk']);- });-- test('a release-all on lock lets the next portal press through', async () => {- const harness = createEngine({- session: 'wayland',- portalConsent: 'granted',- settings: createSettings({migrated: true}),- });- harness.attach(1);- await settle();- const portal = harness.portals[0];- portal.onEvent({type: 'activated', id: 'voice_push_to_talk'});- harness.engine.releaseAllPressed();- portal.onEvent({type: 'activated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.events(1), [- 'press:portal:voice_push_to_talk',- 'release:portal:voice_push_to_talk',- 'press:portal:voice_push_to_talk',- ]);- });-- test('a portal release is only sent for a press the client received', async () => {- const harness = createEngine({- session: 'wayland',- portalConsent: 'granted',- settings: createSettings({migrated: true}),- });- harness.attach(1);- await settle();- harness.engine.setPaused(1, true);- harness.portals[0].onEvent({type: 'activated', id: 'voice_push_to_talk'});- harness.engine.setPaused(1, false);- harness.portals[0].onEvent({type: 'deactivated', id: 'voice_push_to_talk'});- harness.engine.releaseAllPressed();- assert.deepEqual(harness.events(1), []);- });-});--describe('GlobalShortcutsEngine portal lifecycle', () => {- test('the portal stays closed until a client of the new API calls in', async () => {- const harness = createEngine({- session: 'wayland',- portalConsent: 'granted',- settings: createSettings({migrated: true}),- });- harness.engine.start();- await settle();- assert.equal(harness.portals.length, 0);- assert.equal(harness.portal.getState(), 'unknown');- harness.attach(1);- await settle();- assert.equal(harness.portals.length, 1);- assert.equal(harness.portal.getState(), 'bound');- });-});--describe('GlobalShortcutsEngine capture', () => {- test('captures raw input on a hook backend for the requesting client only', async () => {- const harness = createEngine({session: 'x11', settings: createSettings({migrated: true})});- harness.attach(1);- harness.attach(2);- const captureId = await harness.engine.startCapture(1);- assert.equal(typeof captureId, 'number');- assert.deepEqual(harness.started, ['x11']);- const hook = harness.activeHook();- hook.onEvent({...keyEvent('keydown', 'PrintScreen', 107, {ctrl: true}), key: 'Print'});- hook.onEvent({- type: 'mousedown',- button: 4,- ctrlKey: false,- altKey: false,- shiftKey: false,- metaKey: false,- native: null,- });- assert.deepEqual(harness.captured(1), [- {- type: 'keydown',- code: 'PrintScreen',- key: 'Print',- button: null,- ctrl: true,- alt: false,- shift: false,- meta: false,- },- {type: 'mousedown', code: null, key: null, button: 4, ctrl: false, alt: false, shift: false, meta: false},- ]);- assert.deepEqual(harness.captured(2), []);- harness.engine.stopCapture(2, captureId);- hook.onEvent(keyEvent('keyup', 'PrintScreen', 107));- assert.equal(harness.captured(1).length, 3);- harness.engine.stopCapture(1, captureId);- await settle();- assert.deepEqual(harness.stopped, ['x11']);- assert.equal(harness.timers[0].cancelled, true);- });-- test('capture stops on its own after a minute and when the client goes away', async () => {- const harness = createEngine({platform: 'windows'});- harness.attach(1);- assert.notEqual(await harness.engine.startCapture(1), null);- assert.equal(harness.timers[0].delayMs, engineModule.GLOBAL_SHORTCUT_CAPTURE_TIMEOUT_MS);- harness.timers[0].callback();- await settle();- assert.deepEqual(harness.stopped, ['windows']);- assert.notEqual(await harness.engine.startCapture(1), null);- harness.engine.detachClient(1);- await settle();- assert.deepEqual(harness.stopped, ['windows', 'windows']);- });-- test('a late stop from a replaced capture leaves the newer capture running', async () => {- const harness = createEngine({platform: 'windows'});- harness.attach(1);- const first = await harness.engine.startCapture(1);- const secondStart = harness.engine.startCapture(1);- harness.engine.stopCapture(1, first);- const second = await secondStart;- assert.notEqual(second, null);- assert.notEqual(second, first);- await settle();- assert.deepEqual(harness.stopped, []);- harness.activeHook().onEvent(keyEvent('keydown', 'F13', 100));- assert.equal(harness.captured(1).length, 1);- harness.timers[0].callback();- await settle();- assert.deepEqual(harness.stopped, []);- harness.engine.stopCapture(1, second);- await settle();- assert.deepEqual(harness.stopped, ['windows']);- });-});--describe('GlobalShortcutsNative translation', () => {- function nativeKey(type, overrides) {- return {type, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, ...overrides};- }-- test('an old renderer media select registration matches the media select key', () => {- const binding = legacy.legacyRegistrationToBinding({id: 'key:media', keyName: 'LaunchMediaPlayer'});- assert.deepEqual(binding.trigger, {kind: 'key', layoutKey: 'LaunchMediaPlayer', code: 'MediaSelect'});- const matcher = new GlobalShortcutMatcher();- matcher.setBindings([binding]);- const identity = {keycode: 0xb5, keyName: 'LaunchMediaPlayer', scanCode: 0x6d, extended: true};- assert.equal(- matcher.handleKey(native.translateNativeHookEvent('windows', nativeKey('keydown', identity)), true).length,- 1,- );- });-- test('X11 Right Alt survives events whose Mod1 flag is clear on AltGr layouts', () => {- const matcher = new GlobalShortcutMatcher();- matcher.setBindings([- bindingFromCombo(- 'custom:a',- 'voice_push_to_talk',- combo({key: 'AltGraph', code: 'AltRight', modifierOnly: true}),- ),- ]);- const down = native.translateNativeHookEvent(- 'x11',- nativeKey('keydown', {keycode: 0xfe03, keyName: '', x11Keycode: 108}),- );- const click = native.translateNativeHookEvent('x11', {- type: 'mousedown',- button: 0,- ctrlKey: false,- altKey: false,- shiftKey: false,- metaKey: false,- });- const other = native.translateNativeHookEvent(- 'x11',- nativeKey('keydown', {keycode: 0x71, keyName: 'Q', x11Keycode: 24}),- );- const up = native.translateNativeHookEvent(- 'x11',- nativeKey('keyup', {keycode: 0xfe03, keyName: '', x11Keycode: 108}),- );- assert.deepEqual(matcher.handleKey(down, true), [- {sourceId: 'custom:a', action: 'voice_push_to_talk', phase: 'press'},- ]);- assert.deepEqual(matcher.handleMouse(click, true), []);- assert.deepEqual(matcher.handleKey(other, true), []);- assert.deepEqual(matcher.handleKey(up, true), [- {sourceId: 'custom:a', action: 'voice_push_to_talk', phase: 'release'},- ]);- });-- test('a left Alt hold still recovers from a lost key-up on X11', () => {- const matcher = new GlobalShortcutMatcher();- matcher.setBindings([- bindingFromCombo('custom:a', 'voice_push_to_talk', combo({key: 'Alt', code: 'AltLeft', modifierOnly: true})),- ]);- const down = native.translateNativeHookEvent(- 'x11',- nativeKey('keydown', {keycode: 0xffe9, keyName: 'AltLeft', x11Keycode: 64}),- );- const other = native.translateNativeHookEvent(- 'x11',- nativeKey('keydown', {keycode: 0x71, keyName: 'Q', x11Keycode: 24}),- );- assert.equal(matcher.handleKey(down, true).length, 1);- assert.deepEqual(matcher.handleKey(other, true), [- {sourceId: 'custom:a', action: 'voice_push_to_talk', phase: 'release'},- ]);- });-});--function loadNativeWith(modules) {- return loadTsModule('@electron/main/GlobalShortcutsNative', {- stubs: {- 'node:module': {createRequire: () => (name) => modules[name] ?? {loadError: null}},- '@electron/common/Logger': {createChildLogger: () => ({info: () => {}, warn: () => {}})},- '@electron/main/MacTcc': {getTccStatus: () => 'granted'},- },- });-}--describe('GlobalShortcutsNative backends', () => {- function x11Module(start) {- const instances = [];- class InputHook {- constructor(callback) {- this.callback = callback;- this.stopped = false;- instances.push(this);- }- start() {- return start(this);- }- stop() {- this.stopped = true;- }- }- return {instances, module: {InputHook, loadError: null}};- }-- test('an asynchronous native start is awaited before the hook counts as running', async () => {- let resolveStart;- const x11 = x11Module(() => new Promise((resolve) => (resolveStart = resolve)));- const loaded = loadNativeWith({'@fluxer/linux-input-hook': x11.module});- const backend = loaded.createNativeHookBackend('x11');- let settled = null;- const pending = backend.start(() => {}).then((result) => (settled = result));- await settle();- assert.equal(settled, null);- resolveStart();- await pending;- assert.equal(settled, 'ok');- backend.stop();- assert.equal(x11.instances[0].stopped, true);- });-- test('a rejected native start stops the instance and surfaces the error', async () => {- const x11 = x11Module(() => Promise.reject(new Error('XRecord extension not available')));- const backend = loadNativeWith({'@fluxer/linux-input-hook': x11.module}).createNativeHookBackend('x11');- await assert.rejects(- backend.start(() => {}),- /XRecord extension not available/,- );- assert.equal(x11.instances[0].stopped, true);- });-- test('the session monitor never loads the portals module when portals are turned off', () => {- const original = Object.getOwnPropertyDescriptor(process, 'platform');- const previousEnv = process.env.FLUXER_DISABLE_LINUX_PORTALS;- let constructed = 0;- const portals = {- GlobalShortcutsPortal: null,- SessionStateMonitor: class {- constructor() {- constructed += 1;- }- close() {}- },- loadError: null,- };- Object.defineProperty(process, 'platform', {...original, value: 'linux'});- try {- process.env.FLUXER_DISABLE_LINUX_PORTALS = '1';- const off = loadNativeWith({'@fluxer/linux-portals': portals});- assert.equal(- off.createLinuxSessionStateMonitor(() => {}),- null,- );- assert.equal(constructed, 0);- delete process.env.FLUXER_DISABLE_LINUX_PORTALS;- const on = loadNativeWith({'@fluxer/linux-portals': portals});- assert.notEqual(- on.createLinuxSessionStateMonitor(() => {}),- null,- );- assert.equal(constructed, 1);- } finally {- Object.defineProperty(process, 'platform', original);- if (previousEnv === undefined) delete process.env.FLUXER_DISABLE_LINUX_PORTALS;- else process.env.FLUXER_DISABLE_LINUX_PORTALS = previousEnv;- }- });-});--describe('LegacyGlobalKeyHookAdapter', () => {- function legacyHarness({session = 'x11', portalConsent = 'unset'} = {}) {- const harness = createEngine({session, portalConsent, settings: createSettings({migrated: true})});- const adapter = new legacy.LegacyGlobalKeyHookAdapter();- harness.engine.addConsumer(adapter);- harness.legacySent = [];- adapter.attach(7, (channel, payload) => harness.legacySent.push({channel, payload}));- harness.adapter = adapter;- harness.triggered = () =>- harness.legacySent- .filter((entry) => entry.channel === 'global-keybind-triggered')- .map((entry) => `${entry.payload.type}:${entry.payload.id}`);- return harness;- }-- test('legacy registrations translate to bindings', () => {- assert.deepEqual(- legacy.legacyRegistrationToBinding({- id: 'key:voice_toggle_mute:m',- keycode: 50,- keyName: 'M',- physicalKeyName: 'M',- ctrl: true,- }),- {- sourceId: 'key:voice_toggle_mute:m',- action: 'key:voice_toggle_mute:m',- trigger: {kind: 'key', layoutKey: 'M', code: 'KeyM'},- modifiers: {ctrl: true, alt: false, shift: false, meta: false},- },- );- assert.deepEqual(legacy.legacyRegistrationToBinding({id: 'mouse:voice_push_to_talk:3', mouseButton: 3}).trigger, {- kind: 'mouse',- button: 3,- });- assert.equal(legacy.legacyRegistrationToBinding({id: 'key:x', keycode: 50}), null);- });-- test('started legacy senders get raw events and triggered ids without the keysym collision', async () => {- const harness = legacyHarness();- harness.adapter.register(- 7,- legacy.legacyRegistrationToBinding({id: 'key:voice_toggle_mute:m', keyName: 'M', ctrl: true}),- );- harness.adapter.acquire(7);- await harness.engine.refreshHooks();- const hook = harness.activeHook();- hook.onEvent({...keyEvent('keydown', 'Digit2', 11, {ctrl: true}, {keycode: 0x32, keyName: '2'}), key: '2'});- hook.onEvent({...keyEvent('keydown', 'KeyM', 58, {ctrl: true}, {keycode: 0x6d, keyName: 'M'}), key: 'M'});- hook.onEvent({...keyEvent('keyup', 'KeyM', 58, {}, {keycode: 0x6d, keyName: 'M'}), key: 'M'});- assert.deepEqual(harness.triggered(), ['keydown:key:voice_toggle_mute:m', 'keyup:key:voice_toggle_mute:m']);- const raw = harness.legacySent.filter((entry) => entry.channel === 'global-key-event');- assert.equal(raw.length, 3);- assert.deepEqual(raw[1].payload, {- type: 'keydown',- keycode: 0x6d,- keyName: 'M',- ctrlKey: true,- altKey: false,- shiftKey: false,- metaKey: false,- backend: 'native',- });- harness.adapter.release(7);- await harness.engine.refreshHooks();- assert.deepEqual(harness.stopped, ['x11']);- });-- function registerLegacy(harness) {- legacyHandlers.clear();- const sender = {- id: 9,- isDestroyed: () => false,- send: (channel, payload) => harness.legacySent.push({channel, payload}),- };- legacy.registerLegacyGlobalKeyHookHandlers(harness.engine, harness.adapter, {- platform: 'linux',- sandboxed: false,- username: 'u',- hasInputMonitoringAccess: () => true,- watchSender: () => {},- });- return (channel, ...args) => legacyHandlers.get(channel)({sender}, ...args);- }-- test('an old renderer alone never opens the portal', async () => {- const harness = legacyHarness({session: 'wayland', portalConsent: 'granted'});- harness.engine.start();- await settle();- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- await invoke('global-key-hook-register', {id: 'key:voice_toggle_mute::F9:F9', keyName: 'F9'});- assert.equal(harness.portals.length, 0);- assert.deepEqual(harness.started, []);- });-- test('the portal closes when the last new renderer goes away and reopens for the next one', async () => {- const harness = legacyHarness({session: 'wayland', portalConsent: 'granted'});- harness.attach(1);- await settle();- assert.equal(harness.engine.getStatus().linux.portal.state, 'bound');- harness.portals[0].onEvent({type: 'activated', id: 'voice_push_to_talk'});- harness.engine.detachClient(1);- await settle();- assert.equal(harness.portals[0].closed, true);- assert.equal(harness.engine.getStatus().linux.portal.state, 'unknown');- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- assert.equal(harness.portals.length, 1);- harness.attach(2);- await settle();- assert.equal(harness.portals.length, 2);- assert.equal(harness.engine.getStatus().linux.portal.state, 'bound');- });-- test('an old renderer alone on Wayland is told it has access so it never offers a grant', async () => {- const harness = legacyHarness({session: 'wayland', portalConsent: 'granted'});- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- assert.equal((await invoke('linux-evdev-status')).hasAccess, true);- assert.equal(harness.engine.getStatus().linux.portal.state, 'unknown');- });-- test('a portal bound for a new renderer keeps an old renderer quiet without routing to it', async () => {- const harness = legacyHarness({session: 'wayland', portalConsent: 'granted'});- harness.attach(1);- await settle();- assert.equal(harness.engine.getStatus().linux.portal.state, 'bound');- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- assert.equal((await invoke('linux-evdev-status')).hasAccess, true);- harness.portals[0].onEvent({type: 'activated', id: 'voice_toggle_mute'});- assert.deepEqual(harness.triggered(), []);- });-- function unmigratedLegacyHarness(options) {- const harness = createEngine(options);- harness.legacySent = [];- harness.adapter = new legacy.LegacyGlobalKeyHookAdapter();- harness.engine.addConsumer(harness.adapter);- return harness;- }-- test('a legacy start alone migrates readable keyboards to direct input on Wayland', async () => {- const harness = unmigratedLegacyHarness({session: 'wayland', keyboardReadable: true, portalConsent: 'granted'});- harness.engine.start();- await settle();- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), true);- assert.deepEqual(harness.started, ['evdev']);- assert.equal(harness.settings.state.migrated, true);- assert.equal(harness.settings.state.directInputEnabled, true);- assert.equal(harness.engine.getStatus().backend, 'evdev');- await invoke('global-key-hook-register', {id: 'key:voice_toggle_mute::F9:F9', keyName: 'F9'});- assert.deepEqual(harness.started, ['evdev']);- assert.equal((await invoke('linux-evdev-status')).hasAccess, true);- });-- test('legacy calls leave the migration pending while no keyboard is readable', async () => {- const harness = unmigratedLegacyHarness({session: 'wayland', keyboardReadable: false});- harness.engine.start();- await settle();- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- await invoke('global-key-hook-register', {id: 'key:voice_toggle_mute::F9:F9', keyName: 'F9'});- assert.equal(harness.settings.state.migrated, false);- assert.equal(harness.settings.state.directInputEnabled, false);- harness.keyboardReadable = true;- assert.equal(await invoke('global-key-hook-start'), true);- assert.equal(harness.settings.state.migrated, true);- assert.deepEqual(harness.started, ['evdev']);- });-- test('a migrated user who turned direct input off stays on the portal for legacy starts', async () => {- const harness = unmigratedLegacyHarness({- session: 'wayland',- keyboardReadable: true,- settings: createSettings({migrated: true}),- });- const invoke = registerLegacy(harness);- assert.equal(await invoke('global-key-hook-start'), false);- assert.equal(harness.settings.state.directInputEnabled, false);- assert.deepEqual(harness.started, []);- });-- test('a legacy registration also runs the migration', async () => {- const harness = unmigratedLegacyHarness({session: 'x11', keyboardReadable: true});- const invoke = registerLegacy(harness);- await invoke('global-key-hook-register', {id: 'mouse:voice_push_to_talk::4', mouseButton: 4});- assert.equal(harness.settings.state.migrated, true);- assert.equal(harness.settings.state.directInputEnabled, true);- assert.equal(harness.engine.getStatus().backend, 'evdev');- });-- test('legacy evdev status never offers a prompt', () => {- assert.deepEqual(legacy.buildLegacyLinuxEvdevStatus({platform: 'linux', sandboxed: true, username: 'u'}), {- supported: true,- hasAccess: true,- canPrompt: false,- sandboxed: true,- username: 'u',- totalEventDevices: 0,- readableEventDevices: 0,- inInputGroup: false,- });- assert.equal(- legacy.buildLegacyLinuxEvdevStatus({platform: 'darwin', sandboxed: false, username: null}).hasAccess,- true,- );- });-});diff --git a/fluxer_desktop/src/main/LegacyAppOrigin.test.mjs b/fluxer_desktop/src/main/LegacyAppOrigin.test.mjsdeleted file mode 100644index a123dbfd1..000000000--- a/fluxer_desktop/src/main/LegacyAppOrigin.test.mjs+++ /dev/null@@ -1,123 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import {createRequire} from 'node:module';-import os from 'node:os';-import path from 'node:path';-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');--function transform(relativePath) {- const sourcePath = fileURLToPath(new URL(relativePath, import.meta.url));- const code = esbuild.transformSync(fs.readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',- }).code;- return {sourcePath, code};-}--const constantsSource = transform('../common/Constants.ts');-const localAppRouteContractSource = transform('../../../packages/desktop_ipc/src/LocalAppRouteContract.ts');-const desktopConfigSource = transform('../common/DesktopConfig.ts');-const plainRecordSource = transform('../common/PlainRecord.ts');-const recordGuardsSource = transform('../../../packages/record_utils/src/RecordGuards.ts');-const globalShortcutActionsSource = transform('../common/GlobalShortcutActions.ts');--const silentLog = {debug() {}, info() {}, warn() {}, error() {}};--function runModule({sourcePath, code}, requireStub) {- const module = {exports: {}};- const context = vm.createContext({- require: requireStub,- module,- exports: module.exports,- process,- console,- URL,- JSON,- });- vm.runInContext(code, context, {filename: sourcePath});- return module.exports;-}--function loadDesktop({channel = 'stable', settings} = {}) {- const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-legacy-app-origin-test-'));- const settingsPath = path.join(userDataPath, 'settings.json');- if (settings !== undefined) {- fs.writeFileSync(settingsPath, JSON.stringify(settings), 'utf-8');- }- const localAppRouteContract = runModule(localAppRouteContractSource, (specifier) => {- throw new Error(`Unexpected import: ${specifier}`);- });- const constants = runModule(constantsSource, (specifier) => {- if (specifier === '@electron/common/BuildChannel') return {BUILD_CHANNEL: channel};- if (specifier === '@fluxer/desktop_ipc/src/LocalAppRouteContract') return localAppRouteContract;- throw new Error(`Unexpected import: ${specifier}`);- });- const globalShortcutActions = runModule(globalShortcutActionsSource, (specifier) => {- throw new Error(`Unexpected import: ${specifier}`);- });- const plainRecord = runModule(plainRecordSource, (specifier) => {- throw new Error(`Unexpected import: ${specifier}`);- });- const recordGuards = runModule(recordGuardsSource, (specifier) => {- throw new Error(`Unexpected import: ${specifier}`);- });- const desktopConfig = runModule(desktopConfigSource, (specifier) => {- if (specifier === '@electron/common/PlainRecord') return plainRecord;- if (specifier === '@fluxer/record_utils/src/RecordGuards') return recordGuards;- if (specifier === 'node:fs') return fs;- if (specifier === '@electron/common/GlobalShortcutActions') return globalShortcutActions;- if (specifier === 'node:path') return path;- if (specifier === '@electron/common/BuildChannel') return {BUILD_CHANNEL: channel};- if (specifier === '@electron/common/Constants') return constants;- if (specifier === '@fluxer/instance_bootstrap/src/EndpointNormalization') {- return {InstanceEndpointKind: {API: 'api'}, normalizeInstanceEndpoint: () => null};- }- if (specifier === 'electron-log') return silentLog;- throw new Error(`Unexpected import: ${specifier}`);- });- desktopConfig.loadDesktopConfig(userDataPath);- return desktopConfig;-}--describe('DesktopConfig legacy app origin', () => {- test('harvests the legacy web app origin when no app origin is stored', () => {- assert.equal(loadDesktop().getLegacyAppOrigin(), 'https://web.fluxer.app');- assert.equal(loadDesktop({channel: 'canary'}).getLegacyAppOrigin(), 'https://web.canary.fluxer.app');- });-- test('harvests the migrated origin an older build stored', () => {- const stable = loadDesktop({settings: {app_origin: 'https://fluxer.com'}});- const canary = loadDesktop({channel: 'canary', settings: {app_origin: 'https://canary.fluxer.com'}});-- assert.equal(stable.getLegacyAppOrigin(), 'https://fluxer.com');- assert.equal(canary.getLegacyAppOrigin(), 'https://canary.fluxer.com');- });-- test('harvests the legacy web app origin for a stored legacy origin', () => {- const desktopConfig = loadDesktop({settings: {app_origin: 'https://web.fluxer.app'}});-- assert.equal(desktopConfig.getLegacyAppOrigin(), 'https://web.fluxer.app');- });-- test('drops stored origins outside the channel allowlist', () => {- for (const appOrigin of [- 'https://canary.fluxer.com',- 'https://fluxer.com/',- 'https://evil.example',- 'http://fluxer.com',- 42,- ]) {- const desktopConfig = loadDesktop({settings: {app_origin: appOrigin}});- assert.equal(desktopConfig.getLegacyAppOrigin(), 'https://web.fluxer.app');- }- });-});diff --git a/fluxer_desktop/src/main/LegacyHarvestIpc.test.mjs b/fluxer_desktop/src/main/LegacyHarvestIpc.test.mjsdeleted file mode 100644index dc1dc5e71..000000000--- a/fluxer_desktop/src/main/LegacyHarvestIpc.test.mjs+++ /dev/null@@ -1,278 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {mkdtempSync} 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 {installDesktopAppStorageStub, installElectronStub, installWindowStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-installWindowStub(null);-installDesktopAppStorageStub(null);--const {- DESKTOP_LEGACY_HARVEST_BLOB_REF_KEY,- DESKTOP_LEGACY_HARVEST_CHANNELS,- DESKTOP_LEGACY_HARVEST_VALUE_ENCODING_KEY,- DESKTOP_LEGACY_REPLANT_MARKER_KEY,-} = await import('../../../packages/desktop_ipc/src/LegacyHarvestContract.ts');-const {- DESKTOP_LEGACY_AUTHORITY_MARKER_KEY,- DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE,- DesktopLegacyImportPhase,- desktopLegacyImportMarker,-} = await import('../../../packages/desktop_ipc/src/StorageContract.ts');-const {discardStagedHarvest, readStagedHarvest, readStagedHarvestLocalStorageSync, writeStagedHarvest} = await import(- './LegacyOriginHarvestStore.ts'-);-const {cleanupLegacyHarvestHandlers, registerLegacyHarvestHandlers} = await import('./LegacyHarvestIpc.ts');-const {getLegacyAppOrigin} = await import('../common/DesktopConfig.ts');-const OFFICIAL_ORIGIN = getLegacyAppOrigin();--const temporaryRoots = [];--function harvestFixture() {- return {- version: 1,- origin: OFFICIAL_ORIGIN,- capturedAt: 1_700_000_000_000,- localStorage: {token: 'live.session.token', userId: '100000000000000002', theme: 'dark'},- stores: [- {- database: 'FluxerAccounts',- version: 2,- store: 'accounts',- records: [{key: null, value: {userId: '100000000000000002', token: 'tok'}}],- },- ],- serviceWorkersUnregistered: 0,- cachesDeleted: 0,- truncated: [],- };-}--function nestedMapValue(levels, {innermostEmpty = false} = {}) {- let value = innermostEmpty ? {[DESKTOP_LEGACY_HARVEST_VALUE_ENCODING_KEY]: [1, 'map', []]} : 0;- for (let index = 0; index < levels; index += 1) {- value = {[DESKTOP_LEGACY_HARVEST_VALUE_ENCODING_KEY]: [1, 'map', [['k', value]]]};- }- return value;-}--function createStoreStub() {- const markers = new Map();- return {- markers,- getMarker: (key) => Promise.resolve(markers.get(key) ?? null),- setMarker: (key, value) => {- markers.set(key, value);- return Promise.resolve();- },- };-}--function createRefusingStoreStub() {- return {- getMarker: () => Promise.resolve(null),- setMarker: () => Promise.reject(new Error('the desktop app store is unavailable')),- };-}--function createUserData(registered) {- const userData = mkdtempSync(path.join(os.tmpdir(), 'legacy-harvest-ipc-'));- temporaryRoots.push(userData);- installElectronStub({- app: {isReady: () => true, getPath: () => userData, getAppPath: () => userData},- ipcMain: {- handle: (channel, listener) => registered.set(channel, listener),- on: (channel, listener) => registered.set(channel, listener),- removeHandler: (channel) => registered.delete(channel),- removeAllListeners: (channel) => registered.delete(channel),- },- });- return userData;-}--function senderEvent() {- const frame = {detached: false, parent: null, url: 'fluxer-app://app/'};- frame.top = frame;- const sender = {isDestroyed: () => false, isLoadingMainFrame: () => false, mainFrame: frame};- frame.owner = sender;- installWindowStub({webContents: sender});- return {sender, senderFrame: frame};-}--after(async () => {- cleanupLegacyHarvestHandlers();- for (const root of temporaryRoots) {- await rm(root, {recursive: true, force: true});- }-});--describe('marking the harvest replanted', () => {- test('writes the filesystem witness even when the app store cannot take the marker', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- installDesktopAppStorageStub(createRefusingStoreStub());- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();-- await assert.rejects(() => handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document));-- assert.equal(readStagedHarvestLocalStorageSync(), null);- cleanupLegacyHarvestHandlers();- });-- test('writes the filesystem witness when there is no app store at all', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- installDesktopAppStorageStub(null);- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();-- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document);-- assert.equal(readStagedHarvestLocalStorageSync(), null);- cleanupLegacyHarvestHandlers();- });-- test('records both witnesses when the store is healthy', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- const store = createStoreStub();- installDesktopAppStorageStub(store);- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();-- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document);-- assert.equal(readStagedHarvestLocalStorageSync(), null);- assert.ok(store.markers.get(DESKTOP_LEGACY_REPLANT_MARKER_KEY));- cleanupLegacyHarvestHandlers();- });-});--describe('the preboot localStorage read', () => {- test('serves the harvested keys until the replant is recorded', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- installDesktopAppStorageStub(null);-- assert.equal(readStagedHarvestLocalStorageSync().theme, 'dark');-- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document);- assert.equal(readStagedHarvestLocalStorageSync(), null);- cleanupLegacyHarvestHandlers();- });-});--describe('serving the staged harvest for the replant', () => {- test('serves the harvest until the replant is recorded, then never again', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- installDesktopAppStorageStub(createStoreStub());- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();- const read = handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.read);-- assert.equal((await read(document)).stores[0].records.length, 1);- assert.equal((await read(document)).stores[0].records.length, 1);-- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document);-- assert.equal(await read(document), null);- assert.notEqual(await readStagedHarvest(), null);- cleanupLegacyHarvestHandlers();- });-});--describe('discarding the staged harvest', () => {- test('reports the removal once and does nothing on later launches', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());-- assert.equal(await discardStagedHarvest(), true);- assert.equal(await readStagedHarvest(), null);- assert.equal(await discardStagedHarvest(), false);- assert.equal(readStagedHarvestLocalStorageSync(), null);- });-- test('keeps the harvest until authority is committed and the import is done', async () => {- const handlers = new Map();- createUserData(handlers);- await writeStagedHarvest(harvestFixture(), new Map());- const store = createStoreStub();- installDesktopAppStorageStub(store);- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.markReplanted)(document);-- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.discard)(document);- assert.notEqual(await readStagedHarvest(), null);-- store.markers.set(DESKTOP_LEGACY_AUTHORITY_MARKER_KEY, DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE);- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.discard)(document);- assert.notEqual(await readStagedHarvest(), null);-- const done = desktopLegacyImportMarker(DesktopLegacyImportPhase.DONE, 1);- store.markers.set(done.key, done.value);- await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.discard)(document);- assert.equal(await readStagedHarvest(), null);- cleanupLegacyHarvestHandlers();- });-});--describe('serving a deeply nested harvest to the renderer', () => {- test('a Map chain the encoder accepts survives the read', async () => {- const handlers = new Map();- createUserData(handlers);- const harvest = harvestFixture();- const records = [{key: null, value: nestedMapValue(64, {innermostEmpty: true})}];- await writeStagedHarvest({...harvest, stores: [{...harvest.stores[0], records}]}, new Map());- installDesktopAppStorageStub(null);- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();-- const served = await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.read)(document);-- assert.equal(served.stores[0].records.length, 1);- cleanupLegacyHarvestHandlers();- });-});--describe('serving a harvest whose blob reference is damaged', () => {- test('drops the field instead of failing the whole read', async () => {- const handlers = new Map();- createUserData(handlers);- const harvest = harvestFixture();- const records = [{key: null, value: {avatar: {[DESKTOP_LEGACY_HARVEST_BLOB_REF_KEY]: {blobId: '../escape'}}}}];- await writeStagedHarvest({...harvest, stores: [{...harvest.stores[0], records}]}, new Map());- installDesktopAppStorageStub(null);- const document = senderEvent();- cleanupLegacyHarvestHandlers();- registerLegacyHarvestHandlers();-- const served = await handlers.get(DESKTOP_LEGACY_HARVEST_CHANNELS.read)(document);-- assert.equal(served.stores[0].records[0].value.avatar, null);- assert.equal(served.localStorage.theme, 'dark');- cleanupLegacyHarvestHandlers();- });-});diff --git a/fluxer_desktop/src/main/LegacyHarvestOfficialInstance.test.mjs b/fluxer_desktop/src/main/LegacyHarvestOfficialInstance.test.mjsdeleted file mode 100644index 14699165c..000000000--- a/fluxer_desktop/src/main/LegacyHarvestOfficialInstance.test.mjs+++ /dev/null@@ -1,174 +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 {rekeyHarvestToOfficialInstance} = await import('./LegacyHarvestOfficialInstance.ts');--const USER_ID = '100000000000000002';-const OTHER_USER_ID = '100000000000000003';--function harvestFrom(origin, {localStorage = {}, stores = []} = {}) {- return {- version: 1,- origin,- capturedAt: 1_700_000_000_000,- localStorage,- stores,- mediaDevices: [],- serviceWorkersUnregistered: 0,- cachesDeleted: 0,- truncated: [],- };-}--function legacyAccount(origin, userId) {- return {- userId,- token: `token-${userId}`,- localStorageData: {},- lastActive: 1,- instance: {- apiEndpoint: `${origin}/api`,- webAppEndpoint: origin,- gatewayEndpoint: 'wss://gateway.fluxer.app',- mediaEndpoint: 'https://fluxerusercontent.com',- },- };-}--function accountStore(records) {- return {database: 'FluxerAccounts', version: 2, store: 'accounts', records};-}--function appStorageRow(scope, key, value) {- return {key: null, value: {id: JSON.stringify([scope, key]), scope, key, value, updatedAt: {wall: 1, seq: 1}}};-}--describe('a harvest taken from the migrated official domain', () => {- for (const [migrated, official] of [- ['https://fluxer.com', 'https://web.fluxer.app'],- ['https://canary.fluxer.com', 'https://web.canary.fluxer.app'],- ]) {- test(`an old client account stored on ${migrated} is staged on the official instance`, () => {- const harvest = harvestFrom(migrated, {- localStorage: {token: 'live', userId: USER_ID},- stores: [- accountStore([- {key: null, value: legacyAccount(migrated, USER_ID)},- {key: null, value: legacyAccount(migrated, OTHER_USER_ID)},- ]),- ],- });-- const staged = rekeyHarvestToOfficialInstance(harvest);-- assert.equal(staged.origin, migrated);- assert.deepEqual(staged.localStorage, {token: 'live', userId: USER_ID});- for (const record of staged.stores[0].records) {- assert.equal(record.value.instance.apiEndpoint, `${official}/api`);- assert.equal(record.value.instance.webAppEndpoint, official);- assert.equal(record.value.instance.gatewayEndpoint, 'wss://gateway.fluxer.app');- assert.equal(record.value.instance.mediaEndpoint, 'https://fluxerusercontent.com');- }- assert.equal(staged.stores[0].records[0].value.token, `token-${USER_ID}`);- assert.equal(harvest.stores[0].records[0].value.instance.apiEndpoint, `${migrated}/api`);- });-- test(`account-scoped state written on ${migrated} follows the account to the official instance`, () => {- const migratedKey = `${migrated}/api::${USER_ID}`;- const officialKey = `${official}/api::${USER_ID}`;- const harvest = harvestFrom(migrated, {- localStorage: {- 'fluxer:auth:active-account-key': migratedKey,- [`fluxer:app-storage-mirror:${migratedKey}::Drafts`]: '{"drafts":{"1":"hello"}}',- theme: 'dark',- },- stores: [- accountStore([{key: null, value: {...legacyAccount(migrated, USER_ID), storageKey: migratedKey}}]),- {- database: 'fluxer-app-storage',- version: 1,- store: 'entries',- records: [- appStorageRow(migratedKey, 'Drafts', '{"drafts":{"1":"hello"}}'),- appStorageRow('global', 'fluxer:auth:active-account-key', migratedKey),- appStorageRow('global', 'BackgroundAccountPresence', JSON.stringify({[migratedKey]: {status: 'idle'}})),- appStorageRow('global', 'Theme', '{"theme":"dark"}'),- ],- },- ],- });-- const staged = rekeyHarvestToOfficialInstance(harvest);-- assert.deepEqual(staged.localStorage, {- 'fluxer:auth:active-account-key': officialKey,- [`fluxer:app-storage-mirror:${officialKey}::Drafts`]: '{"drafts":{"1":"hello"}}',- theme: 'dark',- });- const [accounts, appStorage] = staged.stores;- assert.equal(accounts.records[0].value.storageKey, officialKey);- assert.equal(accounts.records[0].value.instance.apiEndpoint, `${official}/api`);- assert.deepEqual(- appStorage.records.map((record) => record.value),- [- appStorageRow(officialKey, 'Drafts', '{"drafts":{"1":"hello"}}').value,- appStorageRow('global', 'fluxer:auth:active-account-key', officialKey).value,- appStorageRow('global', 'BackgroundAccountPresence', JSON.stringify({[officialKey]: {status: 'idle'}})).value,- appStorageRow('global', 'Theme', '{"theme":"dark"}').value,- ],- );- assert.equal(JSON.stringify(staged).includes(`${migrated}/api::`), false);- });- }-- test('values that are not plain data survive the rekey untouched', () => {- const savedAt = new Date(5);- const bytes = new Uint8Array([1, 2, 3]);- const harvest = harvestFrom('https://canary.fluxer.com', {- stores: [- {- database: 'FluxerCustomSounds',- version: 2,- store: 'customSounds',- records: [{key: 'message', value: {soundType: 'message', savedAt, bytes, blob: {__blobRef: {blobId: 'a'}}}}],- },- ],- });-- const [record] = rekeyHarvestToOfficialInstance(harvest).stores[0].records;-- assert.equal(record.key, 'message');- assert.equal(record.value.savedAt, savedAt);- assert.equal(record.value.bytes, bytes);- assert.deepEqual(record.value.blob, {__blobRef: {blobId: 'a'}});- });-- test('an account on another instance keeps its own identity', () => {- const selfHosted = legacyAccount('https://chat.example.test', OTHER_USER_ID);- const harvest = harvestFrom('https://canary.fluxer.com', {- localStorage: {[`fluxer:app-storage-mirror:https://chat.example.test/api::${OTHER_USER_ID}::Drafts`]: '{}'},- stores: [accountStore([{key: null, value: selfHosted}])],- });-- const staged = rekeyHarvestToOfficialInstance(harvest);-- assert.deepEqual(staged.localStorage, harvest.localStorage);- assert.deepEqual(staged.stores[0].records[0].value, selfHosted);- });-});--describe('a harvest taken from the legacy official web origin', () => {- for (const origin of ['https://web.fluxer.app', 'https://web.canary.fluxer.app']) {- test(`${origin} already is the official instance and is staged as harvested`, () => {- const harvest = harvestFrom(origin, {- localStorage: {'fluxer:auth:active-account-key': `${origin}/api::${USER_ID}`},- stores: [accountStore([{key: null, value: legacyAccount(origin, USER_ID)}])],- });-- assert.equal(rekeyHarvestToOfficialInstance(harvest), harvest);- });- }-});diff --git a/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.test.mjs b/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.test.mjsdeleted file mode 100644index f89ad636a..000000000--- a/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.test.mjs+++ /dev/null@@ -1,360 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {loadTsModule} from './fixtures/TsModuleLoader.mjs';--const {LinuxPortalShortcutsManager, PORTAL_RECOVERY_BACKOFF_MS, PORTAL_TOGGLE_REARM_MS} = loadTsModule(- '@electron/main/LinuxGlobalShortcutsPortal',-);-const {GLOBAL_SHORTCUT_ACTIONS} = loadTsModule('@electron/common/GlobalShortcutActions');--function listedAll(trigger = 'F13') {- return GLOBAL_SHORTCUT_ACTIONS.map((id) => ({id, description: id, triggerDescription: trigger}));-}--class FakePortal {- constructor(harness, onEvent) {- this.harness = harness;- this.onEvent = onEvent;- this.closed = false;- this.bindCalls = [];- this.configureCalls = [];- }-- async open() {- this.harness.openCalls += 1;- const next = this.harness.openResults.shift() ?? this.harness.defaultOpen;- if (next instanceof Error) throw next;- if (typeof next === 'function') return next(this);- return next;- }-- async bind(shortcuts, parentWindow) {- this.bindCalls.push({shortcuts, parentWindow});- this.harness.bindCalls.push({shortcuts, parentWindow});- const next = this.harness.bindResults.shift() ?? {outcome: 'bound', shortcuts: listedAll()};- if (next instanceof Error) throw next;- return next;- }-- async configure(parentWindow) {- this.configureCalls.push(parentWindow);- this.harness.configureCalls.push(parentWindow);- const next = this.harness.configureResults.shift();- if (next instanceof Error) throw next;- }-- close() {- this.closed = true;- }-- emit(event) {- this.onEvent(event);- }-}--function createHarness({- consent = 'unset',- desktop = 'gnome',- plasma5 = false,- version = 2,- listed = [],- appIdSource = 'registered',-} = {}) {- const harness = {- consent,- openCalls: 0,- openResults: [],- bindResults: [],- bindCalls: [],- configureCalls: [],- configureResults: [],- defaultOpen: {version, appIdSource, uniqueName: ':1.42', listed},- portals: [],- shortcuts: [],- statusChanges: 0,- timers: [],- clock: 0,- };- harness.manager = new LinuxPortalShortcutsManager({- createPortal: (onEvent) => {- const portal = new FakePortal(harness, onEvent);- harness.portals.push(portal);- return portal;- },- desktop,- plasma5,- portalAppId: 'app.fluxer.FluxerDesktop',- getConsent: () => harness.consent,- setConsent: (next) => {- harness.consent = next;- },- getDefinitions: () => GLOBAL_SHORTCUT_ACTIONS.map((id) => ({id, description: `Label ${id}`})),- getParentWindow: () => 'x11:2a',- onShortcut: (action, phase) => harness.shortcuts.push(`${phase}:${action}`),- onStatusChanged: () => {- harness.statusChanges += 1;- },- schedule: (callback, delayMs) => {- const timer = {callback, delayMs, cancelled: false, cancel: () => (timer.cancelled = true)};- harness.timers.push(timer);- return timer;- },- now: () => harness.clock,- log: () => {},- });- harness.latestPortal = () => harness.portals[harness.portals.length - 1];- harness.runTimer = async () => {- const timer = harness.timers.find((entry) => !entry.cancelled && !entry.ran);- assert.ok(timer, 'expected a pending timer');- timer.ran = true;- timer.callback();- await harness.manager.probe();- await flush();- return timer.delayMs;- };- return harness;-}--async function flush() {- for (let index = 0; index < 10; index += 1) await Promise.resolve();-}--describe('LinuxPortalShortcutsManager events', () => {- test('activations are deduplicated and unknown ids are ignored', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- portal.emit({type: 'activated', id: 'not_an_action'});- portal.emit({type: 'deactivated', id: 'voice_toggle_mute'});- portal.emit({type: 'deactivated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.shortcuts, ['press:voice_push_to_talk', 'release:voice_push_to_talk']);- });-- test('shortcuts-changed with empty triggers keeps the bound state', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- harness.latestPortal().emit({type: 'shortcuts-changed', shortcuts: listedAll('')});- const status = harness.manager.getStatus();- assert.equal(status.state, 'bound');- assert.ok(status.shortcuts.every((entry) => entry.triggerDescription === null));- });-- test('session loss releases held shortcuts and reopens with backoff while still reporting bound', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const first = harness.latestPortal();- first.emit({type: 'activated', id: 'voice_push_to_talk'});- const changesBefore = harness.statusChanges;- first.emit({type: 'session-lost', reason: 'portal-restarted'});- assert.deepEqual(harness.shortcuts, ['press:voice_push_to_talk', 'release:voice_push_to_talk']);- assert.equal(first.closed, true);- assert.ok(harness.statusChanges > changesBefore);- let status = harness.manager.getStatus();- assert.equal(status.state, 'bound');- assert.equal(status.recovering, true);- assert.equal(status.canConfigure, false);- await harness.manager.configure();- assert.deepEqual(harness.configureCalls, []);- first.emit({type: 'activated', id: 'voice_toggle_mute'});- assert.equal(harness.shortcuts.length, 2);- harness.openResults.push(new Error('error:bus'), new Error('error:timeout'));- assert.equal(await harness.runTimer(), PORTAL_RECOVERY_BACKOFF_MS[0]);- assert.equal(harness.manager.getState(), 'bound');- assert.equal(harness.manager.getStatus().recovering, true);- assert.equal(await harness.runTimer(), PORTAL_RECOVERY_BACKOFF_MS[1]);- assert.equal(await harness.runTimer(), PORTAL_RECOVERY_BACKOFF_MS[2]);- status = harness.manager.getStatus();- assert.equal(status.state, 'bound');- assert.equal(status.recovering, false);- assert.equal(status.canConfigure, true);- assert.equal(harness.openCalls, 4);- });-- test('a reopen that lists new triggers pushes a status even when the state stays bound', async () => {- const harness = createHarness({consent: 'granted', version: 1, desktop: 'kde', listed: listedAll()});- await harness.manager.activate();- harness.latestPortal().emit({type: 'session-lost', reason: 'portal-restarted'});- harness.defaultOpen = {...harness.defaultOpen, listed: listedAll('F14')};- const changesBefore = harness.statusChanges;- await harness.runTimer();- assert.equal(harness.bindCalls.length, 0);- assert.ok(harness.statusChanges > changesBefore);- const status = harness.manager.getStatus();- assert.equal(status.recovering, false);- assert.ok(status.shortcuts.every((entry) => entry.triggerDescription === 'F14'));- });-- test('a recovery that runs out of backoff steps settles into an error and keeps retrying', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- harness.latestPortal().emit({type: 'session-lost', reason: 'portal-restarted'});- for (const delay of PORTAL_RECOVERY_BACKOFF_MS) {- assert.equal(harness.manager.getStatus().recovering, true);- harness.openResults.push(new Error('error:bus'));- assert.equal(await harness.runTimer(), delay);- }- const status = harness.manager.getStatus();- assert.equal(status.state, 'error');- assert.equal(status.error, 'portal-unavailable');- assert.equal(status.recovering, false);- assert.equal(await harness.runTimer(), 30000);- assert.equal(harness.manager.getState(), 'bound');- });-- test('the backoff caps at thirty seconds', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- harness.latestPortal().emit({type: 'session-lost', reason: 'bus-error'});- const delays = [];- for (let index = 0; index < 7; index += 1) {- harness.openResults.push(new Error('down'));- delays.push(await harness.runTimer());- }- assert.deepEqual(delays, [1000, 2000, 5000, 10000, 30000, 30000, 30000]);- });-- test('a closed session reopens once, then a second close within a minute is an error', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- harness.latestPortal().emit({type: 'session-lost', reason: 'closed'});- await harness.runTimer();- assert.equal(harness.manager.getState(), 'bound');- harness.clock += 1000;- harness.latestPortal().emit({type: 'session-lost', reason: 'closed'});- assert.equal(harness.manager.getState(), 'error');- assert.equal(harness.manager.getStatus().error, 'session-closed');- assert.equal(harness.timers.filter((timer) => !timer.cancelled && !timer.ran).length, 0);- });-- test('deactivate releases held shortcuts, cancels recovery and ignores late events', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_mute'});- harness.manager.deactivate();- assert.deepEqual(harness.shortcuts, ['press:voice_push_to_mute', 'release:voice_push_to_mute']);- assert.equal(portal.closed, true);- assert.equal(harness.manager.getState(), 'unknown');- portal.emit({type: 'activated', id: 'voice_push_to_mute'});- assert.equal(harness.shortcuts.length, 2);- });-- test('a deactivate that lands before the queued startup never opens a session', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- const activation = harness.manager.activate();- harness.manager.deactivate();- await activation;- await flush();- assert.equal(harness.openCalls, 0);- assert.equal(harness.bindCalls.length, 0);- assert.equal(harness.manager.getState(), 'unknown');- });-- test('check again is only offered where it can do something', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- assert.equal(harness.manager.getStatus().canRecheck, false);- harness.manager.deactivate();- assert.equal(harness.manager.getStatus().canRecheck, false);- });-- test('configure only runs on version 2 portals', async () => {- const v2 = createHarness({consent: 'granted', version: 2, listed: listedAll()});- await v2.manager.activate();- await v2.manager.configure();- assert.deepEqual(v2.configureCalls, ['x11:2a']);- const v1 = createHarness({consent: 'granted', version: 1, desktop: 'kde', listed: listedAll()});- await v1.manager.activate();- await v1.manager.configure();- assert.deepEqual(v1.configureCalls, []);- });-});--describe('LinuxPortalShortcutsManager configure and triggers', () => {- test('a trigger change on a held shortcut releases it', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- portal.emit({type: 'activated', id: 'voice_toggle_mute'});- portal.emit({- type: 'shortcuts-changed',- shortcuts: [{id: 'voice_push_to_talk', description: null, triggerDescription: 'F14'}],- });- assert.deepEqual(harness.shortcuts, [- 'press:voice_push_to_talk',- 'press:voice_toggle_mute',- 'release:voice_push_to_talk',- ]);- portal.emit({type: 'deactivated', id: 'voice_push_to_talk'});- assert.equal(harness.shortcuts.length, 3);- });-- test('a repeated activation of a toggle after a lost deactivation is a new press', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_toggle_mute'});- harness.clock += PORTAL_TOGGLE_REARM_MS + 1;- portal.emit({type: 'activated', id: 'voice_toggle_mute'});- portal.emit({type: 'deactivated', id: 'voice_toggle_mute'});- portal.emit({type: 'deactivated', id: 'voice_toggle_mute'});- assert.deepEqual(harness.shortcuts, [- 'press:voice_toggle_mute',- 'release:voice_toggle_mute',- 'press:voice_toggle_mute',- 'release:voice_toggle_mute',- ]);- });-- test('autorepeat of a held toggle never re-arms it', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- for (let index = 0; index < 10; index += 1) {- portal.emit({type: 'activated', id: 'voice_toggle_deafen'});- harness.clock += index === 0 ? 500 : 30;- }- harness.clock += 2000;- portal.emit({type: 'deactivated', id: 'voice_toggle_deafen'});- assert.deepEqual(harness.shortcuts, ['press:voice_toggle_deafen', 'release:voice_toggle_deafen']);- });-- test('a hold shortcut never re-arms on a repeated activation', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- harness.clock += 10 * PORTAL_TOGGLE_REARM_MS;- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.shortcuts, ['press:voice_push_to_talk']);- });-- test('a press after releaseAll is not mistaken for a repeat', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- harness.manager.releaseAll();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.shortcuts, [- 'press:voice_push_to_talk',- 'release:voice_push_to_talk',- 'press:voice_push_to_talk',- ]);- });-- test('releaseAll releases held shortcuts and ignores their later deactivation', async () => {- const harness = createHarness({consent: 'granted', listed: listedAll()});- await harness.manager.activate();- const portal = harness.latestPortal();- portal.emit({type: 'activated', id: 'voice_push_to_talk'});- harness.manager.releaseAll();- portal.emit({type: 'deactivated', id: 'voice_push_to_talk'});- assert.deepEqual(harness.shortcuts, ['press:voice_push_to_talk', 'release:voice_push_to_talk']);- });-});diff --git a/fluxer_desktop/src/main/LinuxLaunchPath.test.mjs b/fluxer_desktop/src/main/LinuxLaunchPath.test.mjsdeleted file mode 100644index f16e0d933..000000000--- a/fluxer_desktop/src/main/LinuxLaunchPath.test.mjs+++ /dev/null@@ -1,227 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {spawn, spawnSync} from 'node:child_process';-import {chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import {tmpdir} from 'node:os';-import {join} from 'node:path';-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('./LinuxLaunchPath.ts', import.meta.url));-const transformedSource = esbuild.transformSync(readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--const APPIMAGE_PATH = '/home/hampus/Applications/My Fluxer.AppImage';-const EXEC_PATH = '/tmp/.mount_My FluhKjNGD/fluxer-canary';--function loadLaunchPath({- platform = 'linux',- appImagePath = APPIMAGE_PATH,- argv = [],- spawnThrows = false,- shells = ['/bin/bash'],-} = {}) {- const spawned = [];- const relaunched = [];- const module = {exports: {}};- const stubs = {- '@electron/common/Logger': {createChildLogger: () => ({debug() {}, info() {}, warn() {}, error() {}})},- electron: {- app: {- relaunch(options) {- relaunched.push(options);- },- },- },- 'node:child_process': {- spawn(command, args, options) {- if (spawnThrows) {- throw new Error('spawn EPERM');- }- let unrefCalls = 0;- const child = {- pid: 4242,- unref() {- unrefCalls += 1;- },- get unrefCalls() {- return unrefCalls;- },- };- spawned.push({command, args, options, child});- return child;- },- },- 'node:fs': {existsSync: (path) => shells.includes(path)},- 'node:os': {homedir: () => '/home/hampus'},- };- const context = vm.createContext({- module,- exports: module.exports,- console,- process: {- platform,- pid: 13274,- execPath: EXEC_PATH,- argv: [EXEC_PATH, ...argv],- env: appImagePath ? {APPIMAGE: appImagePath} : {},- },- require: (specifier) => stubs[specifier] ?? require(specifier),- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return {...module.exports, spawned, relaunched};-}--describe('Linux launch path', () => {- test('reports the AppImage as the stable launch path', () => {- assert.equal(loadLaunchPath({}).getStableLinuxLaunchPath(), APPIMAGE_PATH);- assert.equal(loadLaunchPath({appImagePath: null}).getStableLinuxLaunchPath(), EXEC_PATH);- assert.equal(loadLaunchPath({platform: 'darwin'}).getStableLinuxLaunchPath(), EXEC_PATH);- });-});--function relaunchScript() {- const probe = loadLaunchPath({});- probe.relaunchStableLaunchPath();- return probe.spawned[0].args[1];-}--describe('AppImage relaunch script', () => {- for (const shell of ['/bin/bash', '/bin/sh']) {- test(`replaces the process once the parent exits under ${shell}`, {skip: !existsSync(shell)}, async () => {- const root = mkdtempSync(join(tmpdir(), 'fluxer-relaunch-test-'));- const marker = join(root, 'replacement-argv');- const replacement = join(root, 'My Fluxer.AppImage');- writeFileSync(- replacement,- `#!${shell}\nprintf '%s\\n' "$@" > '${marker}.tmp'\nmv '${marker}.tmp' '${marker}'\n`,- {mode: 0o755},- );- const parent = spawn(shell, ['-c', 'sleep 30'], {stdio: 'ignore', detached: true});- parent.unref();-- const relaunch = spawn(- shell,- [- '-c',- relaunchScript(),- 'fluxer-relaunch',- String(parent.pid),- replacement,- root,- '--fluxer-portable',- 'fluxer://invite/a b',- ],- {cwd: root, detached: true, stdio: 'ignore'},- );- relaunch.unref();-- spawnSync('kill', [String(parent.pid)]);- for (let attempt = 0; attempt < 100 && !existsSync(marker); attempt += 1) {- await new Promise((resolve) => setTimeout(resolve, 100));- }-- assert.equal(existsSync(marker), true, 'the replacement never started');- assert.deepEqual(readFileSync(marker, 'utf8').split('\n').slice(0, 2), [- '--fluxer-portable',- 'fluxer://invite/a b',- ]);- chmodSync(replacement, 0o755);- });- }-});--describe('AppImage relaunch', () => {- test('never asks Electron to relaunch an AppImage', () => {- const updater = loadLaunchPath({argv: ['--fluxer-portable']});-- updater.relaunchStableLaunchPath();-- assert.equal(- updater.relaunched.length,- 0,- "Electron's relauncher runs under PR_SET_NO_NEW_PRIVS, which makes the setuid fusermount the AppImage runtime needs fail with EPERM, so the app quits and never comes back",- );- assert.equal(updater.spawned.length, 1);- const [relaunch] = updater.spawned;- assert.equal(relaunch.command, '/bin/bash');- assert.equal(relaunch.options.detached, true);- assert.equal(relaunch.options.stdio, 'ignore');- assert.equal(relaunch.options.cwd, '/home/hampus');- assert.equal(relaunch.child.unrefCalls, 1);- });-- test('waits for this process to exit before starting the replacement, and keeps its arguments', () => {- const updater = loadLaunchPath({argv: ['--fluxer-portable', 'fluxer://invite/a b']});-- updater.relaunchStableLaunchPath();-- const [flag, script, name, pid, target, home, ...forwarded] = updater.spawned[0].args;- assert.equal(flag, '-c');- assert.match(script, /kill -0 "\$pid"/);- assert.match(script, /exec "\$app" "\$@"/);- assert.equal(name, 'fluxer-relaunch');- assert.equal(pid, '13274');- assert.equal(target, APPIMAGE_PATH);- assert.equal(home, '/home/hampus');- assert.deepEqual(forwarded, ['--fluxer-portable', 'fluxer://invite/a b']);- });-- test('hands the replacement a clean descriptor table', () => {- const updater = loadLaunchPath({});-- updater.relaunchStableLaunchPath();-- const script = updater.spawned[0].args[1];- assert.match(- script,- /cd \/proc\/self\/fd/,- "Chromium leaves its icudtl.dat, v8 snapshot, .pak and app.asar descriptors open across a spawn, so the replacement would pin the outgoing build's fuse mount and its unlinked AppImage for as long as it runs",- );- assert.match(- script,- /\[ -n "\$BASH_VERSION" \]/,- 'dash only parses single digit descriptor numbers, and a failed exec kills a non-interactive shell, so the two-digit closes have to be guarded',- );- });-- test('falls back to the system shell when bash is missing', () => {- const updater = loadLaunchPath({shells: ['/bin/sh']});-- updater.relaunchStableLaunchPath();-- assert.equal(updater.spawned[0].command, '/bin/sh');- assert.equal(updater.relaunched.length, 0);- });-- test('leaves every other install to Electron', () => {- const deb = loadLaunchPath({appImagePath: null});- deb.relaunchStableLaunchPath();- assert.equal(deb.spawned.length, 0);- assert.deepEqual(deb.relaunched, [undefined]);-- const mac = loadLaunchPath({platform: 'darwin'});- mac.relaunchStableLaunchPath();- assert.equal(mac.spawned.length, 0);- assert.deepEqual(mac.relaunched, [undefined]);- });-- test('falls back to Electron when the replacement process cannot be started', () => {- const updater = loadLaunchPath({spawnThrows: true});-- updater.relaunchStableLaunchPath();-- assert.equal(updater.relaunched.length, 1);- assert.equal(updater.relaunched[0]?.execPath, APPIMAGE_PATH);- });-});diff --git a/fluxer_desktop/src/main/MainWindowReveal.test.mjs b/fluxer_desktop/src/main/MainWindowReveal.test.mjsdeleted file mode 100644index 1c93f1931..000000000--- a/fluxer_desktop/src/main/MainWindowReveal.test.mjs+++ /dev/null@@ -1,111 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';--const {MAIN_WINDOW_CONTENT_GRACE_MS, MAIN_WINDOW_HARD_FALLBACK_MS, MainWindowRevealGate, MainWindowRevealReason} =- await import('./MainWindowReveal.ts');--function harness() {- const reveals = [];- const timers = [];- const gate = new MainWindowRevealGate({- onReveal: (reason) => reveals.push(reason),- setTimer: (callback, delayMs) => {- const timer = {callback, delayMs, cleared: false};- timers.push(timer);- return timer;- },- clearTimer: (timer) => {- timer.cleared = true;- },- });- const live = () => timers.filter((timer) => !timer.cleared);- const fire = (delayMs) => {- const timer = live().find((entry) => entry.delayMs === delayMs);- assert.ok(timer, `no live ${delayMs} ms timer`);- timer.cleared = true;- timer.callback();- };- return {gate, reveals, timers, live, fire};-}--describe('main window reveal gate', () => {- test('ready-to-show alone never reveals a window whose renderer has not painted content', () => {- const {gate, reveals} = harness();- gate.start();- gate.markReadyToShow();-- assert.deepEqual(reveals, []);- assert.equal(gate.revealed, false);- });-- test('the renderer content signal reveals at once and disarms every fallback', () => {- const {gate, reveals, live} = harness();- gate.start();- gate.markReadyToShow();-- gate.markContentPainted();-- assert.deepEqual(reveals, [MainWindowRevealReason.CONTENT_PAINTED]);- assert.deepEqual(live(), []);- });-- test('content painted before ready-to-show still reveals exactly once', () => {- const {gate, reveals, live} = harness();- gate.start();- gate.markContentPainted();- gate.markReadyToShow();- gate.markContentPainted();-- assert.deepEqual(reveals, [MainWindowRevealReason.CONTENT_PAINTED]);- assert.deepEqual(live(), []);- });-- test('a renderer that never signals is revealed after the grace that follows its first paint', () => {- const {gate, reveals, fire} = harness();- gate.start();- gate.markReadyToShow();-- fire(MAIN_WINDOW_CONTENT_GRACE_MS);-- assert.deepEqual(reveals, [MainWindowRevealReason.CONTENT_GRACE_EXPIRED]);- });-- test('a window that never paints at all is still revealed by the hard fallback', () => {- const {gate, reveals, fire, live} = harness();- gate.start();-- fire(MAIN_WINDOW_HARD_FALLBACK_MS);-- assert.deepEqual(reveals, [MainWindowRevealReason.HARD_FALLBACK]);- assert.deepEqual(live(), []);- });-- test('the grace never outlasts the hard fallback and both are bounded', () => {- assert.ok(MAIN_WINDOW_CONTENT_GRACE_MS < MAIN_WINDOW_HARD_FALLBACK_MS);- assert.ok(MAIN_WINDOW_HARD_FALLBACK_MS <= 10000);- });-- test('a window shown or closed by someone else disarms the gate without revealing', () => {- const {gate, reveals, live} = harness();- gate.start();- gate.markReadyToShow();-- gate.dispose();- gate.markContentPainted();-- assert.deepEqual(reveals, []);- assert.deepEqual(live(), []);- });-- test('repeated ready-to-show and start calls arm one timer each', () => {- const {gate, timers} = harness();- gate.start();- gate.start();- gate.markReadyToShow();- gate.markReadyToShow();-- assert.equal(timers.length, 2);- });-});diff --git a/fluxer_desktop/src/main/ModuleBootHandoff.test.mjs b/fluxer_desktop/src/main/ModuleBootHandoff.test.mjsdeleted file mode 100644index a41263acc..000000000--- a/fluxer_desktop/src/main/ModuleBootHandoff.test.mjs+++ /dev/null@@ -1,199 +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 {- armOpenUrlForwarding,- armSecondInstanceForwarding,- onMainWindowCreated,- onMainWindowReady,- setOpenUrlSink,- setSecondInstanceSink,- signalMainWindowCreated,- signalMainWindowReady,-} = await import('@electron/main/ModuleBootHandoff');--describe('ModuleBootHandoff', () => {- test('a listener registered before the signal receives the window', () => {- const received = [];- onMainWindowCreated((window) => {- received.push(window);- });- onMainWindowCreated(() => {- throw new Error('this listener throws');- });- onMainWindowCreated((window) => {- received.push(window);- });- assert.deepEqual(received, []);- const window = {id: 1, isDestroyed: () => false};- signalMainWindowCreated(window);- assert.deepEqual(received, [window, window]);- });-- test('a listener registered after the signal fires immediately', () => {- const received = [];- onMainWindowCreated((window) => {- received.push(window);- });- assert.equal(received.length, 1);- assert.equal(received[0].id, 1);- });-- test('a second signal is ignored', () => {- const received = [];- signalMainWindowCreated({id: 2, isDestroyed: () => false});- onMainWindowCreated((window) => {- received.push(window);- });- assert.equal(received[0].id, 1);- });-- test('creating the window does not by itself mean the window became ready', () => {- let ready = 0;- onMainWindowReady(() => {- ready += 1;- });- assert.equal(ready, 0);- });-- test('the ready signal fires every waiting listener exactly once and survives a thrower', () => {- let ready = 0;- onMainWindowReady(() => {- throw new Error('this listener throws');- });- onMainWindowReady(() => {- ready += 1;- });- signalMainWindowReady();- signalMainWindowReady();- assert.equal(ready, 1);- });-- test('a ready listener registered after the signal fires immediately', () => {- let ready = 0;- onMainWindowReady(() => {- ready += 1;- });- assert.equal(ready, 1);- });-});--const appRegistrations = [];-installElectronStub({- app: {- on: (eventName, listener) => {- appRegistrations.push({eventName, listener, once: false});- },- once: (eventName, listener) => {- appRegistrations.push({eventName, listener, once: true});- },- },-});--describe('ModuleBootHandoff second instance forwarding', () => {- const registrations = appRegistrations;- const forward = (argv) => {- registrations[0].listener({}, argv, '/');- };-- test('arming is idempotent, so the bootstrap and the main app cannot double dispatch one launch', () => {- armSecondInstanceForwarding();- armSecondInstanceForwarding();- assert.deepEqual(- registrations.map(({eventName}) => eventName),- ['second-instance'],- 'the bootstrap arms this the moment it takes the lock and the main app arms it again on the path where the bootstrap never ran',- );- });-- test('launches forwarded before a sink exists are replayed in order once it lands, thrower and all', () => {- forward(['fluxer', 'fluxer://channels/1']);- forward(['fluxer', 'boom']);- forward(['fluxer', '--jump-list-task=new-dm']);- const seen = [];- setSecondInstanceSink((argv) => {- seen.push(argv[1]);- if (argv[1] === 'boom') {- throw new Error('this sink throws');- }- });- assert.deepEqual(- seen,- ['fluxer://channels/1', 'boom', '--jump-list-task=new-dm'],- 'Electron never queues second-instance, so a launch that arrives while the splash is still updating is only recoverable from this buffer',- );- });-- test('a launch that arrives after the sink landed reaches it directly and nothing is replayed twice', () => {- const seen = [];- setSecondInstanceSink((argv) => {- seen.push(argv[1]);- });- assert.deepEqual(seen, [], 'the buffer drained into the first sink, so a later sink must start empty');- forward(['fluxer', 'fluxer://channels/2']);- assert.deepEqual(seen, ['fluxer://channels/2']);- });-});--describe('ModuleBootHandoff open-url forwarding', () => {- const registrations = appRegistrations;- const listenerFor = (eventName) =>- registrations.find((registration) => registration.eventName === eventName).listener;- const openUrl = (url) => {- let prevented = false;- listenerFor('open-url')(- {- preventDefault: () => {- prevented = true;- },- },- url,- );- return prevented;- };-- test('arming is idempotent and listens for open-url and the launch fallback link', () => {- armOpenUrlForwarding();- armOpenUrlForwarding();- assert.deepEqual(- registrations- .filter(({eventName}) => eventName !== 'second-instance')- .map(({eventName, once}) => [eventName, once]),- [- ['open-url', false],- ['ready', true],- ],- );- });-- test('links opened before the main app exists are buffered and replayed in order once its sink lands', () => {- assert.equal(openUrl('fluxer://invite/abc'), true, 'macOS opens the link in a browser unless the event is claimed');- listenerFor('ready')({}, {userInfo: {fallbackDeepLink: 'fluxer://channels/1'}});- openUrl('fluxer://boom');- const seen = [];- setOpenUrlSink((url) => {- seen.push(url);- if (url === 'fluxer://boom') {- throw new Error('this sink throws');- }- });- assert.deepEqual(- seen,- ['fluxer://invite/abc', 'fluxer://channels/1', 'fluxer://boom'],- 'open-url fires around will-finish-launching on a cold start, long before module convergence imports the main app',- );- });-- test('a link that arrives after the sink landed reaches it directly and nothing is replayed twice', () => {- const seen = [];- setOpenUrlSink((url) => {- seen.push(url);- });- assert.deepEqual(seen, []);- openUrl('fluxer://channels/2');- assert.deepEqual(seen, ['fluxer://channels/2']);- });-});diff --git a/fluxer_desktop/src/main/NativeAudioValidation.test.mjs b/fluxer_desktop/src/main/NativeAudioValidation.test.mjsdeleted file mode 100644index eb723bba4..000000000--- a/fluxer_desktop/src/main/NativeAudioValidation.test.mjs+++ /dev/null@@ -1,61 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import {loadTsModule} from './fixtures/TsModuleLoader.mjs';--const {isValidWinEndpoints, resolveWindowsCaptureScope} = loadTsModule('@electron/main/NativeAudioValidation');--const SPEAKERS_ID = '{0.0.0.00000000}.{6f1e8a2c-0000-4000-8000-000000000001}';--describe('isValidWinEndpoints', () => {- test('accepts the default entry and device ids', () => {- assert.equal(isValidWinEndpoints(['default']), true);- assert.equal(isValidWinEndpoints(['default', SPEAKERS_ID]), true);- assert.equal(isValidWinEndpoints([`{${'a'.repeat(511)}`]), true);- });-- test('rejects malformed selections', () => {- assert.equal(isValidWinEndpoints(undefined), false);- assert.equal(isValidWinEndpoints('default'), false);- assert.equal(isValidWinEndpoints([]), false);- assert.equal(isValidWinEndpoints(Array.from({length: 17}, (_, index) => `{${index}}`)), false);- assert.equal(isValidWinEndpoints(['speakers']), false);- assert.equal(isValidWinEndpoints(['{abc\0}']), false);- assert.equal(isValidWinEndpoints([`{${'a'.repeat(512)}`]), false);- assert.equal(isValidWinEndpoints([42]), false);- });-});--describe('resolveWindowsCaptureScope', () => {- const fullCapabilities = {- process: true,- system: true,- processExclude: true,- sessionMixer: true,- endpointSelect: true,- };-- test('device selection needs the session mixer and the endpoint capability', () => {- assert.deepEqual(resolveWindowsCaptureScope('session-mixer', ['default'], fullCapabilities), {- captureScope: 'session-mixer',- endpoints: ['default'],- });- assert.throws(() =>- resolveWindowsCaptureScope('session-mixer', ['default'], {...fullCapabilities, endpointSelect: false}),- );- assert.throws(() => resolveWindowsCaptureScope('session-mixer', ['default'], undefined));- assert.throws(() => resolveWindowsCaptureScope('system', ['default'], fullCapabilities));- });-- test('include-only hosts downgrade entire system audio to the session mixer', () => {- assert.deepEqual(resolveWindowsCaptureScope('system', undefined, {...fullCapabilities, processExclude: false}), {- captureScope: 'session-mixer',- });- });-- test('entire system audio keeps process-exclude loopback when it is available', () => {- assert.deepEqual(resolveWindowsCaptureScope('system', undefined, fullCapabilities), {captureScope: 'system'});- assert.deepEqual(resolveWindowsCaptureScope('process', undefined, fullCapabilities), {captureScope: 'process'});- });-});diff --git a/fluxer_desktop/src/main/NativeModulePreflight.test.mjs b/fluxer_desktop/src/main/NativeModulePreflight.test.mjsdeleted file mode 100644index 1dfff87d2..000000000--- a/fluxer_desktop/src/main/NativeModulePreflight.test.mjs+++ /dev/null@@ -1,181 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import crypto from 'node:crypto';-import {readFileSync} from 'node:fs';-import {createRequire} from 'node:module';-import nodePath from 'node:path';-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('./NativeModulePreflight.ts', import.meta.url));-const transformedSource = esbuild.transformSync(readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--const MARKER_PATH = nodePath.join('/userData', 'native-module-preflight-v2.json');--function loadPreflight({- files = new Map(),- unresolvable = new Set(),- probeFailures = new Set(),- isPackaged = true,-} = {}) {- const spawns = [];- const warnings = [];-- function spawnSyncStub(_execPath, args) {- spawns.push(args.slice(2));- const lines = [];- for (const [index, modulePath] of args.slice(2).entries()) {- lines.push(JSON.stringify({i: index, modulePath, phase: 'start'}));- const failing = [...probeFailures].some((name) => modulePath.includes(name));- lines.push(- JSON.stringify(- failing- ? {i: index, modulePath, phase: 'load-error', message: 'dlopen failed'}- : {i: index, modulePath, phase: 'done'},- ),- );- }- return {stdout: `${lines.join('\n')}\n`, stderr: '', status: 0, signal: null, error: undefined};- }-- function requireStub(specifier) {- if (specifier === 'node:child_process') return {spawnSync: spawnSyncStub};- if (specifier === 'node:crypto') return crypto;- if (specifier === 'node:path') return nodePath;- if (specifier === 'node:fs') {- return {- existsSync: (path) => files.has(path),- mkdirSync: () => {},- readFileSync: (path) => {- if (!files.has(path)) throw new Error(`ENOENT: ${path}`);- return files.get(path);- },- writeFileSync: (path, contents) => files.set(path, contents),- };- }- if (specifier === 'node:module') {- return {- createRequire: () => ({- resolve: (name) => {- if (unresolvable.has(name)) throw new Error(`Cannot find module '${name}'`);- return `/app/node_modules/${name}/index.js`;- },- }),- };- }- if (specifier === '@electron/main/NativeModulePreflightModules.json') {- return JSON.parse(readFileSync(new URL('./NativeModulePreflightModules.json', import.meta.url), 'utf8'));- }- if (specifier === '@electron/main/AppStoreNativeBoundary') return {APP_STORE_ADDON_PACKAGE: '@fluxer/app-store'};- if (specifier === '@electron/main/GatewaySocketNativeBoundary') {- return {GATEWAY_SOCKET_ADDON_PACKAGE: '@fluxer/gateway-socket'};- }- if (specifier === 'electron') {- return {- app: {- isPackaged,- getVersion: () => '1.2.3',- getPath: () => '/userData',- },- };- }- if (specifier === 'electron-log') {- return {- info: () => {},- warn: (...args) => warnings.push(args),- };- }- throw new Error(`Unexpected import: ${specifier}`);- }-- const module = {exports: {}};- const context = vm.createContext({- exports: module.exports,- module,- process: {env: {}, platform: 'linux', arch: 'x64', execPath: '/app/fluxer'},- require: requireStub,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});-- return {files, module: module.exports, spawns, warnings};-}--function degradedModules(preflight) {- return [...preflight.module.runNativeModulePreflight().degraded];-}--describe('NativeModulePreflight', () => {- test('does nothing and reports no degraded modules when the app is not packaged', () => {- const preflight = loadPreflight({isPackaged: false});- assert.deepEqual(degradedModules(preflight), []);- assert.equal(preflight.spawns.length, 0);- });-- test('a missing optional addon degrades instead of aborting startup', () => {- const preflight = loadPreflight({unresolvable: new Set(['@fluxer/app-store'])});- assert.deepEqual(degradedModules(preflight), ['@fluxer/app-store']);- const marker = JSON.parse(preflight.files.get(MARKER_PATH));- assert.equal(marker.version, 2);- assert.deepEqual(marker.degraded, ['@fluxer/app-store']);- });-- test('an optional addon that fails to dlopen degrades instead of aborting startup', () => {- const preflight = loadPreflight({probeFailures: new Set(['@fluxer/gateway-socket'])});- assert.deepEqual(degradedModules(preflight), ['@fluxer/gateway-socket']);- assert.equal(preflight.warnings.length, 1);- });-- test('a required addon still aborts startup and clears the marker', () => {- const files = new Map([[MARKER_PATH, JSON.stringify({version: 2, fingerprint: 'stale', degraded: []})]]);- const {module} = loadPreflight({files, probeFailures: new Set(['@fluxer/linux-portals'])});- assert.throws(() => module.runNativeModulePreflight(), /native module preflight failed/);- assert.equal(files.get(MARKER_PATH), '');- });-- test('a matching marker replays the recorded degraded set without probing again', () => {- const first = loadPreflight({unresolvable: new Set(['@fluxer/gateway-socket'])});- assert.deepEqual(degradedModules(first), ['@fluxer/gateway-socket']);- const second = loadPreflight({files: first.files, unresolvable: new Set(['@fluxer/gateway-socket'])});- assert.deepEqual(degradedModules(second), ['@fluxer/gateway-socket']);- assert.equal(second.spawns.length, 0);- });-- test('a version 1 marker is read as no degraded modules', () => {- const probe = loadPreflight();- assert.deepEqual(degradedModules(probe), []);- const {fingerprint} = JSON.parse(probe.files.get(MARKER_PATH));- const files = new Map([- [MARKER_PATH, JSON.stringify({version: 1, fingerprint, completedAt: '2026-01-01T00:00:00.000Z'})],- ]);- const replay = loadPreflight({files});- assert.deepEqual(degradedModules(replay), []);- assert.equal(replay.spawns.length, 0);- });-- test('an unreadable marker is ignored rather than treated as a pass', () => {- const files = new Map([[MARKER_PATH, 'not json']]);- const preflight = loadPreflight({files});- assert.deepEqual(degradedModules(preflight), []);- assert.equal(preflight.spawns.length, 1);- });-});--test('every module the preflight requires is a dependency of the desktop app', () => {- const modules = JSON.parse(readFileSync(new URL('./NativeModulePreflightModules.json', import.meta.url), 'utf8'));- const manifest = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));- const dependencies = {...manifest.dependencies, ...manifest.optionalDependencies};- assert.deepEqual(- modules.map((spec) => spec.name).filter((name) => !Object.hasOwn(dependencies, name)),- [],- );-});diff --git a/fluxer_desktop/src/main/NativeProbeCache.test.mjs b/fluxer_desktop/src/main/NativeProbeCache.test.mjsdeleted file mode 100644index 0eb564ee4..000000000--- a/fluxer_desktop/src/main/NativeProbeCache.test.mjs+++ /dev/null@@ -1,138 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {existsSync, mkdtempSync, readFileSync, writeFileSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import {createRequire, registerHooks} from 'node:module';-import os from 'node:os';-import path from 'node:path';-import {after, afterEach, describe, test} from 'node:test';--const DESKTOP_SRC = new URL('../', 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};- }- return nextResolve(specifier, context);- },-});--const require = createRequire(import.meta.url);-const {loadNativeBinding, probeNativeBinary} = require('../../native/app-store/loader-diagnostics.cjs');-const {NATIVE_PROBE_CACHE_ENV, NATIVE_PROBE_CACHE_FILENAME, armNativeProbeCache} = await import(- './NativeProbeCache.ts'-);--const SKIP_ENV = 'FLUXER_TEST_SKIP_NATIVE_PROBE';-const roots = [];-const savedCacheEnv = process.env[NATIVE_PROBE_CACHE_ENV];--after(async () => {- for (const root of roots) {- await rm(root, {recursive: true, force: true});- }-});--afterEach(() => {- if (savedCacheEnv === undefined) {- delete process.env[NATIVE_PROBE_CACHE_ENV];- } else {- process.env[NATIVE_PROBE_CACHE_ENV] = savedCacheEnv;- }-});--function fixture({exitCode = null} = {}) {- const root = mkdtempSync(path.join(os.tmpdir(), 'native-probe-cache-'));- roots.push(root);- const log = path.join(root, 'loads.log');- const nativePath = path.join(root, 'binding.cjs');- const exit = exitCode == null ? '' : `if (process.env.${SKIP_ENV} === '1') process.exit(${exitCode});`;- writeFileSync(- nativePath,- `require('node:fs').appendFileSync(${JSON.stringify(log)}, 'load\\n');${exit}module.exports = {ok: true};\n`,- );- const cacheFile = path.join(root, 'userData', NATIVE_PROBE_CACHE_FILENAME);- process.env[NATIVE_PROBE_CACHE_ENV] = cacheFile;- return {root, log, nativePath, cacheFile};-}--function loads(log) {- return existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean).length : 0;-}--function probe(nativePath) {- return probeNativeBinary({- moduleName: '@fluxer/test-binding',- nativePath,- nativeRoot: path.dirname(nativePath),- packageDir: path.dirname(nativePath),- skipNativeProbeEnv: SKIP_ENV,- });-}--describe('native module probe cache', () => {- test('a binary that passed its probe is not probed again on the next boot', () => {- const {log, nativePath, cacheFile} = fixture();-- assert.equal(probe(nativePath), null);- assert.equal(loads(log), 1);- assert.equal(existsSync(cacheFile), true);-- assert.equal(probe(nativePath), null);- assert.equal(loads(log), 1);- });-- test('a replaced binary is probed again', () => {- const {log, nativePath} = fixture();- assert.equal(probe(nativePath), null);- writeFileSync(nativePath, `${readFileSync(nativePath, 'utf8')}module.exports.changed = true;\n`);-- assert.equal(probe(nativePath), null);- assert.equal(loads(log), 2);- });-- test('a binary that crashes its probe is never cached as safe', () => {- const {log, nativePath, cacheFile} = fixture({exitCode: 3});-- assert.notEqual(probe(nativePath), null);- assert.notEqual(probe(nativePath), null);- assert.equal(loads(log), 2);- assert.equal(existsSync(cacheFile), false);- });-- test('a binary that loaded in process counts as probed, so the next boot skips the child', () => {- const {log, nativePath} = fixture();- const loaded = loadNativeBinding({- moduleName: '@fluxer/test-binding',- nativePath,- nativeRoot: path.dirname(nativePath),- packageDir: path.dirname(nativePath),- skipNativeProbeEnv: SKIP_ENV,- probe: false,- });- assert.equal(loaded.loadError, null);- assert.equal(loads(log), 1);-- assert.equal(probe(nativePath), null);- assert.equal(loads(log), 1);- });-- test('without a cache file the probe still runs every time', () => {- const {log, nativePath} = fixture();- delete process.env[NATIVE_PROBE_CACHE_ENV];-- probe(nativePath);- probe(nativePath);- assert.equal(loads(log), 2);- });-- test('arming points the loaders at the user data directory and keeps an explicit override', () => {- const env = {};- armNativeProbeCache('/userData', env);- assert.equal(env[NATIVE_PROBE_CACHE_ENV], path.join('/userData', NATIVE_PROBE_CACHE_FILENAME));- armNativeProbeCache('/elsewhere', env);- assert.equal(env[NATIVE_PROBE_CACHE_ENV], path.join('/userData', NATIVE_PROBE_CACHE_FILENAME));- });-});diff --git a/fluxer_desktop/src/main/OpenExternal.test.mjs b/fluxer_desktop/src/main/OpenExternal.test.mjsdeleted file mode 100644index 8a4086f1c..000000000--- a/fluxer_desktop/src/main/OpenExternal.test.mjs+++ /dev/null@@ -1,103 +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('./OpenExternal.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadOpenExternal() {- const openExternalCalls = [];- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- console,- Date,- Error,- Map,- Set,- URL,- require: (specifier) => {- if (specifier === '@electron/common/Constants') {- return {APP_PROTOCOL: 'fluxer'};- }- if (specifier === 'electron') {- return {- shell: {- openExternal: async (url) => {- openExternalCalls.push(url);- },- },- };- }- return require(specifier);- },- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return {...module.exports, openExternalCalls};-}--describe('OpenExternal URL validation', () => {- test('allows standard and custom external protocols', () => {- const {shouldOpenExternalUrl} = loadOpenExternal();-- assert.equal(shouldOpenExternalUrl('https://fluxer.app'), true);- assert.equal(shouldOpenExternalUrl('http://fluxer.app'), true);- assert.equal(shouldOpenExternalUrl('mailto:[email protected]'), true);- assert.equal(shouldOpenExternalUrl('tel:+15551234567'), true);- assert.equal(shouldOpenExternalUrl('fluxer://invite/test'), true);- });-- test('blocks dangerous or malformed external URLs', () => {- const {shouldOpenExternalUrl} = loadOpenExternal();-- assert.equal(shouldOpenExternalUrl('file:///etc/passwd'), false);- assert.equal(shouldOpenExternalUrl('javascript:alert(1)'), false);- assert.equal(shouldOpenExternalUrl('data:text/html,hello'), false);- assert.equal(shouldOpenExternalUrl('about:blank'), false);- assert.equal(shouldOpenExternalUrl('chrome://settings'), false);- assert.equal(shouldOpenExternalUrl('/relative/path'), false);- assert.equal(shouldOpenExternalUrl('not a url'), false);- assert.equal(shouldOpenExternalUrl('http://[::1'), false);- });-- test('blocks schemes outside the allowlist (allowlist hardening)', () => {- const {shouldOpenExternalUrl} = loadOpenExternal();-- assert.equal(shouldOpenExternalUrl('smb://server/share'), false);- assert.equal(shouldOpenExternalUrl('search-ms:query=secret'), false);- assert.equal(shouldOpenExternalUrl('ms-officecmd:foo'), false);- assert.equal(shouldOpenExternalUrl('vbscript:msgbox(1)'), false);- assert.equal(shouldOpenExternalUrl('ftp://example.com/x'), false);- });-- test('opens normalized URLs once inside the dedupe window', async () => {- const {openExternalDeduped, openExternalCalls} = loadOpenExternal();-- await openExternalDeduped('HTTPS://Fluxer.App/path');- await openExternalDeduped('https://fluxer.app/path');-- assert.deepEqual(openExternalCalls, ['https://fluxer.app/path']);- });-- test('rejects blocked URLs before calling Electron shell', async () => {- const {openExternalDeduped, openExternalCalls} = loadOpenExternal();-- await assert.rejects(openExternalDeduped('javascript:alert(1)'), /External URL open request blocked/);- assert.deepEqual(openExternalCalls, []);- });-});diff --git a/fluxer_desktop/src/main/OtherPlatformTemplateIpc.test.mjs b/fluxer_desktop/src/main/OtherPlatformTemplateIpc.test.mjsdeleted file mode 100644index 966d1f4a5..000000000--- a/fluxer_desktop/src/main/OtherPlatformTemplateIpc.test.mjs+++ /dev/null@@ -1,206 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {afterEach, describe, test} from 'node:test';-import {installElectronStub, installWindowStub} from './LocalAppTestSupport.test.mjs';--installElectronStub();-installWindowStub(null);--const {DESKTOP_OTHER_PLATFORM_TEMPLATE_CHANNELS, OtherPlatformTemplateFetchFailure, isOtherPlatformTemplateCode} =- await import('../../../packages/desktop_ipc/src/OtherPlatformTemplateContract.ts');-const {- MAX_TEMPLATE_RESPONSE_BYTES,- cleanupOtherPlatformTemplateHandlers,- fetchOtherPlatformTemplate,- registerOtherPlatformTemplateHandlers,-} = await import('./OtherPlatformTemplateIpc.ts');-const {createOtherPlatformTemplatePreloadAPI} = await import('../preload/OtherPlatformTemplatePreload.ts');--const TEMPLATE_BODY = {code: 'hgM48av5Q69A', name: 'Starter', serialized_source_guild: {name: 'Starter'}};--function installFetch(respond) {- const calls = [];- const handlers = new Map();- installElectronStub({- net: {- fetch: async (url, init) => {- calls.push({url, init});- return respond(url, init);- },- },- ipcMain: {- handle: (channel, listener) => handlers.set(channel, listener),- removeHandler: (channel) => handlers.delete(channel),- },- });- return {calls, handlers};-}--function jsonResponse(body, init = {}) {- return new Response(JSON.stringify(body), {- status: 200,- headers: {'content-type': 'application/json'},- ...init,- });-}--function topLevelSender() {- const frame = {detached: false, parent: null, url: 'fluxer-app://app/'};- return {sender: {}, senderFrame: frame};-}--function subframeSender() {- const parent = {detached: false, parent: null, url: 'fluxer-app://app/'};- return {sender: {}, senderFrame: {detached: false, parent, url: 'fluxer-app://app/'}};-}--afterEach(() => {- cleanupOtherPlatformTemplateHandlers();-});--describe('template code validation', () => {- test('accepts alphanumeric codes and rejects anything that could reshape the URL', () => {- assert.equal(isOtherPlatformTemplateCode('hgM48av5Q69A'), true);- assert.equal(isOtherPlatformTemplateCode('a'.repeat(64)), true);- for (const value of [- '',- 'a'.repeat(65),- 'abc/def',- '../users/@me',- 'abc?x=1',- 'abc#frag',- 'abc def',- 'abc%2F',- 'https://discord.new/abc',- 42,- null,- undefined,- ]) {- assert.equal(isOtherPlatformTemplateCode(value), false, String(value));- }- });-- test('rejects an invalid code before any request is made', async () => {- const {calls} = installFetch(() => jsonResponse(TEMPLATE_BODY));- for (const code of ['abc/../x', '', 'a'.repeat(65), {code: 'abc'}]) {- const result = await fetchOtherPlatformTemplate(code);- assert.deepEqual(result, {- ok: false,- failure: OtherPlatformTemplateFetchFailure.INVALID_CODE,- });- }- assert.equal(calls.length, 0);- });-});--describe('template fetch', () => {- test('requests only the fixed template endpoint with a generic browser user agent and no credentials', async () => {- const {calls} = installFetch(() => jsonResponse(TEMPLATE_BODY));- const result = await fetchOtherPlatformTemplate('hgM48av5Q69A');- assert.deepEqual(result, {ok: true, template: TEMPLATE_BODY});- assert.equal(calls.length, 1);- const [{url, init}] = calls;- assert.equal(url, 'https://discord.com/api/v10/guilds/templates/hgM48av5Q69A');- assert.equal(init.method, 'GET');- assert.equal(init.redirect, 'error');- assert.equal(init.credentials, 'omit');- const userAgent = init.headers['User-Agent'];- assert.match(userAgent, /^Mozilla\/5\.0 \(/);- assert.doesNotMatch(userAgent, /fluxer|electron/i);- assert.equal(init.headers.Accept, 'application/json');- assert.ok(init.signal instanceof AbortSignal);- });-- test('maps a 404 to not found', async () => {- installFetch(() => jsonResponse({message: 'Unknown Guild Template', code: 10057}, {status: 404}));- assert.deepEqual(await fetchOtherPlatformTemplate('missing'), {- ok: false,- failure: OtherPlatformTemplateFetchFailure.NOT_FOUND,- });- });-- test('maps a 429 to rate limited', async () => {- installFetch(() =>- jsonResponse({message: 'You are being rate limited.'}, {status: 429, headers: {'retry-after': '2.4'}}),- );- assert.deepEqual(await fetchOtherPlatformTemplate('busy'), {- ok: false,- failure: OtherPlatformTemplateFetchFailure.RATE_LIMITED,- });- });-- test('maps server errors and transport failures to network', async () => {- installFetch(() => new Response('oops', {status: 503}));- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.NETWORK);- installFetch(() => {- throw new TypeError('net::ERR_INTERNET_DISCONNECTED');- });- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.NETWORK);- installFetch(() => {- throw new TypeError('redirect mode is set to error');- });- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.NETWORK);- });-- test('maps unreadable, non-object and oversized bodies to invalid response', async () => {- installFetch(() => new Response('<html>not json</html>', {status: 200}));- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.INVALID_RESPONSE);- installFetch(() => jsonResponse([TEMPLATE_BODY]));- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.INVALID_RESPONSE);- installFetch(- () => new Response('x', {status: 200, headers: {'content-length': String(MAX_TEMPLATE_RESPONSE_BYTES + 1)}}),- );- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.INVALID_RESPONSE);- const chunk = new Uint8Array(1024 * 1024).fill(0x20);- let sent = 0;- const stream = new ReadableStream({- pull(controller) {- if (sent > MAX_TEMPLATE_RESPONSE_BYTES) {- controller.close();- return;- }- sent += chunk.byteLength;- controller.enqueue(chunk);- },- });- installFetch(() => new Response(stream, {status: 200}));- assert.equal((await fetchOtherPlatformTemplate('abc')).failure, OtherPlatformTemplateFetchFailure.INVALID_RESPONSE);- assert.ok(sent <= MAX_TEMPLATE_RESPONSE_BYTES + chunk.byteLength);- });-});--describe('template IPC', () => {- test('the preload call reaches the registered handler for a trusted top-level document', async () => {- const {handlers} = installFetch(() => jsonResponse(TEMPLATE_BODY));- registerOtherPlatformTemplateHandlers();- const handler = handlers.get(DESKTOP_OTHER_PLATFORM_TEMPLATE_CHANNELS.fetch);- assert.equal(typeof handler, 'function');- const api = createOtherPlatformTemplatePreloadAPI({- invoke: (channel, ...args) => handlers.get(channel)(topLevelSender(), ...args),- });- assert.deepEqual(await api.otherPlatformTemplate.fetch('hgM48av5Q69A'), {ok: true, template: TEMPLATE_BODY});- });-- test('refuses subframes and detached frames without fetching', async () => {- const {calls, handlers} = installFetch(() => jsonResponse(TEMPLATE_BODY));- registerOtherPlatformTemplateHandlers();- const handler = handlers.get(DESKTOP_OTHER_PLATFORM_TEMPLATE_CHANNELS.fetch);- assert.throws(() => handler(subframeSender(), 'hgM48av5Q69A'), /trusted top-level renderer document/);- const detached = topLevelSender();- detached.senderFrame.detached = true;- assert.throws(() => handler(detached, 'hgM48av5Q69A'), /trusted top-level renderer document/);- assert.throws(- () => handler({sender: {}, senderFrame: null}, 'hgM48av5Q69A'),- /trusted top-level renderer document/,- );- assert.equal(calls.length, 0);- });-- test('cleanup removes the handler', () => {- const {handlers} = installFetch(() => jsonResponse(TEMPLATE_BODY));- registerOtherPlatformTemplateHandlers();- cleanupOtherPlatformTemplateHandlers();- assert.equal(handlers.has(DESKTOP_OTHER_PLATFORM_TEMPLATE_CHANNELS.fetch), false);- });-});diff --git a/fluxer_desktop/src/main/Passkeys.test.mjs b/fluxer_desktop/src/main/Passkeys.test.mjsdeleted file mode 100644index c3400a4c5..000000000--- a/fluxer_desktop/src/main/Passkeys.test.mjs+++ /dev/null@@ -1,211 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {registerHooks} from 'node:module';-import {describe, test} from 'node:test';-import {installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--const PROTOCOL_STATE_KEY = '__fluxerPasskeyProtocolTestState__';-const WEBAUTHN_STUB_URL = 'file:///fluxer-webauthn-passkey-test-stub.cjs';-const CEREMONY_STATE_KEY = '__fluxerPasskeyCeremonyTestState__';--const protocolState = {activePlan: null, cachedPlans: new Map()};-const ceremonyState = {calls: []};-globalThis[PROTOCOL_STATE_KEY] = protocolState;-globalThis[CEREMONY_STATE_KEY] = ceremonyState;--installTestModuleStub(- '@electron/main/LocalAppProtocol',- `const state = globalThis[${JSON.stringify(PROTOCOL_STATE_KEY)}];-export const getDesktopLocalAppProtocol = () => ({- getActivePlan: () => state.activePlan,- findPlanForRoute: (key) => (state.activePlan?.instanceKey === key ? state.activePlan : (state.cachedPlans.get(key) ?? null)),-});`,-);--registerHooks({- resolve(specifier, context, nextResolve) {- if (specifier === '@fluxer/webauthn') {- return {shortCircuit: true, url: WEBAUTHN_STUB_URL};- }- return nextResolve(specifier, context);- },- load(url, context, nextLoad) {- if (url === WEBAUTHN_STUB_URL) {- return {- shortCircuit: true,- format: 'commonjs',- source: `const state = globalThis[${JSON.stringify(CEREMONY_STATE_KEY)}];-const credential = {- rawId: Buffer.from('credential-id'),- response: Buffer.from(JSON.stringify({clientDataJSON: 'client-data'})),- authenticatorAttachment: null,-};-module.exports = {- isSupported: async () => true,- get: async (options) => {- state.calls.push(options);- return credential;- },- create: async (options) => {- state.calls.push(options);- return credential;- },-};`,- };- }- return nextLoad(url, context);- },-});--const handlers = new Map();-installElectronStub({- ipcMain: {- handle: (channel, listener) => handlers.set(channel, listener),- removeHandler: (channel) => handlers.delete(channel),- },- BrowserWindow: {fromWebContents: () => null, getFocusedWindow: () => null},-});--const {registerPasskeyHandlers} = await import('./Passkeys.ts');--registerPasskeyHandlers();--const REQUEST_OPTIONS = {- challenge: 'Y2hhbGxlbmdl',- rpId: 'fluxer.app',- allowCredentials: [],-};--const REGISTRATION_OPTIONS = {- challenge: 'Y2hhbGxlbmdl',- rp: {id: 'fluxer.app', name: 'Fluxer'},- user: {id: 'dXNlcg', name: 'user', displayName: 'user'},- pubKeyCredParams: [{type: 'public-key', alg: -7}],-};--function plan(apiEndpoint, webAppEndpoint) {- return {- instanceKey: apiEndpoint,- document: {},- selfHosted: false,- endpoints: {- apiEndpoint,- apiPublicEndpoint: apiEndpoint,- webAppEndpoint,- mediaEndpoint: null,- staticCdnEndpoint: null,- uploadRelayEndpoint: null,- gatewayEndpoint: null,- inviteEndpoint: null,- giftEndpoint: null,- },- };-}--function localAppEvent() {- const frame = {url: 'fluxer-app://app/'};- return {senderFrame: frame, sender: {getURL: () => frame.url}};-}--async function authenticate(requestContext) {- ceremonyState.calls = [];- const handler = handlers.get('passkey-authenticate');- assert.ok(handler != null);- return await handler(localAppEvent(), REQUEST_OPTIONS, requestContext);-}--async function register(requestContext) {- ceremonyState.calls = [];- const handler = handlers.get('passkey-register');- assert.ok(handler != null);- return await handler(localAppEvent(), REGISTRATION_OPTIONS, requestContext);-}--describe('passkey ceremony origin', () => {- test('an instance may only sign a ceremony for its own registrable site', async () => {- protocolState.activePlan = plan('https://api.fluxer.app', 'https://web.fluxer.app');- await authenticate();- assert.equal(ceremonyState.calls[0]?.origin, 'https://web.fluxer.app');-- protocolState.activePlan = plan('http://localhost:8088/api', 'http://localhost:8088');- await authenticate();- assert.equal(ceremonyState.calls[0]?.origin, 'http://localhost:8088');- });-- test('an instance may not name another site as the ceremony origin', async () => {- protocolState.activePlan = plan('https://evil.example', 'https://web.fluxer.app');- await assert.rejects(authenticate(), /UntrustedPasskeyCeremonyOriginError/u);- assert.deepEqual(ceremonyState.calls, []);- });-- test('a bare address or public suffix may not borrow another host', async () => {- protocolState.activePlan = plan('https://10.0.0.1', 'https://20.0.0.1');- await assert.rejects(authenticate(), /UntrustedPasskeyCeremonyOriginError/u);-- protocolState.activePlan = plan('https://api.fluxer.app', 'https://web.fluxer.app.');- await assert.rejects(authenticate(), /UntrustedPasskeyCeremonyOriginError/u);-- assert.deepEqual(ceremonyState.calls, []);- });-- test('sharing a public suffix is not sharing a site', async () => {- for (const [api, webApp] of [- ['https://api.evil.co.uk', 'https://bank.co.uk'],- ['https://evil.github.io', 'https://victim.github.io'],- ['https://evil.vercel.app', 'https://victim.vercel.app'],- ['https://evil.pages.dev', 'https://victim.pages.dev'],- ['https://evil.fluxer.app', 'https://web.fluxer.app'],- ]) {- protocolState.activePlan = plan(api, webApp);- await assert.rejects(authenticate(), /UntrustedPasskeyCeremonyOriginError/u);- }- assert.deepEqual(ceremonyState.calls, []);- });-- test('a ceremony without an active plan is refused', async () => {- protocolState.activePlan = null;- await assert.rejects(authenticate(), /requires a browser frame origin/u);- assert.deepEqual(ceremonyState.calls, []);- });-- test('a signed-out ceremony uses the plan of the instance that issued the options', async () => {- protocolState.activePlan = null;- const official = plan('https://api.fluxer.app', 'https://web.fluxer.app');- protocolState.cachedPlans = new Map([[official.instanceKey, official]]);- await authenticate({instanceKey: official.instanceKey});- assert.equal(ceremonyState.calls[0]?.origin, 'https://web.fluxer.app');- await register({instanceKey: official.instanceKey, pin: '1234'});- assert.equal(ceremonyState.calls[0]?.origin, 'https://web.fluxer.app');- assert.equal(ceremonyState.calls[0]?.pin, '1234');- protocolState.cachedPlans = new Map();- });-- test('the named instance wins over the active plan of another instance', async () => {- protocolState.activePlan = plan('http://localhost:8088/api', 'http://localhost:8088');- const official = plan('https://api.fluxer.app', 'https://web.fluxer.app');- protocolState.cachedPlans = new Map([[official.instanceKey, official]]);- await authenticate({instanceKey: official.instanceKey});- assert.equal(ceremonyState.calls[0]?.origin, 'https://web.fluxer.app');- protocolState.cachedPlans = new Map();- });-- test('an unknown instance never falls back to the active plan', async () => {- protocolState.activePlan = plan('https://api.fluxer.app', 'https://web.fluxer.app');- protocolState.cachedPlans = new Map();- await assert.rejects(- authenticate({instanceKey: 'https://unknown.example/api'}),- /requires a browser frame origin/u,- );- assert.deepEqual(ceremonyState.calls, []);- });-- test('a keyed plan is still held to its own site', async () => {- protocolState.activePlan = null;- const hostile = plan('https://evil.example', 'https://web.fluxer.app');- protocolState.cachedPlans = new Map([[hostile.instanceKey, hostile]]);- await assert.rejects(authenticate({instanceKey: hostile.instanceKey}), /UntrustedPasskeyCeremonyOriginError/u);- assert.deepEqual(ceremonyState.calls, []);- protocolState.cachedPlans = new Map();- });-});diff --git a/fluxer_desktop/src/main/PlatformInfo.test.mjs b/fluxer_desktop/src/main/PlatformInfo.test.mjsdeleted file mode 100644index ff7674f45..000000000--- a/fluxer_desktop/src/main/PlatformInfo.test.mjs+++ /dev/null@@ -1,156 +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('./PlatformInfo.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadPlatformInfo(platform = 'win32', {nativeGpu = null, electronGpu = null, gpuInfoRequests = []} = {}) {- const app = {- getVersion: () => '0.0.0-test',- getGPUInfo: async (infoType) => {- gpuInfoRequests.push(infoType);- return {gpuDevice: electronGpu ?? []};- },- commandLine: {- getSwitchValue: () => '',- hasSwitch: () => true,- },- };- const osModule = {- arch: () => 'x64',- release: () => '10.0.26100',- };-- function requireStub(specifier) {- if (specifier === 'node:module') {- return {- createRequire: () => (moduleSpecifier) => {- if (moduleSpecifier === '@fluxer/platform-info' && nativeGpu) {- return {getGpuInfo: () => ({devices: nativeGpu, source: 'dxgi'}), loadError: null};- }- throw new Error(`Unexpected native module require: ${moduleSpecifier}`);- },- };- }- if (specifier === 'node:os') return osModule;- if (specifier === 'electron') return {app};- if (specifier === '@electron/common/BuildChannel') return {BUILD_CHANNEL: 'stable'};- if (specifier === '@electron/common/UserDataPath') return {isPortableMode: () => false};- if (specifier === '@electron/main/LinuxSandbox') {- return {getFlatpakAppId: () => null, isFlatpakRuntime: () => false};- }- if (specifier === '@electron/main/LinuxSession') return {isWaylandSession: () => false};- throw new Error(`Unexpected import: ${specifier}`);- }-- const module = {exports: {}};- const context = vm.createContext({- require: requireStub,- module,- exports: module.exports,- process: {- ...process,- platform,- env: {},- versions: {...process.versions},- getSystemVersion: () => '10.0.26100',- },- console,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--describe('PlatformInfo Chromium runtime diagnostics', () => {- test('never reports Media Foundation H.264 switches that Chromium no longer has', async () => {- const module = loadPlatformInfo('win32');-- const info = await module.getDesktopInfo({nativeProbes: false});-- const switches = [...info.chromiumRuntime.switches];-- assert.deepEqual(- switches.filter((name) => name.startsWith('enable-h264-mf')),- [],- );- assert.equal(switches.includes('disable_accelerated_h264_encode'), true);- });-});--describe('PlatformInfo dual-GPU merge', () => {- const NVIDIA = {vendorId: 0x10de, deviceId: 0x2684, deviceString: 'NVIDIA GeForce RTX 4090 Laptop GPU'};- const INTEL = {vendorId: 0x8086, deviceId: 0x9bc4, deviceString: 'Intel(R) UHD Graphics'};-- test('keeps the adapter Chromium reports active and drops the native probe active flag', async () => {- const gpuInfoRequests = [];- const module = loadPlatformInfo('win32', {- gpuInfoRequests,- nativeGpu: [- {...NVIDIA, active: true, dedicatedVideoMemory: 16 * 1024 * 1024 * 1024, source: 'dxgi'},- {...INTEL, active: false, dedicatedVideoMemory: 0, source: 'dxgi'},- ],- electronGpu: [- {...INTEL, active: true},- {...NVIDIA, active: false},- ],- });-- const info = await module.getGpuInfo();- const byVendor = new Map(info.devices.map((device) => [device.vendorId, device]));-- assert.deepEqual(gpuInfoRequests, ['complete']);- assert.equal(byVendor.get(INTEL.vendorId).active, true);- assert.equal(byVendor.get(NVIDIA.vendorId).active, false);- assert.equal(byVendor.get(NVIDIA.vendorId).dedicatedVideoMemory, 16 * 1024 * 1024 * 1024);- });-- test('leaves a native adapter Chromium never lists inactive', async () => {- const module = loadPlatformInfo('win32', {- nativeGpu: [- {...NVIDIA, active: true, dedicatedVideoMemory: 16 * 1024 * 1024 * 1024, source: 'dxgi'},- {...INTEL, active: false, dedicatedVideoMemory: 0, source: 'dxgi'},- ],- electronGpu: [{...INTEL, active: true}],- });-- const info = await module.getGpuInfo();- const byVendor = new Map(info.devices.map((device) => [device.vendorId, device]));-- assert.equal(byVendor.get(NVIDIA.vendorId).active, false);- assert.equal(byVendor.get(INTEL.vendorId).active, true);- });-- test('keeps the native details when Electron reports the dedicated adapter active', async () => {- const module = loadPlatformInfo('win32', {- nativeGpu: [- {...NVIDIA, active: true, dedicatedVideoMemory: 16 * 1024 * 1024 * 1024, source: 'dxgi'},- {...INTEL, active: false, dedicatedVideoMemory: 0, source: 'dxgi'},- ],- electronGpu: [- {...NVIDIA, active: true},- {...INTEL, active: false},- ],- });-- const info = await module.getGpuInfo();- const byVendor = new Map(info.devices.map((device) => [device.vendorId, device]));-- assert.equal(byVendor.get(NVIDIA.vendorId).active, true);- assert.equal(byVendor.get(INTEL.vendorId).active, false);- });-});diff --git a/fluxer_desktop/src/main/SplashBundleOwnership.test.mjs b/fluxer_desktop/src/main/SplashBundleOwnership.test.mjsdeleted file mode 100644index 577d44308..000000000--- a/fluxer_desktop/src/main/SplashBundleOwnership.test.mjs+++ /dev/null@@ -1,106 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {existsSync, readFileSync, statSync} from 'node:fs';-import path from 'node:path';-import {describe, test} from 'node:test';-import {fileURLToPath} from 'node:url';--const SRC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');-const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];-const TYPE_ONLY_STATEMENT = /\b(?:import|export)\s+type\b[\s\S]*?from\s*'[^']*';/g;-const RUNTIME_SPECIFIER = /(?:from|import\s*\()\s*'([^']+)'/g;--const BOOTSTRAP_ENTRY = 'main/Bootstrap.ts';-const MAIN_APP_ENTRY = 'main/index.ts';-const SPLASH_MODULE = 'main/SplashWindow.ts';--function resolveSourceModule(absolutePath) {- if (existsSync(absolutePath) && statSync(absolutePath).isFile()) {- return absolutePath;- }- for (const extension of SOURCE_EXTENSIONS) {- if (existsSync(absolutePath + extension)) {- return absolutePath + extension;- }- }- for (const extension of SOURCE_EXTENSIONS) {- const indexPath = path.join(absolutePath, `index${extension}`);- if (existsSync(indexPath)) {- return indexPath;- }- }- return null;-}--function resolveSpecifier(specifier, fromRelativePath) {- if (specifier.startsWith('@electron/')) {- return resolveSourceModule(path.join(SRC_DIR, specifier.slice('@electron/'.length)));- }- if (specifier.startsWith('.')) {- return resolveSourceModule(path.resolve(SRC_DIR, path.dirname(fromRelativePath), specifier));- }- return null;-}--function readRuntimeEdges(relativePath) {- const source = readFileSync(path.join(SRC_DIR, relativePath), 'utf8').replace(TYPE_ONLY_STATEMENT, '');- const edges = new Set();- for (const match of source.matchAll(RUNTIME_SPECIFIER)) {- const resolved = resolveSpecifier(match[1], relativePath);- if (resolved != null) {- edges.add(path.relative(SRC_DIR, resolved));- }- }- return edges;-}--function findImportChain(entryRelativePath, targetRelativePath) {- const parents = new Map([[entryRelativePath, null]]);- const queue = [entryRelativePath];- while (queue.length > 0) {- const current = queue.shift();- if (current === targetRelativePath) {- const chain = [];- for (let step = current; step != null; step = parents.get(step)) {- chain.unshift(step);- }- return chain;- }- for (const edge of readRuntimeEdges(current)) {- if (!parents.has(edge)) {- parents.set(edge, current);- queue.push(edge);- }- }- }- return null;-}--describe('splash bundle ownership', () => {- test('the bootstrap bundle owns the splash', () => {- assert.notEqual(- findImportChain(BOOTSTRAP_ENTRY, SPLASH_MODULE),- null,- 'Bootstrap must still reach the splash, otherwise this walker proves nothing about the bundle that must not reach it.',- );- });-- test('the main app bundle never reaches the splash', () => {- const chain = findImportChain(MAIN_APP_ENTRY, SPLASH_MODULE);- assert.equal(- chain,- null,- `scripts/build.mjs emits dist/main/index.js and dist/main/MainApp.js as two independent bundles, so a module reachable from both is instantiated twice with two copies of its module state. The splash keeps mutable state, so the second copy would take writes that no window ever reads and silently do nothing, which is the defect the ModuleBootHandoff symbol exists to prevent. Main talks to the splash through ModuleBootHandoff instead. Reached it through: ${chain?.join(' -> ')}`,- );- });-- test('the shell update decision carries no splash presentation', () => {- const edges = readRuntimeEdges('main/ShellUpdateCapability.ts');- assert.equal(- edges.has(SPLASH_MODULE),- false,- 'Updater.ts imports this module into the main app bundle, so a splash import here drags the whole splash across the bundle boundary. The presentation is in ShellUpdateSplash.ts.',- );- });-});diff --git a/fluxer_desktop/src/main/SplashDownloadDiagnostics.test.mjs b/fluxer_desktop/src/main/SplashDownloadDiagnostics.test.mjsdeleted file mode 100644index 8268ed66a..000000000--- a/fluxer_desktop/src/main/SplashDownloadDiagnostics.test.mjs+++ /dev/null@@ -1,58 +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 {buildSplashDiagnosticsText, redactDiagnosticText} = await import('@electron/main/SplashDiagnostics');--function diagnosticsInput(overrides = {}) {- return {- generatedAt: Date.UTC(2026, 9, 8, 1, 0, 0),- splashOpenedAt: Date.UTC(2026, 9, 8, 0, 59, 0),- appVersion: '2026.1008.1',- channel: 'canary',- platform: 'win32',- arch: 'x64',- osVersion: '10.0.26100',- electronVersion: '44.4.1',- logsPath: 'C:\\Users\\u\\AppData\\Roaming\\fluxer_desktop_canary\\logs',- userDataPath: 'C:\\Users\\u\\AppData\\Roaming\\fluxercanary',- packageOrigin: 'https://pkgs.fluxer.com',- proxyRoute: 'PROXY 10.0.0.2:3128',- splashStatus: 'download-stalled',- updaterStatus: 'retry-wait',- pendingModule: 'fluxer_renderer',- receivedBytes: 42000000,- totalBytes: 146684915,- bytesPerSecond: 3100000,- committed: {fluxer_sourcemaps: 'b'.repeat(64), fluxer_renderer: 'a'.repeat(64)},- lastError: 'package download stalled for 30000ms',- lastErrorAt: Date.UTC(2026, 9, 8, 0, 59, 40),- ...overrides,- };-}--describe('splash diagnostics', () => {- test('never carries query values or credential-looking pairs', () => {- const text = buildSplashDiagnosticsText(- diagnosticsInput({- lastError: 'failed to reach https://pkgs.fluxer.com/x?token=abc123&sig=zzz: authorization: Bearer secretvalue',- proxyRoute: 'PROXY user:pass@proxy:8080',- }),- );- assert.ok(!text.includes('abc123'));- assert.ok(!text.includes('zzz'));- assert.ok(!text.includes('secretvalue'));- assert.ok(!text.includes('user:pass'));- assert.ok(text.includes('?token=…&sig=…'));- assert.ok(text.includes('Proxy route: PROXY …@proxy:8080'));- });-- test('redaction leaves plain diagnostic text alone', () => {- assert.equal(- redactDiagnosticText('Package origin: https://pkgs.fluxer.com'),- 'Package origin: https://pkgs.fluxer.com',- );- });-});diff --git a/fluxer_desktop/src/main/SplashWindow.test.mjs b/fluxer_desktop/src/main/SplashWindow.test.mjsdeleted file mode 100644index 385d16f92..000000000--- a/fluxer_desktop/src/main/SplashWindow.test.mjs+++ /dev/null@@ -1,1360 +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 {fileURLToPath} from 'node:url';-import vm from 'node:vm';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--const MODULE_URL = new URL('./SplashWindow.ts', import.meta.url).href;-const PRELOAD_PATH = fileURLToPath(new URL('../preload/splash.cjs', import.meta.url));-const PRELOAD_SOURCE = readFileSync(PRELOAD_PATH, 'utf8');--const quitCalls = [];-const ipcRegistrations = [];--class FakeWebContents {- constructor() {- this.listeners = new Map();- this.sent = [];- this.windowOpenHandler = null;- this.destroyed = false;- }-- on(eventName, listener) {- const existing = this.listeners.get(eventName) ?? [];- existing.push(listener);- this.listeners.set(eventName, existing);- }-- setWindowOpenHandler(handler) {- this.windowOpenHandler = handler;- }-- isDestroyed() {- return this.destroyed;- }-- send(channel, payload) {- this.sent.push({channel, payload});- }-- emit(eventName, ...args) {- for (const listener of this.listeners.get(eventName) ?? []) {- listener(...args);- }- }-}--class FakeBrowserWindow {- static last = null;-- constructor(options) {- FakeBrowserWindow.last = this;- this.options = options;- this.webContents = new FakeWebContents();- this.listeners = new Map();- this.destroyed = false;- this.visible = false;- this.shownInactive = 0;- this.alwaysOnTop = false;- this.skipTaskbar = false;- this.minimized = false;- this.focusCount = 0;- this.loadedUrls = [];- }-- on(eventName, listener) {- const existing = this.listeners.get(eventName) ?? [];- existing.push(listener);- this.listeners.set(eventName, existing);- }-- once(eventName, listener) {- this.on(eventName, listener);- }-- isDestroyed() {- return this.destroyed;- }-- isVisible() {- return this.visible;- }-- show() {- this.visible = true;- }-- focus() {- this.focusCount += 1;- }-- isMinimized() {- return this.minimized;- }-- restore() {- this.minimized = false;- }-- showInactive() {- this.visible = true;- this.shownInactive += 1;- }-- hide() {- this.visible = false;- }-- setSkipTaskbar(value) {- this.skipTaskbar = value;- }-- setAlwaysOnTop(value) {- this.alwaysOnTop = value;- }-- close() {- if (this.destroyed) return;- this.destroyed = true;- this.webContents.destroyed = true;- this.emit('closed');- }-- destroy() {- this.close();- }-- loadURL(url) {- this.loadedUrls.push(url);- return Promise.resolve();- }-- emit(eventName, ...args) {- for (const listener of this.listeners.get(eventName) ?? []) {- listener(...args);- }- }-}--const nativeTheme = {themeSource: 'system'};--installElectronStub({- app: {- quit: () => {- quitCalls.push('quit');- },- },- BrowserWindow: FakeBrowserWindow,- nativeTheme,- ipcMain: {- on: (channel, handler) => {- ipcRegistrations.push({channel, handler});- },- },-});--function emitIpc(channel, event, payload) {- for (const registration of ipcRegistrations) {- if (registration.channel === channel) {- registration.handler(event, payload);- }- }-}--async function loadSplashWindow(instance) {- return await import(`${MODULE_URL}?instance=${instance}`);-}--function withPlatform(platform, run) {- const original = Object.getOwnPropertyDescriptor(process, 'platform');- Object.defineProperty(process, 'platform', {value: platform, configurable: true});- try {- run();- } finally {- Object.defineProperty(process, 'platform', original);- }-}--function withPlatformResult(platform, run) {- let result;- withPlatform(platform, () => {- result = run();- });- return result;-}--function withCapturedTimers(run) {- 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;- }- };- let result;- try {- result = run();- } finally {- globalThis.setTimeout = originalSetTimeout;- globalThis.clearTimeout = originalClearTimeout;- }- return {result, timers};-}--function fireTimers(timers) {- for (const timer of timers) {- if (!timer.cleared) {- timer.callback();- }- }-}--function withPlatformTimers(platform, run) {- const captured = withCapturedTimers(() => withPlatformResult(platform, run));- return {- result: captured.result,- timers: captured.timers,- flush: () => {- withPlatform(platform, () => {- fireTimers(captured.timers);- });- },- };-}--describe('splash launch latch', () => {- test('quits on a non-darwin close only while the latch is unset', async () => {- const {shouldQuitOnSplashClosed} = await loadSplashWindow('latch-decision');-- assert.equal(shouldQuitOnSplashClosed('win32', false), true);- assert.equal(shouldQuitOnSplashClosed('linux', false), true);- assert.equal(shouldQuitOnSplashClosed('win32', true), false);- assert.equal(shouldQuitOnSplashClosed('linux', true), false);- assert.equal(shouldQuitOnSplashClosed('darwin', false), false);- assert.equal(shouldQuitOnSplashClosed('darwin', true), false);- });-- test('a user close before launch quits the app on win32', async () => {- const {openSplashWindow} = await loadSplashWindow('latch-unset');- quitCalls.length = 0;-- withPlatform('win32', () => {- const window = openSplashWindow();- window.emit('closed');- });-- assert.deepEqual(quitCalls, ['quit']);- });-- test('markSplashLaunching stops the handoff close from quitting the app', async () => {- const {closeSplashWindow, markSplashLaunching, openSplashWindow} = await loadSplashWindow('latch-set');- quitCalls.length = 0;-- const {result: window, flush} = withPlatformTimers('win32', () => {- const opened = openSplashWindow();- markSplashLaunching();- closeSplashWindow();- return opened;- });- flush();-- assert.equal(window.destroyed, true);- assert.deepEqual(quitCalls, []);- });-- test('a handoff close without the latch still quits, so an aborted boot never leaves a headless process', async () => {- const {closeSplashWindow, openSplashWindow} = await loadSplashWindow('latch-abort');- quitCalls.length = 0;-- const {flush} = withPlatformTimers('linux', () => {- openSplashWindow();- closeSplashWindow();- });- flush();-- assert.deepEqual(quitCalls, ['quit']);- });-- test('darwin never quits from the splash close handler', async () => {- const {closeSplashWindow, openSplashWindow} = await loadSplashWindow('latch-darwin');- quitCalls.length = 0;-- const {flush} = withPlatformTimers('darwin', () => {- openSplashWindow();- closeSplashWindow();- });- flush();-- assert.deepEqual(quitCalls, []);- });-});--describe('splash window configuration', () => {- test('opens frameless, sandboxed and hidden, loaded from file://', async () => {- const {openSplashWindow} = await loadSplashWindow('configuration');-- const window = withPlatformResult('darwin', () => openSplashWindow());-- assert.equal(window.options.width, 300);- assert.equal(window.options.height, 300);- assert.equal(window.options.frame, false);- assert.equal(window.options.resizable, false);- assert.equal(window.options.center, true);- assert.equal(window.options.show, false);- assert.equal(window.options.transparent, false);- assert.equal(window.options.webPreferences.contextIsolation, true);- assert.equal(window.options.webPreferences.sandbox, true);- assert.equal(window.options.webPreferences.nodeIntegration, false);- assert.match(window.options.webPreferences.preload.replaceAll('\\', '/'), /\/preload\/splash\.cjs$/);- assert.equal(window.loadedUrls.length, 1);- assert.match(window.loadedUrls[0], /^file:\/\//);- assert.match(window.loadedUrls[0], /\/splash\/index\.html$/);- });-- test('blocks navigation and denies every window open', async () => {- const {openSplashWindow} = await loadSplashWindow('hardening');-- const window = withPlatformResult('darwin', () => openSplashWindow());- let prevented = false;- window.webContents.emit('will-navigate', {- preventDefault: () => {- prevented = true;- },- });-- assert.equal(prevented, true);- assert.deepEqual(window.webContents.windowOpenHandler({url: 'https://fluxer.app'}), {action: 'deny'});- });-- test('stays hidden until the preload reports ready, then shows without stealing focus', async () => {- const {openSplashWindow} = await loadSplashWindow('show-on-ready');-- const window = withPlatformResult('darwin', () => openSplashWindow());- assert.equal(window.visible, false);-- window.emit('ready-to-show');- assert.equal(window.visible, false);-- emitIpc('desktop-splash:ready', {sender: window.webContents});-- assert.equal(window.visible, true);- assert.equal(window.shownInactive, 1);- });-- test('a preloaded splash loads hidden, stays hidden once ready, and reveals on demand', async () => {- const {preloadSplashWindow, revealPreloadedSplashWindow} = await loadSplashWindow('preload');-- const {timers} = withPlatformTimers('darwin', () => preloadSplashWindow());- const splash = FakeBrowserWindow.last;- assert.equal(timers.length, 0);- assert.equal(splash.visible, false);- assert.equal(splash.skipTaskbar, true);- assert.equal(revealPreloadedSplashWindow(), null);-- emitIpc('desktop-splash:ready', {sender: splash.webContents});- assert.equal(splash.visible, false);-- assert.equal(revealPreloadedSplashWindow(), splash);- assert.equal(splash.visible, true);- assert.equal(splash.skipTaskbar, false);- assert.equal(revealPreloadedSplashWindow(), null);- });-- test('a preload that never reports ready still gets shown by the watchdog', async () => {- const {openSplashWindow, SPLASH_READY_WATCHDOG_MS} = await loadSplashWindow('show-watchdog');-- const {result: window, timers, flush} = withPlatformTimers('darwin', () => openSplashWindow());-- assert.equal(window.visible, false);- assert.equal(timers.length, 1);- assert.equal(timers[0].delayMs, SPLASH_READY_WATCHDOG_MS);-- flush();-- assert.equal(window.visible, true);- assert.equal(window.shownInactive, 1);- });-- test('the ready handler disarms the watchdog so the window is never shown twice', async () => {- const {openSplashWindow} = await loadSplashWindow('watchdog-disarm');-- const {- result: window,- timers,- flush,- } = withPlatformTimers('darwin', () => {- const opened = openSplashWindow();- emitIpc('desktop-splash:ready', {sender: opened.webContents});- return opened;- });-- assert.equal(timers[0].cleared, true);-- flush();-- assert.equal(window.shownInactive, 1);- });-- test('reports a dead preload and a failed document load instead of leaving a black rectangle', async () => {- const {openSplashWindow} = await loadSplashWindow('diagnostics');-- const window = withPlatformResult('darwin', () => openSplashWindow());-- assert.ok(window.webContents.listeners.has('did-fail-load'));- assert.ok(window.webContents.listeners.has('preload-error'));- assert.ok(window.webContents.listeners.has('console-message'));-- window.webContents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///splash/index.html');- window.webContents.emit('preload-error', {}, '/preload/splash.cjs', new Error('boom'));- window.webContents.emit('console-message', {level: 'error', message: 'boom', lineNumber: 1});- });-});--describe('splash window focus', () => {- test('a launch forwarded while the splash is blocked restores, shows and raises it', async () => {- const {focusSplashWindow, openSplashWindow} = await loadSplashWindow('focus-blocked');- const window = withPlatformResult('darwin', () => openSplashWindow());- window.visible = false;- window.minimized = true;-- focusSplashWindow();-- assert.equal(window.minimized, false);- assert.equal(window.visible, true);- assert.equal(- window.focusCount,- 1,- 'The blocked update paths never launch a main window, so raising the splash is the only answer a relaunch can get.',- );- });-});--describe('splash window teardown', () => {- test('gives up the taskbar slot at once and only closes after the handoff gap', async () => {- const {closeSplashWindow, openSplashWindow, SPLASH_CLOSE_DELAY_MS, markSplashLaunching} =- await loadSplashWindow('teardown-order');-- const {- result: window,- timers,- flush,- } = withPlatformTimers('darwin', () => {- const opened = openSplashWindow();- markSplashLaunching();- closeSplashWindow();- return opened;- });-- assert.equal(window.skipTaskbar, true);- assert.equal(window.destroyed, false);- assert.equal(timers.filter((timer) => !timer.cleared).length, 1);- assert.equal(timers.at(-1).delayMs, SPLASH_CLOSE_DELAY_MS);-- flush();-- assert.equal(window.visible, false);- assert.equal(window.destroyed, true);- });-- test('a window that dies inside the handoff gap is never touched again', async () => {- const {closeSplashWindow, openSplashWindow, markSplashLaunching} = await loadSplashWindow('teardown-race');-- const {result: window, flush} = withPlatformTimers('darwin', () => {- const opened = openSplashWindow();- markSplashLaunching();- closeSplashWindow();- return opened;- });- window.destroy();- window.hide = () => {- throw new Error('a destroyed window must never be hidden');- };-- flush();- });-});--describe('splash state serialisation', () => {- test('truncates counters and clamps progress', async () => {- const {serializeSplashState, SplashStatus} = await loadSplashWindow('serialise-clean');-- assert.deepEqual(- serializeSplashState({- status: SplashStatus.DOWNLOADING_UPDATES,- current: 3.9,- total: 7,- progress: 42.5,- }),- {- status: 'downloading-updates',- current: 3,- total: 7,- progress: 42.5,- seconds: null,- receivedBytes: null,- totalBytes: null,- bytesPerSecond: null,- action: null,- message: null,- },- );- });-- test('drops values that cannot cross the IPC boundary as numbers', async () => {- const {serializeSplashState, SplashStatus} = await loadSplashWindow('serialise-junk');-- assert.deepEqual(- serializeSplashState({- status: SplashStatus.UPDATE_FAILURE,- current: Number.NaN,- total: Number.POSITIVE_INFINITY,- progress: -12,- seconds: -4,- }),- {- status: 'update-failure',- current: null,- total: null,- progress: 0,- seconds: 0,- receivedBytes: null,- totalBytes: null,- bytesPerSecond: null,- action: null,- message: null,- },- );- });-- test('clamps progress to 100', async () => {- const {serializeSplashState, SplashStatus} = await loadSplashWindow('serialise-clamp');-- assert.equal(serializeSplashState({status: SplashStatus.INSTALLING_UPDATES, progress: 480}).progress, 100);- });-- test('falls back to checking for updates on an unknown status', async () => {- const {serializeSplashState} = await loadSplashWindow('serialise-unknown');-- assert.equal(serializeSplashState({status: 'not-a-splash-status'}).status, 'checking-for-updates');- });-- test('carries every shipped action through and drops one the renderer could not route', async () => {- const {serializeSplashState, SplashAction, SplashStatus} = await loadSplashWindow('serialise-action');- const actionFor = (action) => serializeSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE, action}).action;-- assert.deepEqual(actionFor(SplashAction.RETRY), {kind: 'retry', label: 'Retry now'});- assert.deepEqual(actionFor(SplashAction.DOWNLOAD), {kind: 'download', label: 'Download update'});- assert.deepEqual(actionFor(SplashAction.QUIT), {kind: 'quit', label: 'Quit'});- assert.equal(actionFor({kind: 'launch-anyway', label: 'Launch anyway'}), null);- assert.equal(actionFor({kind: 'retry', label: ' '}), null);- assert.equal(actionFor({kind: 'retry', label: 42}), null);- assert.equal(actionFor(undefined), null);- assert.equal(actionFor({kind: 'retry', label: 'l'.repeat(200)}).label.length, 48);- });-- test('only a state that carries a way out counts as an affordance', async () => {- const {hasSplashAffordance, serializeSplashState, SplashAction, SplashStatus} =- await loadSplashWindow('affordance-predicate');-- assert.equal(hasSplashAffordance(serializeSplashState({status: SplashStatus.CHECKING_FOR_UPDATES})), false);- assert.equal(hasSplashAffordance(serializeSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE})), false);- assert.equal(- hasSplashAffordance(serializeSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE, action: SplashAction.QUIT})),- true,- );- });-});--describe('splash affordance latch', () => {- test('a state with no way out can never erase one that has one', async () => {- const {openSplashWindow, setSplashState, SplashAction, SplashStatus} = await loadSplashWindow('latch-affordance');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE, action: SplashAction.DOWNLOAD});- window.webContents.sent.length = 0;-- setSplashState({status: SplashStatus.CHECKING_FOR_UPDATES});- setSplashState({status: SplashStatus.DOWNLOADING_UPDATES, current: 1, total: 2, progress: 10});-- assert.deepEqual(window.webContents.sent, []);- });-- test('a state that carries its own way out replaces the armed one', async () => {- const {openSplashWindow, setSplashState, SplashAction, SplashStatus} = await loadSplashWindow('latch-replace');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE, action: SplashAction.DOWNLOAD});- window.webContents.sent.length = 0;-- setSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE_MANAGED, action: SplashAction.QUIT});-- assert.equal(window.webContents.sent.length, 1);- assert.deepEqual(window.webContents.sent[0].payload.action, {kind: 'quit', label: 'Quit'});- });-- test('the shell self update paints its progress because the updater block carries no affordance', async () => {- const {openSplashWindow, setSplashState, SplashStatus} = await loadSplashWindow('latch-self-update');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE});- setSplashState({status: SplashStatus.SHELL_UPDATE_DOWNLOADING, progress: 42});- setSplashState({status: SplashStatus.SHELL_UPDATE_RESTARTING});-- assert.deepEqual(- window.webContents.sent.map((entry) => entry.payload.status),- ['blocked-shell-update', 'shell-update-downloading', 'shell-update-restarting'],- );- });-- test('every state that latches is also raised above the windows that would bury it', async () => {- const {openSplashWindow, setSplashState, SplashAction, SplashStatus} = await loadSplashWindow('latch-on-top');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.CHECKING_FOR_UPDATES});- assert.equal(window.alwaysOnTop, false);-- setSplashState({status: SplashStatus.BLOCKED_UNSUPPORTED_BUILD, action: SplashAction.QUIT});- assert.equal(window.alwaysOnTop, true);- });-- test('releasing the latch lets progress paint again and lowers the window', async () => {- const {openSplashWindow, releaseSplashAffordance, setSplashState, SplashAction, SplashStatus} =- await loadSplashWindow('latch-released');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.BLOCKED_UPDATE_UNREACHABLE, action: SplashAction.RETRY});- setSplashState({status: SplashStatus.CHECKING_FOR_UPDATES});- assert.equal(window.webContents.sent.at(-1).payload.status, 'blocked-update-unreachable');- assert.equal(window.alwaysOnTop, true);-- releaseSplashAffordance();- setSplashState({status: SplashStatus.DOWNLOADING_UPDATES, current: 1, total: 2, progress: 10});-- assert.equal(window.alwaysOnTop, false);- assert.equal(window.webContents.sent.at(-1).payload.status, 'downloading-updates');- assert.equal(window.webContents.sent.at(-1).payload.action, null);- });-- test('closing the splash releases the latch so a re-opened splash is not born blocked', async () => {- const {closeSplashWindow, openSplashWindow, setSplashState, SplashAction, SplashStatus} =- await loadSplashWindow('latch-release');-- const {result: first, flush} = withPlatformTimers('darwin', () => {- const opened = openSplashWindow();- setSplashState({status: SplashStatus.BLOCKED_SHELL_UPDATE, action: SplashAction.DOWNLOAD});- closeSplashWindow();- return opened;- });- flush();- assert.equal(first.destroyed, true);-- const second = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.CHECKING_FOR_UPDATES});-- assert.equal(second.webContents.sent.at(-1).payload.status, 'checking-for-updates');- });-});--describe('splash IPC', () => {- test('sends the serialised state on desktop-splash:state', async () => {- const {openSplashWindow, setSplashState, SplashStatus} = await loadSplashWindow('ipc-state');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.DOWNLOADING_UPDATES, current: 2, total: 5, progress: 40});-- assert.deepEqual(window.webContents.sent, [- {- channel: 'desktop-splash:state',- payload: {- status: 'downloading-updates',- current: 2,- total: 5,- progress: 40,- seconds: null,- receivedBytes: null,- totalBytes: null,- bytesPerSecond: null,- action: null,- message: null,- },- },- ]);- });-- test('replays the last state and notifies listeners when the splash reports ready', async () => {- const {onSplashReady, openSplashWindow, setSplashState, SplashStatus} = await loadSplashWindow('ipc-ready');-- const window = withPlatformResult('darwin', () => openSplashWindow());- setSplashState({status: SplashStatus.VERIFYING});- window.webContents.sent.length = 0;- let readyCount = 0;- onSplashReady(() => {- readyCount += 1;- });- emitIpc('desktop-splash:ready', {sender: window.webContents});-- assert.equal(readyCount, 1);- assert.deepEqual(window.webContents.sent, [- {- channel: 'desktop-splash:state',- payload: {- status: 'verifying',- current: null,- total: null,- progress: null,- seconds: null,- receivedBytes: null,- totalBytes: null,- bytesPerSecond: null,- action: null,- message: null,- },- },- ]);- });-- test('notifies retry and quit listeners only for the splash sender', async () => {- const {onSplashQuit, onSplashRetry, openSplashWindow} = await loadSplashWindow('ipc-sender');-- const window = withPlatformResult('darwin', () => openSplashWindow());- let retryCount = 0;- let quitCount = 0;- onSplashRetry(() => {- retryCount += 1;- });- onSplashQuit(() => {- quitCount += 1;- });- emitIpc('desktop-splash:retry-now', {sender: new FakeWebContents()});- emitIpc('desktop-splash:quit', {sender: new FakeWebContents()});-- assert.equal(retryCount, 0);- assert.equal(quitCount, 0);-- emitIpc('desktop-splash:retry-now', {sender: window.webContents});- emitIpc('desktop-splash:quit', {sender: window.webContents});-- assert.equal(retryCount, 1);- assert.equal(quitCount, 1);- });-- test('notifies network listeners when the splash sees the network return, and only for the splash sender', async () => {- const {onSplashNetworkOnline, openSplashWindow} = await loadSplashWindow('ipc-network-online');-- const window = withPlatformResult('darwin', () => openSplashWindow());- let onlineCount = 0;- onSplashNetworkOnline(() => {- onlineCount += 1;- });- emitIpc('desktop-splash:network-online', {sender: new FakeWebContents()});-- assert.equal(onlineCount, 0);-- emitIpc('desktop-splash:network-online', {sender: window.webContents});-- assert.equal(onlineCount, 1);- });-- test('notifies download listeners only for the splash sender and hands them nothing from the payload', async () => {- const {onSplashOpenDownload, openSplashWindow} = await loadSplashWindow('ipc-open-download');-- const window = withPlatformResult('darwin', () => openSplashWindow());- const calls = [];- onSplashOpenDownload((...args) => {- calls.push(args);- });- emitIpc('desktop-splash:open-download', {sender: new FakeWebContents()});-- assert.deepEqual(calls, []);-- emitIpc('desktop-splash:open-download', {sender: window.webContents});- emitIpc('desktop-splash:open-download', {sender: window.webContents}, 'https://evil.example');-- assert.deepEqual(calls, [[], []]);- });-- test('stops sending state once the splash is closed', async () => {- const {closeSplashWindow, openSplashWindow, setSplashState, SplashStatus} = await loadSplashWindow('ipc-closed');-- const {result: window} = withPlatformTimers('darwin', () => {- const opened = openSplashWindow();- closeSplashWindow();- return opened;- });- setSplashState({status: SplashStatus.LAUNCHING});-- assert.deepEqual(window.webContents.sent, []);- });-- test('stops sending state to a window whose web contents died under it', async () => {- const {openSplashWindow, setSplashState, SplashStatus} = await loadSplashWindow('ipc-dead-contents');-- const window = withPlatformResult('darwin', () => openSplashWindow());- window.webContents.destroyed = true;- setSplashState({status: SplashStatus.LAUNCHING});-- assert.deepEqual(window.webContents.sent, []);- });-});--class StubClassList {- constructor(node) {- this.node = node;- }-- contains(name) {- return this.node.className- .split(' ')- .filter((part) => part.length > 0)- .includes(name);- }-- add(name) {- if (this.contains(name)) return;- this.node.className = `${this.node.className} ${name}`.trim();- }-- remove(name) {- this.node.className = this.node.className- .split(' ')- .filter((part) => part !== name && part.length > 0)- .join(' ');- }-}--class StubNode {- constructor(tagName) {- this.tagName = String(tagName).toLowerCase();- this.className = '';- this.id = '';- this.value = '';- this.style = {};- this.attributes = new Map();- this.children = [];- this.parent = null;- this.listeners = new Map();- this.text = '';- this.classList = new StubClassList(this);- this.replaceChildrenCalls = 0;- this.decodeCalls = 0;- }-- decode() {- this.decodeCalls += 1;- return Promise.resolve();- }-- get textContent() {- return this.text + this.children.map((child) => child.textContent).join('');- }-- set textContent(value) {- for (const child of this.children) {- child.parent = null;- }- this.children = [];- this.text = String(value);- }-- setAttribute(name, value) {- this.attributes.set(name, String(value));- }-- getAttribute(name) {- return this.attributes.get(name) ?? null;- }-- appendChild(node) {- node.parent = this;- this.children.push(node);- return node;- }-- replaceChildren(...nodes) {- this.replaceChildrenCalls += 1;- for (const child of this.children) {- child.parent = null;- }- this.children = [];- for (const node of nodes) {- this.appendChild(node);- }- }-- replaceWith(node) {- const parent = this.parent;- if (parent == null) return;- const index = parent.children.indexOf(this);- if (index < 0) return;- parent.children[index] = node;- node.parent = parent;- this.parent = null;- }-- addEventListener(eventName, listener) {- const existing = this.listeners.get(eventName) ?? [];- existing.push(listener);- this.listeners.set(eventName, existing);- }-- dispatch(eventName) {- for (const listener of this.listeners.get(eventName) ?? []) {- listener();- }- }-- matches(selector) {- return selector- .split(',')- .map((part) => part.trim())- .filter((part) => part.length > 0)- .some((part) => {- if (part.startsWith('.')) return this.classList.contains(part.slice(1));- if (part.startsWith('#')) return this.id === part.slice(1);- return this.tagName === part.toLowerCase();- });- }-- descendants() {- const found = [];- for (const child of this.children) {- found.push(child, ...child.descendants());- }- return found;- }-- querySelector(selector) {- return this.descendants().find((node) => node.matches(selector)) ?? null;- }-}--const {serializeSplashState: serializePreloadState} = await loadSplashWindow('preload-state-producer');--function createPreloadHarness(options = {}) {- const sent = [];- const ipcListeners = new Map();- const windowListeners = new Map();- const intervals = [];- const frames = [];- const timeouts = [];- const fontLoads = [];- const mount = new StubNode('div');- mount.id = 'splash-mount';- const document = {- getElementById: (id) => (mount.id === id ? mount : (mount.querySelector(`#${id}`) ?? null)),- createElement: (tagName) => new StubNode(tagName),- fonts: {- load: (face) => {- fontLoads.push(face);- return Promise.resolve([]);- },- },- };- const context = vm.createContext({- document,- require: (specifier) => {- if (specifier !== 'electron') throw new Error(`The splash preload must not require ${specifier}`);- return {- ipcRenderer: {- on: (channel, listener) => {- ipcListeners.set(channel, listener);- },- send: (channel, payload) => {- sent.push({channel, payload});- },- },- };- },- setInterval: (callback, delayMs) => {- const timer = {id: intervals.length + 1, callback, delayMs, cleared: false};- intervals.push(timer);- return timer.id;- },- clearInterval: (id) => {- const timer = intervals.find((entry) => entry.id === id);- if (timer != null) {- timer.cleared = true;- }- },- setTimeout: (callback, delayMs) => {- timeouts.push({callback, delayMs});- return timeouts.length;- },- clearTimeout: (id) => {- const timer = timeouts[id - 1];- if (timer != null) {- timer.cleared = true;- }- },- window: {- location: {search: options.search ?? ''},- addEventListener: (eventName, listener) => {- windowListeners.set(eventName, listener);- },- requestAnimationFrame: (callback) => {- frames.push(callback);- return frames.length;- },- },- });- vm.runInContext(PRELOAD_SOURCE, context, {filename: PRELOAD_PATH});- const query = (selector) => mount.querySelector(selector);- return {- context,- intervals,- liveIntervals: () => intervals.filter((timer) => !timer.cleared),- mount,- query,- click: (selector) => query(selector).dispatch('click'),- sendState: (payload) => ipcListeners.get('desktop-splash:state')({}, serializePreloadState(payload)),- reveal: () => ipcListeners.get('desktop-splash:revealed')({}),- sent,- channels: () => sent.map((entry) => entry.channel),- frames,- timeouts,- fontLoads,- flushFrame: () => {- for (const callback of frames.splice(0)) callback();- },- settle: () => new Promise((resolve) => setImmediate(resolve)),- startUnpainted: () => windowListeners.get('DOMContentLoaded')(),- start: async () => {- windowListeners.get('DOMContentLoaded')();- await new Promise((resolve) => setImmediate(resolve));- for (const callback of frames.splice(0)) callback();- for (const callback of frames.splice(0)) callback();- },- unload: () => windowListeners.get('beforeunload')(),- networkOnline: () => windowListeners.get('online')(),- statusText: () => query('.splash-status').textContent,- };-}--describe('splash preload rendering', () => {- test('a held splash waits for its reveal before timing the diagnostics links', async () => {- const diagnosticsTimers = (harness) =>- harness.timeouts.filter((timer) => timer.delayMs === 30000 && !timer.cleared);- const shown = createPreloadHarness();- await shown.start();- assert.equal(diagnosticsTimers(shown).length, 1);-- const held = createPreloadHarness({search: '?held=1'});- await held.start();- assert.equal(diagnosticsTimers(held).length, 0);-- held.reveal();- assert.equal(diagnosticsTimers(held).length, 1);- });-- test('renders before it reports ready, so the first paint is never a blank frame', async () => {- const harness = createPreloadHarness();-- await harness.start();-- assert.equal(harness.mount.replaceChildrenCalls, 1);- assert.deepEqual(harness.sent, [{channel: 'desktop-splash:ready', payload: undefined}]);- assert.equal(harness.statusText(), 'Checking for updates…');- assert.equal(harness.query('.progress-placeholder').textContent, ' ');- assert.equal(harness.query('.splash-mark').getAttribute('src'), './symbol.svg');- assert.equal(harness.query('.splash-mark').getAttribute('width'), '88');- });-- test('reports ready only once the mark is decoded, the fonts are in and two frames have painted', async () => {- const harness = createPreloadHarness();-- harness.startUnpainted();- assert.deepEqual(harness.sent, []);- assert.equal(harness.query('.splash-mark').decodeCalls, 1);- assert.deepEqual(harness.fontLoads, ['400 12px "Fluxer Sans"', '500 16px "Fluxer Sans"']);- const brandingWaits = harness.timeouts.filter((timer) => timer.delayMs <= 500);- assert.equal(brandingWaits.length, 1);-- await harness.settle();- assert.deepEqual(harness.sent, []);- harness.flushFrame();- assert.deepEqual(harness.sent, []);- harness.flushFrame();-- assert.deepEqual(harness.channels(), ['desktop-splash:ready']);- });-- test('patches the status in place instead of rebuilding when the layout is unchanged', () => {- const harness = createPreloadHarness();- harness.start();-- harness.sendState({status: 'verifying'});-- assert.equal(harness.mount.replaceChildrenCalls, 1);- assert.equal(harness.statusText(), 'Verifying files…');- });-- test('never rebuilds when the bar appears, and keeps the same mark node throughout', () => {- const harness = createPreloadHarness();- harness.start();- const mark = harness.query('.splash-mark');-- harness.sendState({status: 'downloading-updates', current: 3, total: 7, progress: 42});-- assert.equal(harness.mount.replaceChildrenCalls, 1);- assert.equal(harness.query('.complete').style.width, '42%');- assert.equal(harness.query('.splash-mark'), mark);-- const complete = harness.query('.complete');- harness.sendState({status: 'downloading-updates', current: 4, total: 7, progress: 55});-- assert.equal(harness.mount.replaceChildrenCalls, 1);- assert.equal(harness.statusText(), 'Downloading update 4 of 7…');- assert.equal(harness.query('.complete'), complete);- assert.equal(complete.style.width, '55%');- assert.equal(harness.query('.splash-mark'), mark);- });-- test('swaps the bar back to a placeholder once, then leaves it alone', () => {- const harness = createPreloadHarness();- harness.start();- harness.sendState({status: 'downloading-updates', current: 1, total: 2, progress: 40});- harness.sendState({status: 'verifying'});- const placeholder = harness.query('.progress-placeholder');-- assert.equal(placeholder.textContent, ' ');- assert.equal(harness.query('.progress'), null);-- harness.sendState({status: 'update-failure', seconds: 8});-- assert.equal(harness.query('.progress-placeholder'), placeholder);- });-- test('keeps the placeholder whenever the bar is hidden', () => {- const harness = createPreloadHarness();- harness.start();-- for (const payload of [- {status: 'downloading-updates', current: 1, total: 2},- {status: 'verifying', progress: 50},- {status: 'update-failure', seconds: 8, progress: 50},- {status: 'shell-update-restarting'},- ]) {- harness.sendState(payload);- assert.notEqual(harness.query('.progress-placeholder'), null, `${payload.status} must keep the placeholder`);- assert.equal(harness.query('.progress'), null, `${payload.status} must keep the placeholder`);- }-- harness.sendState({status: 'installing-updates', current: 5, total: 7, progress: 78});-- assert.notEqual(harness.query('.progress-bar'), null);- });-- test('shows the shell update bar only once velopack reports a number', () => {- const harness = createPreloadHarness();- harness.start();-- harness.sendState({status: 'shell-update-downloading'});-- assert.equal(harness.statusText(), 'Updating Fluxer…');- assert.notEqual(harness.query('.progress-placeholder'), null);-- harness.sendState({status: 'shell-update-downloading', progress: 12});-- assert.equal(harness.query('.complete').style.width, '12%');- });-- test('counts the retry down once a second and stops at zero', () => {- const harness = createPreloadHarness();- harness.start();-- harness.sendState({status: 'update-failure', seconds: 2});-- assert.equal(harness.liveIntervals().length, 1);- assert.equal(harness.intervals[0].delayMs, 1000);- assert.equal(harness.statusText(), 'Update failed. Retrying in 2 sec…');-- harness.intervals.at(-1).callback();- assert.equal(harness.statusText(), 'Update failed. Retrying in 1 sec…');-- harness.intervals.at(-1).callback();- assert.equal(harness.statusText(), 'Update failed. Retrying in 0 sec…');- assert.equal(harness.liveIntervals().length, 0);-- harness.intervals.at(-1).callback();- assert.equal(harness.statusText(), 'Update failed. Retrying in 0 sec…');- });-- test('runs a timer only while a state carries a countdown, and stops on unload', () => {- const harness = createPreloadHarness();- harness.start();-- assert.equal(harness.intervals.length, 0);-- harness.sendState({status: 'verifying'});-- assert.equal(harness.intervals.length, 0);-- harness.sendState({status: 'update-failure', seconds: 3});-- assert.equal(harness.liveIntervals().length, 1);-- harness.sendState({status: 'launching'});-- assert.equal(harness.liveIntervals().length, 0);- assert.equal(harness.intervals.length, 1);-- harness.sendState({status: 'update-failure', seconds: 3});- assert.equal(harness.liveIntervals().length, 1);-- harness.unload();-- assert.equal(harness.liveIntervals().length, 0);- });-- test('restarts the countdown on every state so the first tick is a full second away', () => {- const harness = createPreloadHarness();- harness.start();-- harness.sendState({status: 'update-failure', seconds: 10});- harness.intervals.at(-1).callback();- assert.equal(harness.statusText(), 'Update failed. Retrying in 9 sec…');-- harness.sendState({status: 'update-failure', seconds: 12});-- assert.equal(harness.intervals.length, 2);- assert.equal(harness.intervals[0].cleared, true);- assert.equal(harness.liveIntervals().length, 1);- assert.equal(harness.statusText(), 'Update failed. Retrying in 12 sec…');- });-- test('offers the retry action on blocked-update-required and sends retry-now on click', async () => {- const {serializeSplashState, SplashAction} = await loadSplashWindow('preload-retry-action');- const harness = createPreloadHarness();- await harness.start();-- harness.sendState(serializeSplashState({status: 'blocked-update-required', action: SplashAction.RETRY}));-- assert.equal(harness.statusText(), 'Update required to continue');- assert.equal(harness.query('.splash-action').textContent, 'Retry now');-- harness.click('.splash-action');-- assert.deepEqual(harness.channels(), ['desktop-splash:ready', 'desktop-splash:retry-now']);-- harness.sendState({status: 'launching'});-- assert.equal(harness.query('.splash-action'), null);- assert.equal(harness.mount.replaceChildrenCalls, 1);- });-- test('tells the main process when the network returns', async () => {- const harness = createPreloadHarness();- await harness.start();-- harness.networkOnline();-- assert.deepEqual(harness.channels(), ['desktop-splash:ready', 'desktop-splash:network-online']);- });-- test('offers the download action on a required shell update and sends open-download with no token', async () => {- const {serializeSplashState, SplashAction} = await loadSplashWindow('preload-download-action');- const harness = createPreloadHarness();- harness.start();-- harness.sendState(serializeSplashState({status: 'blocked-shell-update', action: SplashAction.DOWNLOAD}));-- assert.equal(harness.statusText(), 'A new version of Fluxer is required');- assert.equal(harness.query('.splash-action').textContent, 'Download update');-- harness.click('.splash-action');-- assert.deepEqual(harness.sent.at(-1), {channel: 'desktop-splash:open-download', payload: undefined});- });-- test('routes a click to the current action kind without rebuilding the button', async () => {- const {serializeSplashState, SplashAction} = await loadSplashWindow('preload-action-swap');- const harness = createPreloadHarness();- await harness.start();-- harness.sendState(serializeSplashState({status: 'blocked-update-required', action: SplashAction.RETRY}));- const button = harness.query('.splash-action');- harness.sendState(serializeSplashState({status: 'blocked-shell-update', action: SplashAction.DOWNLOAD}));-- assert.equal(harness.query('.splash-action'), button);- assert.equal(button.textContent, 'Download update');- assert.equal(button.listeners.get('click').length, 1);-- harness.click('.splash-action');-- assert.deepEqual(harness.channels(), ['desktop-splash:ready', 'desktop-splash:open-download']);- });-- test('renders no button for an action the preload cannot route', () => {- const harness = createPreloadHarness();- harness.start();-- for (const action of [- {kind: 'launch-anyway', label: 'Launch anyway'},- {kind: 'retry', label: ' '},- {kind: 'retry'},- 'retry',- ]) {- harness.sendState({status: 'blocked-shell-update', action});- assert.equal(harness.query('.splash-action'), null, `${JSON.stringify(action)} must not render`);- }- });-- test('never hands a string to innerHTML, so no splash copy can ever be parsed as markup', () => {- assert.doesNotMatch(PRELOAD_SOURCE, /innerHTML/);- });-});--describe('splash preload contract', () => {- test('knows every status the main process can send', async () => {- const {SplashStatus} = await loadSplashWindow('preload-status-parity');- const {context} = createPreloadHarness();-- assert.deepEqual(JSON.parse(JSON.stringify(vm.runInContext('SplashStatus', context))), SplashStatus);- });-- test('shows the bar only for a numeric progress on a status that carries one', () => {- const {context} = createPreloadHarness();- const shows = (payload) => context.shouldShowProgress(serializePreloadState(payload));-- assert.equal(shows({status: 'downloading-updates', progress: 0}), true);- assert.equal(shows({status: 'installing-updates', progress: 100}), true);- assert.equal(shows({status: 'shell-update-downloading', progress: 5}), true);- assert.equal(shows({status: 'downloading-updates'}), false);- assert.equal(shows({status: 'downloading-updates', progress: 'half'}), false);- assert.equal(shows({status: 'shell-update-downloading'}), false);- assert.equal(shows({status: 'shell-update-restarting', progress: 50}), false);- assert.equal(shows({status: 'verifying', progress: 50}), false);- assert.equal(shows({status: 'launching', progress: 50}), false);- });-- test('uses the same channel names as the main process', async () => {- const module = await loadSplashWindow('preload-channels');-- for (const channel of [- module.DESKTOP_SPLASH_STATE_CHANNEL,- module.DESKTOP_SPLASH_READY_CHANNEL,- module.DESKTOP_SPLASH_RETRY_NOW_CHANNEL,- module.DESKTOP_SPLASH_QUIT_CHANNEL,- module.DESKTOP_SPLASH_OPEN_DOWNLOAD_CHANNEL,- module.DESKTOP_SPLASH_NETWORK_ONLINE_CHANNEL,- ]) {- assert.ok(PRELOAD_SOURCE.includes(`'${channel}'`), `${channel} is missing from splash.cjs`);- }- });-});diff --git a/fluxer_desktop/src/main/ThemeLinkedFileWatch.test.mjs b/fluxer_desktop/src/main/ThemeLinkedFileWatch.test.mjsdeleted file mode 100644index 8983d35be..000000000--- a/fluxer_desktop/src/main/ThemeLinkedFileWatch.test.mjs+++ /dev/null@@ -1,66 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import fs from 'node:fs';-import {createRequire} from 'node:module';-import os from 'node:os';-import path from 'node:path';-import {after, 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('./ThemeLinkedFileWatch.ts', import.meta.url));-const source = fs.readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadThemeLinkedFileWatch() {- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- require,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--const {readThemeCssFile} = loadThemeLinkedFileWatch();-const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-theme-linked-'));-let fileCounter = 0;--after(() => {- fs.rmSync(tempRoot, {recursive: true, force: true});-});--function nextFilePath() {- fileCounter += 1;- return path.join(tempRoot, `theme-${fileCounter}.css`);-}--describe('ThemeLinkedFileWatch', () => {- test('rejects oversize files', async () => {- const filePath = nextFilePath();- fs.writeFileSync(filePath, 'a'.repeat(1024 * 1024 + 1));- const change = await readThemeCssFile(filePath);- assert.equal(change.css, undefined);- assert.equal(change.error, 'too_large');- });-- test('refuses to follow a symlink', async () => {- const targetPath = nextFilePath();- const linkPath = nextFilePath();- fs.writeFileSync(targetPath, 'secret');- fs.symlinkSync(targetPath, linkPath);- const change = await readThemeCssFile(linkPath);- assert.equal(change.css, undefined);- assert.equal(change.error, 'not_file');- });-});diff --git a/fluxer_desktop/src/main/TrayIconImage.test.mjs b/fluxer_desktop/src/main/TrayIconImage.test.mjsdeleted file mode 100644index 5bbae5af2..000000000--- a/fluxer_desktop/src/main/TrayIconImage.test.mjs+++ /dev/null@@ -1,117 +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';-import {BLUE_BGRA, discBitmap, FakeNativeImage, fakeNativeImageModule, pixel} from './TrayIconTestSupport.test.mjs';--installElectronStub({nativeImage: fakeNativeImageModule});--const {paintMonochromeGlyph, paintTrayIndicatorDot, renderTrayIcon, resolveTrayIconAppearance} = await import(- './TrayIconImage.ts'-);--describe('tray icon appearance', () => {- test('macOS always uses the template image', () => {- for (const coloredTrayIcon of [false, true]) {- for (const darkSystemUI of [false, true]) {- assert.equal(resolveTrayIconAppearance({platform: 'darwin', coloredTrayIcon, darkSystemUI}), 'template');- }- }- });-- test('Windows follows the taskbar theme unless the colored icon is chosen', () => {- assert.equal(resolveTrayIconAppearance({platform: 'win32', coloredTrayIcon: false, darkSystemUI: true}), 'white');- assert.equal(resolveTrayIconAppearance({platform: 'win32', coloredTrayIcon: false, darkSystemUI: false}), 'black');- assert.equal(resolveTrayIconAppearance({platform: 'win32', coloredTrayIcon: true, darkSystemUI: false}), 'colored');- });-- test('Linux uses a white glyph whatever the system theme says', () => {- assert.equal(resolveTrayIconAppearance({platform: 'linux', coloredTrayIcon: false, darkSystemUI: false}), 'white');- assert.equal(resolveTrayIconAppearance({platform: 'linux', coloredTrayIcon: true, darkSystemUI: false}), 'colored');- });-});--describe('monochrome glyph', () => {- test('keeps the body, cuts out the light mark and leaves the outside transparent', () => {- const bitmap = discBitmap(32);- paintMonochromeGlyph(bitmap, [0xff, 0xff, 0xff]);- assert.deepEqual(pixel(bitmap, 32, 16, 6), [0xff, 0xff, 0xff, 0xff]);- assert.deepEqual(pixel(bitmap, 32, 16, 16), [0, 0, 0, 0]);- assert.deepEqual(pixel(bitmap, 32, 0, 0), [0, 0, 0, 0]);- });-- test('tints the glyph with premultiplied color', () => {- const bitmap = discBitmap(32);- paintMonochromeGlyph(bitmap, [0x1c, 0x1c, 0x1c]);- assert.deepEqual(pixel(bitmap, 32, 16, 6), [0x1c, 0x1c, 0x1c, 0xff]);- });-- test('an icon without a light mark keeps its whole silhouette', () => {- const bitmap = Buffer.alloc(4 * 4 * 4);- for (let offset = 0; offset < bitmap.length; offset += 4) bitmap.set(BLUE_BGRA, offset);- bitmap.set([0, 0, 0, 0], 0);- paintMonochromeGlyph(bitmap, [0xff, 0xff, 0xff]);- assert.deepEqual(pixel(bitmap, 4, 0, 0), [0, 0, 0, 0]);- assert.deepEqual(pixel(bitmap, 4, 2, 2), [0xff, 0xff, 0xff, 0xff]);- });-});--describe('unread dot', () => {- test('draws an opaque dot in the top-right corner with a transparent gap around it', () => {- const size = 64;- const bitmap = Buffer.alloc(size * size * 4, 0xff);- paintTrayIndicatorDot(bitmap, size, size, [0x00, 0x00, 0xdd]);- const radius = size * 0.22;- assert.deepEqual(pixel(bitmap, size, Math.floor(size - radius), Math.floor(radius)), [0x00, 0x00, 0xdd, 0xff]);- assert.deepEqual(pixel(bitmap, size, Math.floor(size - radius), Math.floor(radius * 2 + 2)), [0, 0, 0, 0]);- assert.deepEqual(pixel(bitmap, size, 4, size - 4), [0xff, 0xff, 0xff, 0xff]);- });-});--describe('renderTrayIcon', () => {- test('returns the base image untouched for the colored icon without a dot', () => {- const base = FakeNativeImage.fromBitmap(16);- assert.equal(renderTrayIcon(base, 'colored', false), base);- const template = FakeNativeImage.fromBitmap(16);- template.setTemplateImage(true);- assert.equal(renderTrayIcon(template, 'template', false), template);- });-- test('paints every scale factor and keeps the template flag', () => {- const base = FakeNativeImage.fromBitmap(16);- base.addRepresentation({scaleFactor: 2, width: 32, height: 32, buffer: discBitmap(32)});- base.setTemplateImage(true);- const result = renderTrayIcon(base, 'template', true);- assert.notEqual(result, base);- assert.deepEqual(result.getScaleFactors(), [1, 2]);- assert.equal(result.isTemplateImage(), true);- assert.deepEqual(pixel(result.toBitmap({scaleFactor: 2}), 32, 25, 7), [0, 0, 0, 0xff]);- assert.deepEqual(pixel(base.toBitmap({scaleFactor: 2}), 32, 25, 7), BLUE_BGRA, 'the base image is not mutated');- });-- test('combines the monochrome glyph with a red dot', () => {- const result = renderTrayIcon(FakeNativeImage.fromBitmap(32), 'white', true);- assert.equal(result.isTemplateImage(), false);- const bitmap = result.toBitmap();- assert.deepEqual(pixel(bitmap, 32, 25, 7), [0x00, 0x00, 0xdd, 0xff]);- assert.deepEqual(pixel(bitmap, 32, 6, 16), [0xff, 0xff, 0xff, 0xff]);- });-- test('keeps the Linux monochrome pixmap within 256 pixels', () => {- const result = renderTrayIcon(FakeNativeImage.fromBitmap(256), 'white', false, 'linux');- const [representation] = result.representations.values();- assert.equal(representation.width, 256);- assert.equal(representation.height, 256);- const bitmap = result.toBitmap();- assert.deepEqual(pixel(bitmap, 256, 128, 50), [0xff, 0xff, 0xff, 0xff]);- assert.deepEqual(pixel(bitmap, 256, 128, 128), [0, 0, 0, 0]);- assert.deepEqual(pixel(bitmap, 256, 20, 128), [0, 0, 0, 0]);- });-- test('skips representations whose bitmap does not match their size', () => {- const base = FakeNativeImage.fromBitmap(16);- base.toBitmap = () => Buffer.alloc(3);- assert.equal(renderTrayIcon(base, 'white', true), base);- });-});diff --git a/fluxer_desktop/src/main/TrayIconTestSupport.test.mjs b/fluxer_desktop/src/main/TrayIconTestSupport.test.mjsdeleted file mode 100644index a1175a257..000000000--- a/fluxer_desktop/src/main/TrayIconTestSupport.test.mjs+++ /dev/null@@ -1,77 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--export const BLUE_BGRA = [0xd9, 0x41, 0x46, 0xff];-export const WHITE_BGRA = [0xff, 0xff, 0xff, 0xff];--export function pixel(bitmap, width, x, y) {- const offset = (y * width + x) * 4;- return [...bitmap.subarray(offset, offset + 4)];-}--export function discBitmap(size) {- const bitmap = Buffer.alloc(size * size * 4);- const center = size / 2;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const dx = x + 0.5 - center;- const dy = y + 0.5 - center;- if (dx * dx + dy * dy > center * center) continue;- const color = Math.abs(dy) < size / 16 && Math.abs(dx) < size / 4 ? WHITE_BGRA : BLUE_BGRA;- bitmap.set(color, (y * size + x) * 4);- }- }- return bitmap;-}--export class FakeNativeImage {- constructor() {- this.representations = new Map();- this.template = false;- }-- static fromBitmap(size, scaleFactor = 1) {- const image = new FakeNativeImage();- const width = size * scaleFactor;- image.addRepresentation({scaleFactor, width, height: width, buffer: discBitmap(width)});- return image;- }-- addRepresentation({scaleFactor = 1, width, height, buffer}) {- this.representations.set(scaleFactor, {width, height, buffer: Buffer.from(buffer)});- }-- isEmpty() {- return this.representations.size === 0;- }-- getScaleFactors() {- return [...this.representations.keys()];- }-- getSize(scaleFactor = 1) {- const representation = this.representations.get(scaleFactor) ?? [...this.representations.values()][0];- if (!representation) return {width: 0, height: 0};- return {width: representation.width / scaleFactor, height: representation.height / scaleFactor};- }-- toBitmap({scaleFactor = 1} = {}) {- return Buffer.from(this.representations.get(scaleFactor).buffer);- }-- resize() {- return this;- }-- setTemplateImage(template) {- this.template = template;- }-- isTemplateImage() {- return this.template;- }-}--export const fakeNativeImageModule = {- createEmpty: () => new FakeNativeImage(),- createFromPath: () => FakeNativeImage.fromBitmap(16),-};diff --git a/fluxer_desktop/src/main/UnreadBadge.test.mjs b/fluxer_desktop/src/main/UnreadBadge.test.mjsdeleted file mode 100644index a13511a2d..000000000--- a/fluxer_desktop/src/main/UnreadBadge.test.mjs+++ /dev/null@@ -1,43 +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 {UNREAD_BADGE_DOT, describeUnreadBadge, parseUnreadBadge} = await import('./UnreadBadge.ts');--describe('parseUnreadBadge', () => {- test('accepts the dot, zero and positive counts', () => {- assert.equal(parseUnreadBadge(UNREAD_BADGE_DOT), -1);- assert.equal(parseUnreadBadge(0), 0);- assert.equal(parseUnreadBadge(7), 7);- assert.equal(parseUnreadBadge(Number.MAX_SAFE_INTEGER), Number.MAX_SAFE_INTEGER);- });-- test('rejects anything that is not a safe integer of at least -1', () => {- for (const value of [- -2,- 1.5,- Number.NaN,- Number.POSITIVE_INFINITY,- 2 ** 53,- '3',- null,- undefined,- {count: 1},- true,- ]) {- assert.equal(parseUnreadBadge(value), null, String(value));- }- });-});--describe('describeUnreadBadge', () => {- test('describes the dot and counts and nothing for zero', () => {- assert.equal(describeUnreadBadge(UNREAD_BADGE_DOT), 'Unread messages');- assert.equal(describeUnreadBadge(1234), 'Unread messages: 1,234');- assert.equal(describeUnreadBadge(0), null);- });-});diff --git a/fluxer_desktop/src/main/WindowRendererLifecycle.test.mjs b/fluxer_desktop/src/main/WindowRendererLifecycle.test.mjsdeleted file mode 100644index 06a8cd1d5..000000000--- a/fluxer_desktop/src/main/WindowRendererLifecycle.test.mjs+++ /dev/null@@ -1,93 +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('./WindowRendererLifecycle.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--function loadWindowRendererLifecycle() {- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return module.exports;-}--const visibleMacContext = {- platform: 'darwin',- isQuitting: false,- isMainWindowHidden: false,- closeToTrayEnabled: true,- reloadedRecently: false,-};--const hiddenMacCloseToTrayContext = {- ...visibleMacContext,- isMainWindowHidden: true,-};--describe('WindowRendererLifecycle', () => {- test('reloads a hidden macOS close-to-tray window instead of quitting after a killed renderer', () => {- const {getMainWindowRendererGoneAction} = loadWindowRendererLifecycle();-- assert.equal(getMainWindowRendererGoneAction({reason: 'killed'}, hiddenMacCloseToTrayContext), 'reload');- });-- test('reloads a hidden macOS close-to-tray window after a clean renderer exit', () => {- const {getMainWindowRendererGoneAction} = loadWindowRendererLifecycle();-- assert.equal(getMainWindowRendererGoneAction({reason: 'clean-exit'}, hiddenMacCloseToTrayContext), 'reload');- });-- test('defers repeated hidden macOS close-to-tray recovery instead of quitting', () => {- const {getMainWindowRendererGoneAction} = loadWindowRendererLifecycle();-- assert.equal(- getMainWindowRendererGoneAction(- {reason: 'killed'},- {- ...hiddenMacCloseToTrayContext,- reloadedRecently: true,- },- ),- 'defer-reload',- );- });-- test('defers repeated hidden macOS crash recovery instead of quitting', () => {- const {getMainWindowRendererGoneAction} = loadWindowRendererLifecycle();-- assert.equal(- getMainWindowRendererGoneAction(- {reason: 'crashed'},- {- ...hiddenMacCloseToTrayContext,- reloadedRecently: true,- },- ),- 'defer-reload',- );- });-- test('keeps the existing visible killed-renderer quit behavior', () => {- const {getMainWindowRendererGoneAction} = loadWindowRendererLifecycle();-- assert.equal(getMainWindowRendererGoneAction({reason: 'killed'}, visibleMacContext), 'quit');- });-});diff --git a/fluxer_desktop/src/main/WindowTrustedOrigin.test.mjs b/fluxer_desktop/src/main/WindowTrustedOrigin.test.mjsdeleted file mode 100644index 1e643896e..000000000--- a/fluxer_desktop/src/main/WindowTrustedOrigin.test.mjs+++ /dev/null@@ -1,213 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {mkdtempSync, readFileSync, rmSync} from 'node:fs';-import {tmpdir} from 'node:os';-import nodePath from 'node:path';-import {describe, test} from 'node:test';-import {installElectronStub} from './LocalAppTestSupport.test.mjs';--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 [];- }-- 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 {isTrustedOrigin} = await import('@electron/main/Window');-const {DESKTOP_APP_URL} = await import('@electron/common/Constants');-const {resolveDesktopLandingUrl} = await import('@electron/main/DesktopLastRoute');-const {initializeDeepLinks} = await import('@electron/main/DeepLinks');--function readMainSource(name) {- return readFileSync(new URL(`./${name}`, import.meta.url), 'utf8');-}--function withArgv(argv, run) {- const original = process.argv;- process.argv = [original[0], original[1], ...argv];- try {- return run();- } finally {- process.argv = original;- }-}--const HOSTILE_ARGV = [- '--app-url=https://evil.example',- '--app-url',- 'https://evil.example',- '--url',- 'https://evil.example/channels/@me',- '--fluxer-instance=https://api.evil.example',- 'https://evil.example/',- 'file:///etc/passwd',-];--describe('the window trust boundary is exactly the local app document origin', () => {- test('the local app origin and its routes are trusted', () => {- assert.equal(isTrustedOrigin(DESKTOP_APP_URL), true);- assert.equal(isTrustedOrigin('fluxer-app://app/channels/@me'), true);- assert.equal(isTrustedOrigin('fluxer-app://app/settings/user?tab=1#x'), true);- });-- test('the reserved proxy routes are never trusted documents', () => {- assert.equal(isTrustedOrigin('fluxer-app://app/api/k/v1/users/@me'), false);- assert.equal(isTrustedOrigin('fluxer-app://app/proxy/k?url=https://evil.example'), false);- });-- test('the credential, port and host bypasses are rejected', () => {- assert.equal(isTrustedOrigin('fluxer-app://evil.example/x'), false);- assert.equal(isTrustedOrigin('fluxer-app://u:p@app/'), false);- assert.equal(isTrustedOrigin('fluxer-app://app:8080/'), false);- });-- test('an opaque origin is rejected, which is what protects the data: voice-debug window', () => {- assert.equal(isTrustedOrigin('data:text/html,x'), false);- assert.equal(isTrustedOrigin('about:blank'), false);- assert.equal(isTrustedOrigin('file:///etc/passwd'), false);- });-- test('no remote origin is trusted any more', () => {- assert.equal(isTrustedOrigin('https://web.fluxer.app/channels/@me'), false);- assert.equal(isTrustedOrigin('https://web.canary.fluxer.app/'), false);- assert.equal(isTrustedOrigin('https://evil.example/'), false);- });-- test('the OS deep link scheme is not a document origin', () => {- assert.equal(isTrustedOrigin('fluxer://guild/channel'), false);- });-- test('an empty or absent URL is rejected', () => {- assert.equal(isTrustedOrigin(''), false);- assert.equal(isTrustedOrigin(undefined), false);- assert.equal(isTrustedOrigin('not a url'), false);- });-});--describe('the main window only ever loads the local app document', () => {- test('the window hands its only load to the retry loop, aimed at the landing url', () => {- const windowSource = readMainSource('Window.ts');- assert.doesNotMatch(windowSource, /\.loadURL\(|\.loadFile\(/);- assert.match(- windowSource,- /createAppLoadRetry\(\{\s*webContents,\s*appUrl: resolveDesktopLandingUrl\(app\.getPath\('userData'\)\),/,- );- const retrySource = readMainSource('AppLoadRetry.ts');- assert.equal(retrySource.match(/\.loadURL\(/g)?.length, 1);- assert.match(retrySource, /webContents\.loadURL\(appUrl\)/);- assert.match(retrySource, /const appUrl = options\.appUrl;/);- });-- test('no launch flag moves the landing url off the local app document', () => {- const userData = mkdtempSync(nodePath.join(tmpdir(), 'fluxer-main-window-document-'));- try {- const landing = withArgv(HOSTILE_ARGV, () => resolveDesktopLandingUrl(userData));- assert.equal(landing, `${DESKTOP_APP_URL}channels/@me`);- assert.equal(isTrustedOrigin(landing), true);- } finally {- rmSync(userData, {recursive: true, force: true});- }- });-- test('a deep link reaches the renderer as an in-app path, never as a document to load', async () => {- assert.doesNotMatch(readMainSource('DeepLinks.ts'), /\.loadURL\(|\.loadFile\(/);- for (const deepLink of ['fluxer://channels/@me', 'fluxer://evil.example/https://evil.example', 'fluxer://-/x']) {- ipcHandlers.delete('get-initial-deep-link');- withArgv([...HOSTILE_ARGV, deepLink], () => initializeDeepLinks());- const payload = await ipcHandlers.get('get-initial-deep-link')();- assert.equal(typeof payload, 'string', deepLink);- assert.ok(payload.startsWith('/'), deepLink);- assert.equal(isTrustedOrigin(new URL(payload.replace(/^\/+/u, ''), DESKTOP_APP_URL).href), true, deepLink);- }- });-- test('a sign-in return link never reaches the renderer with its grant', async () => {- ipcHandlers.delete('get-initial-deep-link');- withArgv(['fluxer://handoff?code=ABCDEF-GHJKMN&grant=secret-grant'], () => initializeDeepLinks());- assert.equal(await ipcHandlers.get('get-initial-deep-link')(), null);- });-- test('a deep link that names a site is not forwarded as one', async () => {- ipcHandlers.delete('get-initial-deep-link');- withArgv(['https://evil.example/channels/@me'], () => initializeDeepLinks());- assert.equal(await ipcHandlers.get('get-initial-deep-link')(), null);- });-});diff --git a/fluxer_desktop/src/main/WindowsBadge.test.mjs b/fluxer_desktop/src/main/WindowsBadge.test.mjsdeleted file mode 100644index 60e8cff3a..000000000--- a/fluxer_desktop/src/main/WindowsBadge.test.mjs+++ /dev/null@@ -1,168 +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 {fileURLToPath} from 'node:url';-import {installElectronStub, installTestModuleStub} from './LocalAppTestSupport.test.mjs';--const BUILD_RESOURCES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'build_resources');-const CHANNEL_ICON_DIRECTORIES = ['icons-stable', 'icons-canary', 'icons-development'];-const BADGE_NAMES = Array.from({length: 11}, (_, offset) => [- `badge-${offset + 1}.ico`,- `badge-dark-${offset + 1}.ico`,-]).flat();--const resourcesPath = fs.mkdtempSync(path.join(os.tmpdir(), 'fluxer-desktop-windows-badge-test-'));-fs.mkdirSync(path.join(resourcesPath, 'badges'));-for (const name of BADGE_NAMES) {- fs.copyFileSync(path.join(BUILD_RESOURCES, 'icons-stable', 'badges', name), path.join(resourcesPath, 'badges', name));-}-Object.defineProperty(process, 'resourcesPath', {value: resourcesPath, configurable: true});-Object.defineProperty(process, 'platform', {value: 'win32', configurable: true});--const settings = {darkTaskbarBadge: false};-globalThis.__fluxerDesktopWindowsBadgeTestSettings__ = settings;--installTestModuleStub(- '@electron/common/DesktopConfig',- 'export const getDesktopWindowBehaviorSettings = () => ({...globalThis.__fluxerDesktopWindowsBadgeTestSettings__});',-);--const display = {scaleFactor: 1};--installElectronStub({- nativeImage: {- createFromBuffer: (png) => ({png, isEmpty: () => false}),- },- screen: {- getDisplayMatching: () => display,- },-});--const {pickBadgeFrameSize, readIconPngFrames, refreshWindowsBadgeOverlay, setWindowsBadgeOverlay} = await import(- './WindowsBadge.ts'-);--const framesByName = new Map(- BADGE_NAMES.map((name) => [name, readIconPngFrames(fs.readFileSync(path.join(resourcesPath, 'badges', name)))]),-);--function frameOf(png) {- for (const [name, frames] of framesByName) {- for (const [size, frame] of frames) {- if (frame === png || frame.equals(png)) return `${name}@${size}`;- }- }- return null;-}--function createWindow() {- return {- overlays: [],- isDestroyed: () => false,- getBounds: () => ({x: 0, y: 0, width: 800, height: 600}),- setOverlayIcon(icon, description) {- this.overlays.push({name: icon ? frameOf(icon.png) : null, description});- },- };-}--function readIconFrames(file) {- const data = fs.readFileSync(file);- assert.equal(data.readUInt16LE(2), 1);- return Array.from({length: data.readUInt16LE(4)}, (_, index) => {- const entry = 6 + index * 16;- const offset = data.readUInt32LE(entry + 12);- return {- size: data[entry],- bitsPerPixel: data.readUInt16LE(entry + 6),- png: data.subarray(offset, offset + 4).toString('latin1') === '\x89PNG',- };- });-}--describe('windows taskbar badge overlay', () => {- test('redraws in the chosen color as soon as the setting changes', () => {- const win = createWindow();- refreshWindowsBadgeOverlay(win);- assert.equal(win.overlays.length, 0, 'nothing to refresh before the first count');-- setWindowsBadgeOverlay(win, 3);- assert.equal(win.overlays.at(-1).name, 'badge-3.ico@16');- assert.match(win.overlays.at(-1).description, /3/);- setWindowsBadgeOverlay(win, 3);- assert.equal(win.overlays.length, 1);-- settings.darkTaskbarBadge = true;- refreshWindowsBadgeOverlay(win);- assert.equal(win.overlays.at(-1).name, 'badge-dark-3.ico@16');- setWindowsBadgeOverlay(win, 3);- assert.equal(win.overlays.length, 2, 'the same dark icon is not set twice');-- settings.darkTaskbarBadge = false;- setWindowsBadgeOverlay(win, 3);- assert.equal(win.overlays.length, 3, 'a color switch alone redraws the same count');- assert.equal(win.overlays.at(-1).name, 'badge-3.ico@16');-- settings.darkTaskbarBadge = true;- setWindowsBadgeOverlay(win, 25);- assert.equal(win.overlays.at(-1).name, 'badge-dark-10.ico@16');- setWindowsBadgeOverlay(win, -1);- assert.equal(win.overlays.at(-1).name, 'badge-dark-11.ico@16');-- display.scaleFactor = 1.5;- refreshWindowsBadgeOverlay(win);- assert.equal(win.overlays.at(-1).name, 'badge-dark-11.ico@24', 'the frame follows the display scale');- display.scaleFactor = 1;-- setWindowsBadgeOverlay(win, 0);- assert.equal(win.overlays.at(-1).name, null);- assert.equal(win.overlays.at(-1).description, 'No Notifications');- });-});--describe('badge frame selection', () => {- test('uses the exact frame for each display scale and never upscales when one exists', () => {- const sizes = [16, 20, 24, 32, 40, 48];- assert.equal(pickBadgeFrameSize(sizes, 1), 16);- assert.equal(pickBadgeFrameSize(sizes, 1.25), 20);- assert.equal(pickBadgeFrameSize(sizes, 1.5), 24);- assert.equal(pickBadgeFrameSize(sizes, 1.75), 32);- assert.equal(pickBadgeFrameSize(sizes, 2), 32);- assert.equal(pickBadgeFrameSize(sizes, 3), 48);- assert.equal(pickBadgeFrameSize(sizes, 4), 48);- assert.equal(pickBadgeFrameSize([], 1), null);- });-- test('ignores frames that are not PNG and malformed icon data', () => {- assert.equal(readIconPngFrames(Buffer.alloc(0)).size, 0);- assert.equal(readIconPngFrames(Buffer.from([0, 0, 2, 0, 1, 0])).size, 0);- const truncated = fs.readFileSync(path.join(resourcesPath, 'badges', 'badge-3.ico')).subarray(0, 200);- assert.ok(readIconPngFrames(truncated).size < 6);- });-});--describe('bundled taskbar badge icons', () => {- test('every channel ships the same red and dark PNG badges for every display scale', () => {- const [reference, ...others] = CHANNEL_ICON_DIRECTORIES.map((directory) =>- path.join(BUILD_RESOURCES, directory, 'badges'),- );- for (const name of BADGE_NAMES) {- const frames = readIconFrames(path.join(reference, name));- assert.deepEqual(- frames.map(({size, bitsPerPixel, png}) => [size, bitsPerPixel, png]),- [16, 20, 24, 32, 40, 48].map((size) => [size, 32, true]),- name,- );- for (const directory of others) {- assert.ok(- fs.readFileSync(path.join(directory, name)).equals(fs.readFileSync(path.join(reference, name))),- name,- );- }- }- });-});diff --git a/fluxer_desktop/src/main/WindowsShortcuts.test.mjs b/fluxer_desktop/src/main/WindowsShortcuts.test.mjsdeleted file mode 100644index 398eacc20..000000000--- a/fluxer_desktop/src/main/WindowsShortcuts.test.mjs+++ /dev/null@@ -1,184 +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 path from 'node:path';-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('./WindowsShortcuts.ts', import.meta.url));-const source = readFileSync(sourcePath, 'utf8');-const transformedSource = esbuild.transformSync(source, {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',-}).code;--const APPDATA = 'C:\\Users\\csh\\AppData\\Roaming';-const USERPROFILE = 'C:\\Users\\csh';-const PROGRAMS_DIR = path.win32.join(APPDATA, 'Microsoft', 'Windows', 'Start Menu', 'Programs');-const AUTHOR_DIR = path.win32.join(PROGRAMS_DIR, 'Fluxer Platform AB');-const ROOT_SHORTCUT = path.win32.join(PROGRAMS_DIR, 'Fluxer Canary.lnk');-const AUTHOR_SHORTCUT = path.win32.join(AUTHOR_DIR, 'Fluxer Canary.lnk');-const ROOT_APP_DIR = 'C:\\Users\\csh\\AppData\\Local\\fluxer_desktop_canary';-const CURRENT_DIR = path.win32.join(ROOT_APP_DIR, 'current');-const CURRENT_EXE = path.win32.join(CURRENT_DIR, 'Fluxer Canary.exe');-const STALE_EXE = path.win32.join(ROOT_APP_DIR, 'app-1.0.0', 'Fluxer Canary.exe');-const LEGACY_APP_USER_MODEL_ID = 'velopack.fluxer_desktop_canary';--function lnkBuffer(...values) {- return Buffer.concat([Buffer.from('L\0\0\0', 'utf8'), ...values.map((value) => Buffer.from(value, 'utf16le'))]);-}--function loadWindowsShortcuts(initialFiles) {- const files = new Map(initialFiles);- const dirs = new Set([PROGRAMS_DIR, ROOT_APP_DIR, CURRENT_DIR]);- for (const filePath of files.keys()) {- dirs.add(path.win32.dirname(filePath));- }- files.set(path.win32.join(ROOT_APP_DIR, 'Update.exe'), Buffer.from('exe'));-- const fsOperations = [];- const fakeFs = {- existsSync: (target) => files.has(target) || dirs.has(target),- readFileSync: (target) => {- const contents = files.get(target);- if (!contents) throw new Error(`ENOENT ${target}`);- return contents;- },- mkdirSync: (target) => {- fsOperations.push(['mkdir', target]);- dirs.add(target);- },- renameSync: (from, to) => {- fsOperations.push(['rename', from, to]);- files.set(to, files.get(from));- files.delete(from);- },- rmSync: (target) => {- fsOperations.push(['rm', target]);- files.delete(target);- },- };-- const createdShortcuts = [];- const winShell = {- loadError: null,- createShortcut: async (options) => {- createdShortcuts.push(options);- files.set(options.lnkPath, lnkBuffer(options.target, options.appUserModelId));- },- };-- const module = {exports: {}};- const context = vm.createContext({- module,- exports: module.exports,- console,- Buffer,- process: {platform: 'win32', execPath: CURRENT_EXE, env: {APPDATA, USERPROFILE}},- require: (specifier) => {- if (specifier === '@electron/main/NativeAddon') {- const addonModule = {exports: {}};- const addonSource = esbuild.transformSync(readFileSync(new URL('./NativeAddon.ts', import.meta.url), 'utf8'), {- loader: 'ts',- format: 'cjs',- target: 'node20',- }).code;- vm.runInContext('(function (module, exports) {' + addonSource + '\n})', context)(- addonModule,- addonModule.exports,- );- return addonModule.exports;- }- if (specifier === 'node:fs') {- return {default: fakeFs, ...fakeFs};- }- if (specifier === 'node:path') {- return {default: path.win32, ...path.win32};- }- if (specifier === 'node:module') {- return {- createRequire: () => (moduleName) => {- if (moduleName === '@fluxer/win-shell') return winShell;- throw new Error(`unexpected require ${moduleName}`);- },- };- }- if (specifier === '@electron/common/DesktopIdentity') {- return {- DESKTOP_APP_NAME: 'Fluxer Canary',- WINDOWS_APP_USER_MODEL_ID: 'Fluxer.Fluxer.Canary',- WINDOWS_LEGACY_APP_USER_MODEL_IDS: [LEGACY_APP_USER_MODEL_ID],- WINDOWS_SHORTCUT_AUTHOR: 'Fluxer Platform AB',- WINDOWS_TOAST_ACTIVATOR_CLSID: '{9CEDB5C0-3552-43B0-A279-2232E0CDF74C}',- };- }- return require(specifier);- },- });- vm.runInContext(transformedSource, context, {filename: sourcePath});- return {...module.exports, createdShortcuts, dirs, files, fsOperations};-}--async function runRepair(harness) {- harness.repairWindowsShortcuts();- await new Promise((resolve) => setImmediate(resolve));-}--describe('Windows Start Menu shortcut repair', () => {- test('leaves a user-placed root shortcut alone and does not recreate the author folder', async () => {- const harness = loadWindowsShortcuts([[ROOT_SHORTCUT, lnkBuffer(CURRENT_EXE)]]);-- await runRepair(harness);-- assert.deepEqual(harness.fsOperations, []);- assert.equal(harness.files.has(ROOT_SHORTCUT), true);- assert.equal(harness.files.has(AUTHOR_SHORTCUT), false);- assert.equal(harness.dirs.has(AUTHOR_DIR), false);- });-- test('does not delete a root shortcut when the author shortcut also exists', async () => {- const harness = loadWindowsShortcuts([- [ROOT_SHORTCUT, lnkBuffer(CURRENT_EXE)],- [AUTHOR_SHORTCUT, lnkBuffer(CURRENT_EXE)],- ]);-- await runRepair(harness);-- assert.deepEqual(harness.fsOperations, []);- assert.equal(harness.files.has(ROOT_SHORTCUT), true);- assert.equal(harness.files.has(AUTHOR_SHORTCUT), true);- });-- test('rewrites a stale root shortcut in place instead of relocating it', async () => {- const harness = loadWindowsShortcuts([[ROOT_SHORTCUT, lnkBuffer(STALE_EXE)]]);-- await runRepair(harness);-- assert.deepEqual(harness.fsOperations, []);- const rewritten = harness.createdShortcuts.filter((options) => options.lnkPath === ROOT_SHORTCUT);- assert.equal(rewritten.length, 1);- assert.equal(rewritten[0].target, CURRENT_EXE);- assert.equal(rewritten[0].appUserModelId, 'Fluxer.Fluxer.Canary');- assert.equal(harness.files.has(AUTHOR_SHORTCUT), false);- });-- test('still rewrites the author shortcut with the legacy AppUserModelID', async () => {- const harness = loadWindowsShortcuts([[AUTHOR_SHORTCUT, lnkBuffer(CURRENT_EXE, LEGACY_APP_USER_MODEL_ID)]]);-- await runRepair(harness);-- const rewritten = harness.createdShortcuts.filter((options) => options.lnkPath === AUTHOR_SHORTCUT);- assert.equal(rewritten.length, 1);- assert.equal(rewritten[0].target, CURRENT_EXE);- assert.equal(rewritten[0].appUserModelId, 'Fluxer.Fluxer.Canary');- assert.equal(rewritten[0].toastActivatorClsid, '{9CEDB5C0-3552-43B0-A279-2232E0CDF74C}');- });-});diff --git a/fluxer_desktop/src/main/WindowsWindowCaptureItemReuse.test.mjs b/fluxer_desktop/src/main/WindowsWindowCaptureItemReuse.test.mjsdeleted file mode 100644index c295bb7eb..000000000--- a/fluxer_desktop/src/main/WindowsWindowCaptureItemReuse.test.mjs+++ /dev/null@@ -1,139 +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');--function transform(fileName) {- const sourcePath = fileURLToPath(new URL(fileName, import.meta.url));- return esbuild.transformSync(readFileSync(sourcePath, 'utf8'), {- loader: 'ts',- format: 'cjs',- platform: 'node',- target: 'node20',- logLevel: 'silent',- }).code;-}--const reuseSource = transform('./WindowsWindowCaptureItemReuse.ts');-const nativeAddonSource = transform('./NativeAddon.ts');--function loadReuse({platform = 'win32', windowsBuild = 19045, addon}) {- const logged = [];- const calls = {install: 0, loads: 0};- const counts = {forwarded: 0, reused: 0};- const fakeAddon = addon ?? {- loadError: null,- reuseWindowCaptureItems: () => {- calls.install += 1;- return true;- },- windowCaptureItemCalls: () => ({...counts}),- };- const context = vm.createContext({console, process: {platform, argv: []}});- const load = (source) => {- const module = {exports: {}};- vm.runInContext(`(function (module, exports, require) {${source}\n})`, context)(- module,- module.exports,- fakeRequire,- );- return module.exports;- };- const fakeRequire = (specifier) => {- if (specifier === 'node:module') {- return {- createRequire: () => (name) => {- assert.equal(name, '@fluxer/win-game-capture');- calls.loads += 1;- return fakeAddon;- },- };- }- if (specifier === '@electron/main/NativeAddon') return load(nativeAddonSource);- if (specifier === '@electron/main/LaunchOptions') return {isSafeModeLaunch: () => false};- if (specifier === '@electron/main/WindowsScreenCaptureGuard') return {getWindowsBuildNumber: () => windowsBuild};- if (specifier === 'electron-log') {- const record =- (level) =>- (...args) =>- logged.push([level, ...args]);- return {info: record('info'), warn: record('warn')};- }- throw new Error(`unexpected require ${specifier}`);- };- return {...load(reuseSource), calls, counts, logged};-}--const windowSource = {id: 'window:1234:0', name: 'Notepad'};--describe('Windows window capture item reuse', () => {- test('installs once, only for window shares on Windows 10 2004 to 22H2', () => {- const cases = [- [17763, 0],- [18362, 0],- [19040, 0],- [19041, 1],- [19044, 1],- [19045, 1],- [19046, 0],- [20348, 0],- [22000, 0],- [26100, 0],- [null, 0],- ];- for (const [windowsBuild, installs] of cases) {- const reuse = loadReuse({windowsBuild});- reuse.reuseWindowsCaptureItemsForSource({id: 'screen:0:0', name: 'Screen 1'});- assert.equal(reuse.calls.loads, 0, `build ${windowsBuild} screen share`);- reuse.reuseWindowsCaptureItemsForSource(windowSource);- reuse.reuseWindowsCaptureItemsForSource({id: 'window:5678:0', name: 'Explorer'});- assert.equal(reuse.calls.install, installs, `build ${windowsBuild}`);- assert.equal(reuse.calls.loads, installs, `build ${windowsBuild}`);- }- for (const platform of ['darwin', 'linux']) {- const reuse = loadReuse({platform});- reuse.reuseWindowsCaptureItemsForSource(windowSource);- assert.equal(reuse.calls.loads, 0, platform);- }- });-- test('reports the capture item requests made since the previous report', () => {- const reuse = loadReuse({});- reuse.reuseWindowsCaptureItemsForSource(windowSource);- Object.assign(reuse.counts, {forwarded: 3, reused: 53999});- reuse.reportWindowsCaptureItemReuse('streaming-priority-release');- reuse.reportWindowsCaptureItemReuse('streaming-priority-reset');- Object.assign(reuse.counts, {forwarded: 6, reused: 54009});- reuse.reportWindowsCaptureItemReuse('streaming-priority-release');- const reports = reuse.logged- .filter(([, message]) => message.includes('since the last report'))- .map(([, , fields]) => ({...fields}));- assert.deepEqual(reports, [- {reason: 'streaming-priority-release', forwardedToCaptureService: 3, reusedFromLiveShare: 53999},- {reason: 'streaming-priority-release', forwardedToCaptureService: 3, reusedFromLiveShare: 10},- ]);- });-- test('a failing addon never throws into the share request', () => {- const reuse = loadReuse({- addon: {- loadError: null,- reuseWindowCaptureItems: () => {- throw new Error('binding exploded');- },- windowCaptureItemCalls: () => null,- },- });- assert.doesNotThrow(() => reuse.reuseWindowsCaptureItemsForSource(windowSource));- assert.doesNotThrow(() => reuse.reuseWindowsCaptureItemsForSource(windowSource));- assert.doesNotThrow(() => reuse.reportWindowsCaptureItemReuse('streaming-priority-release'));- assert.equal(reuse.logged.filter(([level]) => level === 'warn').length, 1);- });-});diff --git a/fluxer_desktop/src/preload/LegacyHarvestPreload.test.mjs b/fluxer_desktop/src/preload/LegacyHarvestPreload.test.mjsdeleted file mode 100644index be8e5efad..000000000--- a/fluxer_desktop/src/preload/LegacyHarvestPreload.test.mjs+++ /dev/null@@ -1,333 +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 '../main/LocalAppTestSupport.test.mjs';--const {DESKTOP_LEGACY_HARVEST_BLOB_REF_KEY, DESKTOP_LEGACY_HARVEST_CHANNELS} = await import(- '../../../packages/desktop_ipc/src/LegacyHarvestContract.ts'-);--const SUBMIT_CHANNEL = DESKTOP_LEGACY_HARVEST_CHANNELS.submit;-const FAILING_STORE = Symbol('failing store');-const FAILING_DATABASE = Symbol('failing database');--function fakeDatabase(name, stores) {- return {- name,- version: 2,- objectStoreNames: Object.keys(stores),- close() {},- transaction(storeName) {- const transaction = {abort() {}, db: this};- const store = {- name: storeName,- keyPath: null,- transaction,- openCursor() {- const request = {};- const records = stores[storeName];- if (records === FAILING_STORE) {- queueMicrotask(() => {- request.error = new Error('cursor failed');- request.onerror?.();- });- return request;- }- let index = -1;- const cursor = {continue: () => queueMicrotask(() => step())};- const step = () => {- index += 1;- if (index >= records.length) {- request.result = null;- } else {- cursor.key = records[index].key;- cursor.value = records[index].value;- request.result = cursor;- }- request.onsuccess?.();- };- queueMicrotask(step);- return request;- },- };- transaction.objectStore = () => store;- return transaction;- },- };-}--function installHarvestDocument(- stores,- localStorage,- location = {protocol: 'https:', hostname: 'web.fluxer.app', pathname: '/__fluxer-desktop-storage-harvest'},-) {- const submissions = [];- let settle = () => undefined;- const submitted = new Promise((resolve) => {- settle = resolve;- });- submissions.submitted = submitted;- installElectronStub({- ipcRenderer: {- invoke: (channel, submission) => {- submissions.push({channel, submission});- settle();- return Promise.resolve();- },- },- });- globalThis.window = {- location,- setTimeout: (callback, delay) => setTimeout(callback, delay),- clearTimeout: (timer) => clearTimeout(timer),- localStorage,- indexedDB: {- open(name) {- if (stores[name] === FAILING_DATABASE) throw new Error('database is wedged');- const request = {};- queueMicrotask(() => {- if (stores[name] === undefined) {- request.onupgradeneeded?.();- request.onerror?.();- return;- }- request.result = fakeDatabase(name, stores[name]);- request.onsuccess?.();- });- return request;- },- },- };- return submissions;-}--function readableStorage(entries) {- const keys = Object.keys(entries);- return {length: keys.length, key: (index) => keys[index] ?? null, getItem: (key) => entries[key] ?? null};-}--async function runHarvest(caseName, stores, localStorage = readableStorage({token: 'tok'})) {- const submissions = installHarvestDocument(stores, localStorage);- await import(`./LegacyHarvestPreload.ts?${caseName}`);- await Promise.race([- submissions.submitted,- new Promise((resolve) => {- const guard = setTimeout(resolve, 5_000);- guard.unref?.();- }),- ]);- assert.equal(submissions.length, 1);- assert.equal(submissions[0].channel, SUBMIT_CHANNEL);- return submissions[0].submission;-}--async function harvestRuns(caseName, location) {- const submissions = installHarvestDocument({}, readableStorage({token: 'tok'}), location);- await import(`./LegacyHarvestPreload.ts?${caseName}`);- await Promise.race([- submissions.submitted,- new Promise((resolve) => {- const guard = setTimeout(resolve, 750);- guard.unref?.();- }),- ]);- return submissions.length > 0;-}--describe('which origins the harvest will read storage from', () => {- const sentinel = '/__fluxer-desktop-storage-harvest';-- test('https is trusted, whatever the host', async () => {- assert.equal(- await harvestRuns('https-remote', {protocol: 'https:', hostname: 'web.fluxer.app', pathname: sentinel}),- true,- );- });-- test('http on loopback is trusted, so a local dev instance can be migrated', async () => {- for (const hostname of ['127.0.0.1', 'localhost', '[::1]']) {- assert.equal(- await harvestRuns(`http-loopback-${hostname}`, {protocol: 'http:', hostname, pathname: sentinel}),- true,- `${hostname} over http is a local dev instance and must be harvestable, otherwise the development channel can never migrate an existing profile`,- );- }- });-- test('http off loopback is refused, so storage is never read over a plaintext network origin', async () => {- for (const hostname of ['web.fluxer.app', 'example.com', '10.0.0.1']) {- assert.equal(- await harvestRuns(`http-remote-${hostname}`, {protocol: 'http:', hostname, pathname: sentinel}),- false,- `${hostname} over plaintext http must never have its storage harvested`,- );- }- });-- test('a non http scheme is refused', async () => {- assert.equal(await harvestRuns('file-scheme', {protocol: 'file:', hostname: '', pathname: sentinel}), false);- });-});--describe('a value the codec cannot represent', () => {- test('costs its own record, not the whole legacy origin', async () => {- const oversized = new Blob([new Uint8Array(33 * 1024 * 1024)], {type: 'video/mp4'});- const submission = await runHarvest('oversized-blob', {- 'fluxer-theme-library': {- assets: [{key: null, value: {id: 'a', data: oversized}}],- meta: [{key: null, value: {enabledThemeIds: ['t1']}}],- },- });-- assert.equal(submission.ok, true);- assert.ok(submission.payload.truncated.includes('fluxer-theme-library/assets/0.data'));- assert.deepEqual({...submission.payload.localStorage}, {token: 'tok'});- const byStore = new Map(submission.payload.stores.map((store) => [store.store, store.records.length]));- assert.equal(byStore.get('assets'), 1);- assert.equal(byStore.get('meta'), 1);- assert.equal(submission.payload.stores.find((store) => store.store === 'assets').records[0].value.data, null);- assert.deepEqual(submission.payload.blobs, []);- });-- test('an Error instance and a cycle are reduced without losing the other records', async () => {- const cyclic = {name: 'theme'};- cyclic.self = cyclic;- const submission = await runHarvest('unencodable-shapes', {- 'fluxer-app-storage': {- entries: [- {key: null, value: {scope: 'global', lastError: new Error('boom')}},- {key: null, value: cyclic},- {key: null, value: {scope: 'global', key: 'Theme', value: 'dark'}},- ],- },- });-- assert.equal(submission.ok, true);- assert.equal(submission.payload.stores[0].records.length, 3);- assert.deepEqual({...submission.payload.stores[0].records[0].value}, {scope: 'global', lastError: {}});- assert.deepEqual({...submission.payload.stores[0].records[1].value}, {name: 'theme', self: null});- assert.deepEqual(- {...submission.payload.stores[0].records[2].value},- {- scope: 'global',- key: 'Theme',- value: 'dark',- },- );- });-- test('a sub-object referenced twice survives at both sites, because aliasing is not a cycle', async () => {- const shared = {id: 'guild-1', name: 'Fluxer'};- const nested = {tree: {left: shared, right: shared}};- const submission = await runHarvest('aliased-references', {- 'fluxer-app-storage': {- entries: [- {key: null, value: {primary: shared, mirror: shared, list: [shared, shared]}},- {key: null, value: nested},- ],- },- });-- assert.equal(submission.ok, true);- const [aliased, deep] = submission.payload.stores[0].records;- assert.deepEqual({...aliased.value.primary}, {id: 'guild-1', name: 'Fluxer'});- assert.deepEqual({...aliased.value.mirror}, {id: 'guild-1', name: 'Fluxer'});- assert.deepEqual(- aliased.value.list.map((item) => ({...item})),- [- {id: 'guild-1', name: 'Fluxer'},- {id: 'guild-1', name: 'Fluxer'},- ],- );- assert.deepEqual({...deep.value.tree.left}, {id: 'guild-1', name: 'Fluxer'});- assert.deepEqual({...deep.value.tree.right}, {id: 'guild-1', name: 'Fluxer'});- assert.equal(- submission.payload.truncated.some((label) => label.startsWith('fluxer-app-storage/')),- false,- 'a repeated reference is not a loss, so no record may be reported as truncated',- );- });-- test('a cycle still collapses once the recursion stack unwinds past it', async () => {- const root = {name: 'root'};- root.self = root;- root.child = {parent: root, label: 'child'};- const submission = await runHarvest('cycle-after-alias-fix', {- 'fluxer-app-storage': {entries: [{key: null, value: root}]},- });-- assert.equal(submission.ok, true);- const encoded = submission.payload.stores[0].records[0].value;- assert.equal(encoded.self, null);- assert.equal(encoded.child.parent, null);- assert.equal(encoded.child.label, 'child');- });-- test('a blob is encoded under the key the contract declares, so the app-side decoder still finds it', async () => {- const submission = await runHarvest('blob-reference-key', {- 'fluxer-theme-library': {- assets: [{key: null, value: {id: 'a', data: new Blob([new Uint8Array([1, 2, 3])], {type: 'image/png'})}}],- },- });-- assert.equal(submission.ok, true);- const reference = submission.payload.stores[0].records[0].value.data[DESKTOP_LEGACY_HARVEST_BLOB_REF_KEY];- assert.equal(typeof reference.blobId, 'string');- assert.equal(reference.type, 'image/png');- assert.equal(reference.size, 3);- assert.equal(submission.payload.blobs.length, 1);- assert.equal(submission.payload.blobs[0].blobId, reference.blobId);- });-- test('an unreadable localStorage fails the submission so the harvest is retried', async () => {- const blocked = {- get length() {- throw new Error('storage is blocked');- },- key: () => null,- getItem: () => null,- };- const submission = await runHarvest('blocked-local-storage', {'fluxer-app-storage': {entries: []}}, blocked);-- assert.equal(submission.ok, false);- assert.equal(submission.payload, null);- assert.match(submission.error, /localStorage/);- });-- test('an unreadable FluxerAccounts store fails the submission so saved accounts are not lost', async () => {- const submission = await runHarvest('failing-accounts-store', {- FluxerAccounts: {accounts: FAILING_STORE},- 'fluxer-app-storage': {entries: []},- });-- assert.equal(submission.ok, false);- assert.equal(submission.payload, null);- assert.match(submission.error, /FluxerAccounts\/accounts/);- });-- test('a FluxerAccounts database that cannot be opened fails the submission', async () => {- const submission = await runHarvest('failing-accounts-database', {FluxerAccounts: FAILING_DATABASE});-- assert.equal(submission.ok, false);- assert.match(submission.error, /FluxerAccounts/);- });-- test('an unreadable store in a non-critical database is still only a truncation', async () => {- const submission = await runHarvest('failing-voice-stats-store', {- FluxerAccounts: {accounts: [{key: null, value: {userId: '1'}}]},- FluxerVoiceStats: {samples: FAILING_STORE},- });-- assert.equal(submission.ok, true);- assert.ok(submission.payload.truncated.includes('FluxerVoiceStats/samples'));- assert.equal(submission.payload.stores.find((store) => store.store === 'accounts').records.length, 1);- });-- test('an origin with no legacy databases is not a failure', async () => {- const submission = await runHarvest('no-databases', {});-- assert.equal(submission.ok, true);- assert.deepEqual(submission.payload.stores, []);- });-});diff --git a/fluxer_desktop/src/preload/LegacyRawStorageSeed.test.mjs b/fluxer_desktop/src/preload/LegacyRawStorageSeed.test.mjsdeleted file mode 100644index b5403cd24..000000000--- a/fluxer_desktop/src/preload/LegacyRawStorageSeed.test.mjs+++ /dev/null@@ -1,102 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {describe, test} from 'node:test';-import '../main/LocalAppTestSupport.test.mjs';--const {DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY, DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE} = await import(- '../../../packages/desktop_ipc/src/LegacyHarvestContract.ts'-);-const {applyLegacyRawLocalStorage} = await import('./LegacyRawStorageSeed.ts');--function createStorage(initial = {}, refuseKey = null) {- const entries = new Map(Object.entries(initial));- return {- entries,- getItem: (key) => entries.get(key) ?? null,- setItem: (key, value) => {- if (refuseKey === key) throw new Error('quota exceeded');- entries.set(key, value);- },- };-}--function installWindow(protocol, storage) {- globalThis.window = {location: {protocol}, localStorage: storage};- return storage;-}--function createRenderer(payload) {- const calls = [];- return {- calls,- sendSync: (channel) => {- calls.push(channel);- return payload;- },- };-}--describe('seeding the legacy localStorage onto the new origin', () => {- test('does nothing outside the local app scheme', () => {- const storage = installWindow('https:', createStorage());- const renderer = createRenderer({token: 'tok'});- applyLegacyRawLocalStorage(renderer);- assert.deepEqual(renderer.calls, []);- assert.equal(storage.entries.size, 0);- });-- test('seeds every harvested string key and records the witness once', () => {- const storage = installWindow('fluxer-app:', createStorage());- const renderer = createRenderer({token: 'tok', theme: 'dark', count: 3});- applyLegacyRawLocalStorage(renderer);- assert.equal(storage.getItem('token'), 'tok');- assert.equal(storage.getItem('theme'), 'dark');- assert.equal(storage.getItem('count'), null);- applyLegacyRawLocalStorage(renderer);- assert.equal(renderer.calls.length, 1);- });-- test('a harvested session marks the preboot session so the first frame is the signed-in shell', () => {- const storage = installWindow('fluxer-app:', createStorage());- applyLegacyRawLocalStorage(createRenderer({token: 'tok', userId: '42'}));- assert.equal(storage.getItem('fluxer:gateway:preboot:session'), '1');- });-- test('a half session or one the new origin already holds leaves the preboot marker alone', () => {- const tokenOnly = installWindow('fluxer-app:', createStorage());- applyLegacyRawLocalStorage(createRenderer({token: 'tok'}));- assert.equal(tokenOnly.getItem('fluxer:gateway:preboot:session'), null);- const current = installWindow('fluxer-app:', createStorage({token: 'the new token', userId: '7'}));- applyLegacyRawLocalStorage(createRenderer({token: 'tok', userId: '42'}));- assert.equal(current.getItem('fluxer:gateway:preboot:session'), null);- });-- test('never overwrites a value the new origin already holds', () => {- const storage = installWindow('fluxer-app:', createStorage({token: 'the new token'}));- applyLegacyRawLocalStorage(createRenderer({token: 'the legacy token'}));- assert.equal(storage.getItem('token'), 'the new token');- });-- test('ignores a witness carried inside the harvested corpus', () => {- const storage = installWindow('fluxer-app:', createStorage());- applyLegacyRawLocalStorage(createRenderer({[DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY]: 'stale', token: 'tok'}));- assert.equal(- storage.getItem(DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY),- DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE,- );- });-- test('a refused preboot read leaves the witness unset so a later launch retries', () => {- const storage = installWindow('fluxer-app:', createStorage());- applyLegacyRawLocalStorage(createRenderer(null));- assert.equal(storage.getItem(DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY), null);- });-- test('a storage that refuses a write leaves the witness unset', () => {- const storage = installWindow('fluxer-app:', createStorage({}, 'theme'));- applyLegacyRawLocalStorage(createRenderer({token: 'tok', theme: 'dark'}));- assert.equal(storage.getItem('token'), 'tok');- assert.equal(storage.getItem(DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY), null);- });-});