Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(desktop): start the account engine and stop startup on quit

Hampusb055c187b223
diff --git a/fluxer_desktop/src/main/Bootstrap.ts b/fluxer_desktop/src/main/Bootstrap.ts
index 6000629b2..d6048a126 100644
--- a/fluxer_desktop/src/main/Bootstrap.ts
+++ b/fluxer_desktop/src/main/Bootstrap.ts
@@ -167,6 +167,7 @@ async function runModuleBootstrap(): Promise<void> {
const {
armSecondInstanceForwarding,
getMainWindowFactory,
+ hasQuitStarted,
onMainWindowCreated,
onMainWindowReady,
setCommittedModuleFiles,
@@ -235,6 +236,10 @@ async function runModuleBootstrap(): Promise<void> {
await appendWindowsGpuDriverWorkaroundSwitches();
await app.whenReady();
+ if (hasQuitStarted()) {
+ logger.info('The app started quitting before it was ready, stopping the bootstrap');
+ return;
+ }
if (isStartMinimizedLaunch()) {
logger.info('Launched at login with start minimized, converging the modules without the splash');
@@ -819,6 +824,10 @@ async function runModuleBootstrap(): Promise<void> {
app.once('before-quit', () => {
closeSplashWindow();
});
+ if (hasQuitStarted()) {
+ logger.info('The app started quitting during module convergence, not launching the main app');
+ return;
+ }
await launchMainApp(permit, logger);
} catch (error) {
logger.error('The module bootstrap failed unexpectedly', error);
diff --git a/fluxer_desktop/src/main/ModuleBootHandoff.ts b/fluxer_desktop/src/main/ModuleBootHandoff.ts
index 2e107b6f1..b7de1b165 100644
--- a/fluxer_desktop/src/main/ModuleBootHandoff.ts
+++ b/fluxer_desktop/src/main/ModuleBootHandoff.ts
@@ -38,6 +38,8 @@ interface ModuleBootHandoffState {
openUrlForwarding: boolean;
openUrlSink: OpenUrlSink | null;
readonly bufferedOpenUrls: Array<string>;
+ quitGateArmed: boolean;
+ quitStarted: boolean;
readonly committedModuleFilesListeners: Set<CommittedModuleFilesListener>;
readonly mainWindowListeners: Set<MainWindowListener>;
readonly mainWindowReadyListeners: Set<MainWindowReadyListener>;
@@ -56,6 +58,8 @@ const handoffState: ModuleBootHandoffState = {
openUrlForwarding: false,
openUrlSink: null,
bufferedOpenUrls: [],
+ quitGateArmed: false,
+ quitStarted: false,
committedModuleFilesListeners: new Set(),
mainWindowListeners: new Set(),
mainWindowReadyListeners: new Set(),
@@ -69,10 +73,29 @@ function deliverSecondInstance(sink: SecondInstanceSink, argv: Array<string>): v
}
}
+function armQuitGate(): void {
+ if (handoffState.quitGateArmed) return;
+ handoffState.quitGateArmed = true;
+ app.once('before-quit', () => {
+ handoffState.quitStarted = true;
+ handoffState.bufferedSecondInstances.splice(0);
+ handoffState.bufferedOpenUrls.splice(0);
+ });
+}
+
+export function hasQuitStarted(): boolean {
+ return handoffState.quitStarted;
+}
+
export function armSecondInstanceForwarding(): void {
if (handoffState.secondInstanceForwarding) return;
handoffState.secondInstanceForwarding = true;
+ armQuitGate();
app.on('second-instance', (_event, argv) => {
+ if (handoffState.quitStarted) {
+ logger.info('Ignoring a second instance launch because the app is quitting');
+ return;
+ }
const sink = handoffState.secondInstanceSink;
if (sink == null) {
handoffState.bufferedSecondInstances.push(argv);
@@ -99,6 +122,10 @@ function deliverOpenUrl(sink: OpenUrlSink, url: string): void {
}
function forwardOpenUrl(url: string): void {
+ if (handoffState.quitStarted) {
+ logger.info('Ignoring an opened link because the app is quitting');
+ return;
+ }
const sink = handoffState.openUrlSink;
if (sink == null) {
handoffState.bufferedOpenUrls.push(url);
@@ -110,6 +137,7 @@ function forwardOpenUrl(url: string): void {
export function armOpenUrlForwarding(): void {
if (handoffState.openUrlForwarding) return;
handoffState.openUrlForwarding = true;
+ armQuitGate();
app.on('open-url', (event, url) => {
event.preventDefault();
forwardOpenUrl(url);
diff --git a/fluxer_desktop/src/main/ShutdownCleanup.ts b/fluxer_desktop/src/main/ShutdownCleanup.ts
new file mode 100644
index 000000000..19717d5cd
--- /dev/null
+++ b/fluxer_desktop/src/main/ShutdownCleanup.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createChildLogger} from '@electron/common/Logger';
+
+const logger = createChildLogger('Shutdown');
+
+interface ShutdownCleanupStep {
+ readonly name: string;
+ readonly run: () => Promise<unknown>;
+}
+
+interface ShutdownCleanupResult {
+ readonly unfinished: Array<string>;
+}
+
+export function settleShutdownCleanups(
+ steps: ReadonlyArray<ShutdownCleanupStep>,
+ deadlineMs: number,
+): Promise<ShutdownCleanupResult> {
+ const unfinished = new Set(steps.map((step) => step.name));
+ const settled = steps.map((step) =>
+ Promise.resolve()
+ .then(step.run)
+ .catch((error: unknown) => {
+ logger.error('A shutdown cleanup step failed', {step: step.name}, error);
+ })
+ .finally(() => {
+ unfinished.delete(step.name);
+ }),
+ );
+ return new Promise((resolve) => {
+ const deadline = setTimeout(() => {
+ const names = Array.from(unfinished);
+ logger.warn('Shutdown cleanup steps missed the deadline, exiting without them', {
+ steps: names,
+ deadlineMs,
+ });
+ resolve({unfinished: names});
+ }, deadlineMs);
+ void Promise.all(settled).then(() => {
+ clearTimeout(deadline);
+ resolve({unfinished: []});
+ });
+ });
+}
diff --git a/fluxer_desktop/src/main/index.ts b/fluxer_desktop/src/main/index.ts
index fad3a1e8f..52100b09c 100644
--- a/fluxer_desktop/src/main/index.ts
+++ b/fluxer_desktop/src/main/index.ts
@@ -5,12 +5,13 @@ import path from 'node:path';
import {getDesktopWindowBehaviorSettings, loadDesktopConfig} from '@electron/common/DesktopConfig';
import {
DESKTOP_APP_NAME,
- LINUX_DESKTOP_ENTRY_ID,
WINDOWS_APP_USER_MODEL_ID,
WINDOWS_TOAST_ACTIVATOR_CLSID,
} from '@electron/common/DesktopIdentity';
+import {errorMessage} from '@electron/common/ErrorMessage';
import {writeLogFilesUnder} from '@electron/common/Logger';
import {configureUserDataPath} from '@electron/common/UserDataPath';
+import {startAccountEngine, stopAccountEngine} from '@electron/main/AccountEngineIpc';
import {
APP_STORE_ADDON_PACKAGE,
createAppStoreBoundary,
@@ -84,6 +85,7 @@ import {createApplicationMenu} from '@electron/main/Menu';
import {
armOpenUrlForwarding,
armSecondInstanceForwarding,
+ hasQuitStarted,
setMainWindowFactory,
setOpenUrlSink,
setSecondInstanceSink,
@@ -96,6 +98,7 @@ import {
import {type NativeModulePreflightResult, runNativeModulePreflight} from '@electron/main/NativeModulePreflight';
import {armNativeProbeCache} from '@electron/main/NativeProbeCache';
import {applyPreReadyChromiumConfiguration} from '@electron/main/PreReadyChromium';
+import {settleShutdownCleanups} from '@electron/main/ShutdownCleanup';
import {cleanupLinuxChromiumSpellcheckDictionaries} from '@electron/main/Spellcheck';
import {
clearSavedWindowBounds,
@@ -264,7 +267,7 @@ if (launchConfigurationError) {
writeCliAndExit(process.stdout, formatDesktopDebugInfo(info), 0);
})
.catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
+ const message = errorMessage(error);
log.error('Failed to collect desktop debug info:', error);
writeCliAndExit(process.stderr, `Failed to collect Fluxer desktop debug info: ${message}`, 1);
});
@@ -331,7 +334,7 @@ if (launchConfigurationError) {
try {
nativeModulePreflight = runStartupPhase('native-module-preflight', runNativeModulePreflight);
} catch (error) {
- const message = error instanceof Error ? error.message : String(error);
+ const message = errorMessage(error);
log.error('[NativeModulePreflight] Fatal native module preflight failure:', error);
console.error(message);
try {
@@ -382,12 +385,16 @@ if (launchConfigurationError) {
});
armOpenUrlForwarding();
setOpenUrlSink(handleOpenUrl);
+ const stopStartupIfQuitting = (): void => {
+ if (hasQuitStarted()) throw new Error('The app started quitting during startup');
+ };
(app.isReady()
? Promise.resolve()
: runStartupPhaseAsync('gpu-driver-workarounds', appendWindowsGpuDriverWorkaroundSwitches)
)
.then(() => app.whenReady())
.then(async () => {
+ stopStartupIfQuitting();
log.info('App ready, initializing...');
try {
runStartupPhase('host-resolver', () => app.configureHostResolver({enableAdditionalDnsQueryTypes: false}));
@@ -395,6 +402,7 @@ if (launchConfigurationError) {
log.error('[Init] Failed to configure the host resolver:', error);
}
await runStartupPhaseAsync('launch-net-log', startLaunchNetLog);
+ stopStartupIfQuitting();
try {
runStartupPhase('system-trust', () => installDesktopSystemTrustVerifier(session.defaultSession));
} catch (error) {
@@ -407,6 +415,7 @@ if (launchConfigurationError) {
} catch (error) {
log.error('[DebugInfo] Failed to collect desktop debug info:', error);
}
+ stopStartupIfQuitting();
try {
runStartupPhase('linux-desktop-entry', () => {
if (ensureLinuxDesktopEntry()) {
@@ -488,6 +497,7 @@ if (launchConfigurationError) {
} catch (error) {
log.error('[AppStore] Desktop app store recovery failed:', error);
}
+ stopStartupIfQuitting();
try {
runStartupPhase('app-store-ipc', registerDesktopAppStorageHandlers);
} catch (error) {
@@ -498,6 +508,11 @@ if (launchConfigurationError) {
} catch (error) {
log.error('[NativeGateway] Failed to register native gateway transport IPC handlers:', error);
}
+ try {
+ runStartupPhase('account-engine', () => startAccountEngine(userDataConfig.base));
+ } catch (error) {
+ log.error('[AccountEngine] Failed to start the account engine:', error);
+ }
try {
runStartupPhase('ipc-handlers', registerIpcHandlers);
} catch (error) {
@@ -562,6 +577,7 @@ if (launchConfigurationError) {
} catch (error: unknown) {
log.error('[LegacyHarvest] Legacy origin harvest failed:', error);
}
+ stopStartupIfQuitting();
try {
runStartupPhase('runtime-config-ipc', registerDesktopRuntimeConfigHandlers);
} catch (error: unknown) {
@@ -602,9 +618,11 @@ if (launchConfigurationError) {
});
if (process.env.FLUXER_OFFLINE !== '1' && !shouldDisableModuleUpdatesForLaunch()) {
const {registerUpdater} = await import('@electron/main/Updater');
+ stopStartupIfQuitting();
registerUpdater(getMainWindow);
}
app.on('activate', () => {
+ if (hasQuitStarted()) return;
const mainWindow = getMainWindow();
if ((mainWindow === null || mainWindow.isDestroyed()) && !isMainWindowTakenOver()) {
createWindow();
@@ -616,6 +634,10 @@ if (launchConfigurationError) {
})
.catch((error: unknown) => {
startupWindowsPending = false;
+ if (hasQuitStarted()) {
+ log.info('[Startup] Stopped startup because the app is quitting');
+ return;
+ }
log.error('[Startup] whenReady chain rejected:', error);
});
app.on('window-all-closed', () => {
@@ -635,6 +657,7 @@ if (launchConfigurationError) {
}
});
const QUIT_WATCHDOG_MS = 15000;
+ const QUIT_CLEANUP_DEADLINE_MS = 5000;
let quitWatchdog: NodeJS.Timeout | null = null;
function armQuitWatchdog(reason: string): void {
if (quitWatchdog) return;
@@ -688,19 +711,14 @@ if (launchConfigurationError) {
cleanupNativeHardwareEncoderHandlers();
cleanupVirtmic();
destroyDesktopTray();
- const asyncCleanups: Array<Promise<unknown>> = [
- cleanupDesktopLocalAppProtocol().catch((error: unknown) => {
- log.error('[Shutdown] Failed to shut down the local app protocol:', error);
- }),
+ const asyncCleanups = [
+ {name: 'local-app-protocol', run: cleanupDesktopLocalAppProtocol},
+ {name: 'account-engine', run: stopAccountEngine},
];
if (netLog.currentlyLogging) {
- asyncCleanups.push(
- netLog.stopLogging().catch((error) => {
- log.warn('[DebugInfo] Failed to stop Chromium net log:', error);
- }),
- );
+ asyncCleanups.push({name: 'net-log', run: () => netLog.stopLogging()});
}
- void Promise.allSettled(asyncCleanups).finally(() => {
+ void settleShutdownCleanups(asyncCleanups, QUIT_CLEANUP_DEADLINE_MS).finally(() => {
log.info('[Shutdown] will-quit cleanup complete; exiting');
app.exit(0);
});