Skip to content

A local-first personal finance app

:electron: When data folder is unavailable show a friendly message (#8928)

Michael Clark2ff97090d6c3
diff --git a/packages/desktop-client/src/browser-preload.js b/packages/desktop-client/src/browser-preload.js
index 03afae4f28..ce45a5910e 100644
--- a/packages/desktop-client/src/browser-preload.js
+++ b/packages/desktop-client/src/browser-preload.js
@@ -267,4 +267,10 @@ global.Actual = {
moveBudgetDirectory: () => {
// Only for electron app
},
+
+ setDocumentDir: async () => {
+ throw new Error(
+ 'Changing the data folder is only available in the desktop app',
+ );
+ },
};
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsx
index 837284c387..f1d361b010 100644
--- a/packages/desktop-client/src/components/App.tsx
+++ b/packages/desktop-client/src/components/App.tsx
@@ -155,6 +155,14 @@ function AppInner() {
}
function ErrorFallback({ error }: FallbackProps) {
+ const dispatch = useDispatch();
+
+ // If startup failed mid-way, a loading message is still set. That hides
+ // every modal (see modalsSlice), including the FatalError one, so clear it.
+ useEffect(() => {
+ dispatch(setAppState({ loadingText: null }));
+ }, [dispatch]);
+
return (
<>
<AppBackground />
diff --git a/packages/desktop-client/src/components/FatalError.test.tsx b/packages/desktop-client/src/components/FatalError.test.tsx
index 56f49ccf09..b96da0a814 100644
--- a/packages/desktop-client/src/components/FatalError.test.tsx
+++ b/packages/desktop-client/src/components/FatalError.test.tsx
@@ -44,6 +44,45 @@ describe('FatalError', () => {
).toBeInTheDocument();
});
+ it('renders the data folder path and an access-denied hint for a DocumentDirFailure', () => {
+ const error = {
+ type: 'app-init-failure',
+ DocumentDirFailure: true,
+ path: 'C:\\Users\\peter\\Documents\\Actual',
+ code: 'EPERM',
+ message: 'EPERM: operation not permitted, mkdir',
+ };
+
+ render(<FatalError error={error} />, { wrapper: TestProviders });
+
+ expect(screen.getByText('Data folder unavailable')).toBeInTheDocument();
+ expect(
+ screen.getByText('C:\\Users\\peter\\Documents\\Actual'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/Access to this folder was denied/),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Restart app')).toBeInTheDocument();
+ });
+
+ it('renders the error code without the access-denied hint for a non-permission DocumentDirFailure', () => {
+ const error = {
+ type: 'app-init-failure',
+ DocumentDirFailure: true,
+ path: '/home/peter/blocked/Actual',
+ code: 'ENOTDIR',
+ message: 'ENOTDIR: not a directory, mkdir',
+ };
+
+ render(<FatalError error={error} />, { wrapper: TestProviders });
+
+ expect(screen.getByText('/home/peter/blocked/Actual')).toBeInTheDocument();
+ expect(screen.getByText(/ENOTDIR/)).toBeInTheDocument();
+ expect(
+ screen.queryByText(/Access to this folder was denied/),
+ ).not.toBeInTheDocument();
+ });
+
it('renders the generic simple message for an app-init-failure without a specific cause', () => {
const error = { type: 'app-init-failure' };
diff --git a/packages/desktop-client/src/components/FatalError.tsx b/packages/desktop-client/src/components/FatalError.tsx
index a68ea7f187..8b5f7376b8 100644
--- a/packages/desktop-client/src/components/FatalError.tsx
+++ b/packages/desktop-client/src/components/FatalError.tsx
@@ -3,24 +3,37 @@ import type { ReactNode } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Block } from '@actual-app/components/block';
-import { Button } from '@actual-app/components/button';
+import { Button, ButtonWithLoading } from '@actual-app/components/button';
import { Paragraph } from '@actual-app/components/paragraph';
import { SpaceBetween } from '@actual-app/components/space-between';
import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
+import { isElectron } from '@actual-app/core/shared/environment';
import { LazyLoadFailedError } from '@actual-app/core/shared/errors';
import { useModalState } from '#hooks/useModalState';
+import { DirectoryDisplay } from './common/DirectoryDisplay';
import { Link } from './common/Link';
import { Modal, ModalHeader } from './common/Modal';
import { Checkbox } from './forms';
+const DATA_FOLDER_DOCS_URL =
+ 'https://actualbudget.org/docs/troubleshooting/data-folder-access';
+
+// Filesystem error codes that mean "the OS refused access" rather than "the
+// location is missing or invalid".
+const ACCESS_DENIED_CODES = ['EPERM', 'EACCES'];
+
type AppError = Error & {
type?: string;
IDBFailure?: boolean;
SharedArrayBufferMissing?: boolean;
BackendInitFailure?: boolean;
+ DocumentDirFailure?: boolean;
+ path?: string;
+ code?: string;
};
type FatalErrorProps = {
@@ -70,7 +83,18 @@ function RenderSimple({ error }: RenderSimpleProps) {
</Text>
);
} else if ('BackendInitFailure' in error && error.BackendInitFailure) {
- msg = (
+ msg = isElectron() ? (
+ <Text>
+ <Trans>
+ Actual's backend process failed to start or stopped unexpectedly.
+ Restart the app to try again; if the problem persists, please get{' '}
+ <Link variant="external" to="https://actualbudget.org/contact">
+ in touch
+ </Link>{' '}
+ so it can be investigated.
+ </Trans>
+ </Text>
+ ) : (
<Text>
<Trans>
Actual couldn't load a critical backend worker. Reload the page to try
@@ -103,6 +127,118 @@ function RenderSimple({ error }: RenderSimpleProps) {
);
}
+type RenderDocumentDirErrorProps = {
+ path?: string;
+ code?: string;
+};
+
+function RenderDocumentDirError({ path, code }: RenderDocumentDirErrorProps) {
+ const isAccessDenied = code ? ACCESS_DENIED_CODES.includes(code) : false;
+
+ return (
+ <SpaceBetween
+ direction="vertical"
+ style={{
+ paddingBottom: 15,
+ lineHeight: '1.5em',
+ fontSize: 15,
+ }}
+ >
+ <Text>
+ <Trans>
+ Actual couldn't access the folder where it stores your budget files:
+ </Trans>
+ </Text>
+ {path && <DirectoryDisplay directory={path} />}
+ {isAccessDenied ? (
+ <Text>
+ <Trans>
+ Access to this folder was denied. This is usually caused by folder
+ permissions, or by security software (such as ransomware protection
+ or antivirus) blocking Actual. Allow Actual to use this folder, or
+ choose a different folder below.
+ </Trans>
+ </Text>
+ ) : (
+ <Text>
+ {code ? (
+ <Trans>The system reported the error code {{ code }}. </Trans>
+ ) : null}
+ <Trans>
+ Check that this location exists and that Actual is allowed to write
+ to it, or choose a different folder below.
+ </Trans>
+ </Text>
+ )}
+ <Text>
+ <Trans>
+ See{' '}
+ <Link variant="external" linkColor="muted" to={DATA_FOLDER_DOCS_URL}>
+ our troubleshooting documentation
+ </Link>{' '}
+ for step-by-step instructions.
+ </Trans>
+ </Text>
+ </SpaceBetween>
+ );
+}
+
+/**
+ * Lets the user pick a different budget data folder straight from the error
+ * screen. The backend isn't running at this point, so the choice is saved by
+ * the desktop app's main process and the app is relaunched.
+ */
+function ChooseDocumentDirButton() {
+ const { t } = useTranslation();
+ const [isChanging, setIsChanging] = useState(false);
+ const [chooseError, setChooseError] = useState('');
+
+ async function chooseDirectory() {
+ setChooseError('');
+
+ const chosenDirectories = await window.Actual.openFileDialog({
+ properties: ['openDirectory'],
+ });
+ const chosenDirectory = chosenDirectories?.[0];
+ if (!chosenDirectory) {
+ return;
+ }
+
+ setIsChanging(true);
+ try {
+ await window.Actual.setDocumentDir(chosenDirectory);
+ window.Actual.relaunch();
+ } catch (error) {
+ // The raw failure (path, IPC wrapping, OS error text) goes to the
+ // console for diagnosis; the user gets a plain explanation.
+ console.error('Could not change the data folder', error);
+ setChooseError(
+ t(
+ "That folder can't be used. Make sure it exists and that Actual is allowed to create files in it.",
+ ),
+ );
+ setIsChanging(false);
+ }
+ }
+
+ return (
+ <>
+ <ButtonWithLoading
+ variant="primary"
+ isLoading={isChanging}
+ onPress={chooseDirectory}
+ >
+ <Trans>Choose a different folder</Trans>
+ </ButtonWithLoading>
+ {chooseError && (
+ <Text style={{ color: theme.errorText, flexBasis: '100%' }}>
+ {chooseError}
+ </Text>
+ )}
+ </>
+ );
+}
+
function RenderLazyLoadError() {
return (
<SpaceBetween
@@ -208,14 +344,27 @@ export function FatalError({ error: rawError }: FatalErrorProps) {
// the actual cause.
Object.assign(new Error(JSON.stringify(rawError)), rawError)
: new Error(String(rawError));
- const showSimpleRender = 'type' in error && error.type === 'app-init-failure';
+ const isAppInitFailure = 'type' in error && error.type === 'app-init-failure';
+ const isDocumentDirError =
+ isAppInitFailure &&
+ 'DocumentDirFailure' in error &&
+ Boolean(error.DocumentDirFailure);
+ const documentDirPath =
+ 'path' in error && typeof error.path === 'string' ? error.path : undefined;
+ const documentDirCode =
+ 'code' in error && typeof error.code === 'string' ? error.code : undefined;
const isLazyLoadError = error instanceof LazyLoadFailedError;
+ let title = t('Fatal Error');
+ if (isLazyLoadError) {
+ title = t('Loading Error');
+ } else if (isDocumentDirError) {
+ title = t('Data folder unavailable');
+ }
+
return (
<Modal name={lastModal?.name ?? 'fatal-error'} isDismissable={false}>
- <ModalHeader
- title={isLazyLoadError ? t('Loading Error') : t('Fatal Error')}
- />
+ <ModalHeader title={title} />
<View
style={{
maxWidth: 500,
@@ -223,16 +372,24 @@ export function FatalError({ error: rawError }: FatalErrorProps) {
>
{isLazyLoadError ? (
<RenderLazyLoadError />
- ) : showSimpleRender ? (
+ ) : isDocumentDirError ? (
+ <RenderDocumentDirError
+ path={documentDirPath}
+ code={documentDirCode}
+ />
+ ) : isAppInitFailure ? (
<RenderSimple error={error} />
) : (
<RenderUIError />
)}
<Paragraph>
- <Button onPress={() => window.Actual.relaunch()}>
- <Trans>Restart app</Trans>
- </Button>
+ <View style={{ flexDirection: 'row', gap: 10, flexWrap: 'wrap' }}>
+ {isDocumentDirError && isElectron() && <ChooseDocumentDirButton />}
+ <Button onPress={() => window.Actual.relaunch()}>
+ <Trans>Restart app</Trans>
+ </Button>
+ </View>
</Paragraph>
<Paragraph isLast style={{ fontSize: 11 }}>
<Link variant="text" onClick={() => setShowError(state => !state)}>
diff --git a/packages/desktop-client/src/components/common/DirectoryDisplay.tsx b/packages/desktop-client/src/components/common/DirectoryDisplay.tsx
new file mode 100644
index 0000000000..1b62413427
--- /dev/null
+++ b/packages/desktop-client/src/components/common/DirectoryDisplay.tsx
@@ -0,0 +1,38 @@
+import React from 'react';
+
+import { styles } from '@actual-app/components/styles';
+import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+
+type DirectoryDisplayProps = {
+ directory: string;
+};
+
+/**
+ * Shows a filesystem path in a scrollable, single-line box so long paths stay
+ * readable without wrapping.
+ */
+export function DirectoryDisplay({ directory }: DirectoryDisplayProps) {
+ return (
+ <View style={{ flexDirection: 'row', gap: '0.5rem', width: '100%' }}>
+ <Text
+ title={directory}
+ style={{
+ backgroundColor: theme.pageBackground,
+ padding: '5px 10px',
+ borderRadius: 4,
+ overflow: 'auto',
+ whiteSpace: 'nowrap',
+ width: '100%',
+ ...styles.horizontalScrollbar,
+ '::-webkit-scrollbar': {
+ height: '8px',
+ },
+ }}
+ >
+ {directory}
+ </Text>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/modals/manager/ConfirmChangeDocumentDir.tsx b/packages/desktop-client/src/components/modals/manager/ConfirmChangeDocumentDir.tsx
index a4a7d6f488..fb6ad3e2c2 100644
--- a/packages/desktop-client/src/components/modals/manager/ConfirmChangeDocumentDir.tsx
+++ b/packages/desktop-client/src/components/modals/manager/ConfirmChangeDocumentDir.tsx
@@ -2,42 +2,18 @@ import React, { useCallback, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Button, ButtonWithLoading } from '@actual-app/components/button';
-import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { Information } from '#components/alerts';
+import { DirectoryDisplay } from '#components/common/DirectoryDisplay';
import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';
import { Checkbox } from '#components/forms';
import { useGlobalPref } from '#hooks/useGlobalPref';
import { addNotification } from '#notifications/notificationsSlice';
import { useDispatch } from '#redux';
-function DirectoryDisplay({ directory }: { directory: string }) {
- return (
- <View style={{ flexDirection: 'row', gap: '0.5rem', width: '100%' }}>
- <Text
- title={directory}
- style={{
- backgroundColor: theme.pageBackground,
- padding: '5px 10px',
- borderRadius: 4,
- overflow: 'auto',
- whiteSpace: 'nowrap',
- width: '100%',
- ...styles.horizontalScrollbar,
- '::-webkit-scrollbar': {
- height: '8px',
- },
- }}
- >
- {directory}
- </Text>
- </View>
- );
-}
-
export function ConfirmChangeDocumentDirModal({
currentBudgetDirectory,
newDirectory,
diff --git a/packages/desktop-electron/e2e/fixtures.ts b/packages/desktop-electron/e2e/fixtures.ts
index b74cc78cb9..e1b2fc31bc 100644
--- a/packages/desktop-electron/e2e/fixtures.ts
+++ b/packages/desktop-electron/e2e/fixtures.ts
@@ -1,4 +1,4 @@
-import { mkdir, rm } from 'node:fs/promises';
+import { mkdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { _electron, test as base } from '@playwright/test';
@@ -9,21 +9,39 @@ type ElectronFixtures = {
electronPage: Page;
};
+type ElectronOptions = {
+ /**
+ * When true, the app is launched with its budget data folder pointing
+ * inside a regular file, so creating the folder fails at startup. Used to
+ * exercise the startup error screen.
+ */
+ blockDocumentDir: boolean;
+};
+
// Create the extended test with fixtures
-export const test = base.extend<ElectronFixtures>({
- // oxlint-disable-next-line no-empty-pattern
- electronApp: async ({}, use, testInfo: TestInfo) => {
+export const test = base.extend<ElectronFixtures & ElectronOptions>({
+ blockDocumentDir: [false, { option: true }],
+
+ electronApp: async ({ blockDocumentDir }, use, testInfo: TestInfo) => {
const uniqueTestId = testInfo.testId.replace(/[^\w-]/g, '-');
const testDataDir = path.join('e2e/data/', uniqueTestId);
await rm(testDataDir, { recursive: true, force: true }); // ensure any leftover test data is removed
await mkdir(testDataDir, { recursive: true });
+ let documentDir = testDataDir;
+ if (blockDocumentDir) {
+ // A regular file can't contain a folder, so `mkdir <file>/Actual` fails
+ // deterministically on every platform.
+ documentDir = path.join(testDataDir, 'blocked');
+ await writeFile(documentDir, 'not a directory');
+ }
+
const app = await _electron.launch({
args: ['.'],
env: {
...process.env,
- ACTUAL_DOCUMENT_DIR: testDataDir,
+ ACTUAL_DOCUMENT_DIR: documentDir,
ACTUAL_DATA_DIR: testDataDir,
EXECUTION_CONTEXT: 'playwright',
NODE_ENV: 'development',
diff --git a/packages/desktop-electron/e2e/startup-errors.test.ts b/packages/desktop-electron/e2e/startup-errors.test.ts
new file mode 100644
index 0000000000..08d1b1a6df
--- /dev/null
+++ b/packages/desktop-electron/e2e/startup-errors.test.ts
@@ -0,0 +1,32 @@
+import { expect } from '@playwright/test';
+
+import { test } from './fixtures';
+
+test.describe('Startup errors', () => {
+ test.use({ blockDocumentDir: true });
+
+ test('shows which folder could not be used when the data folder is blocked', async ({
+ electronPage,
+ }) => {
+ await expect(
+ electronPage.getByText('Data folder unavailable'),
+ ).toBeVisible();
+
+ await expect(
+ electronPage.getByText(
+ "Actual couldn't access the folder where it stores your budget files:",
+ ),
+ ).toBeVisible();
+
+ // The failing path is `<ACTUAL_DOCUMENT_DIR>/Actual`, where
+ // ACTUAL_DOCUMENT_DIR points at a regular file named `blocked`.
+ await expect(electronPage.getByText(/blocked[\\/]Actual$/)).toBeVisible();
+
+ await expect(
+ electronPage.getByRole('button', { name: 'Choose a different folder' }),
+ ).toBeVisible();
+ await expect(
+ electronPage.getByRole('button', { name: 'Restart app' }),
+ ).toBeVisible();
+ });
+});
diff --git a/packages/desktop-electron/index.ts b/packages/desktop-electron/index.ts
index 40050b6e19..2408f751b3 100644
--- a/packages/desktop-electron/index.ts
+++ b/packages/desktop-electron/index.ts
@@ -1,7 +1,15 @@
import fs from 'fs';
import { createServer } from 'http';
import type { Server } from 'http';
-import { cp, mkdir, rm } from 'node:fs/promises';
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
import path from 'path';
import type { GlobalPrefsJson } from '@actual-app/core/types/prefs';
@@ -27,6 +35,7 @@ import type {
import { getMenu } from './menu';
import { retry as promiseRetry } from './retry';
+import type { AppInitFailurePayload } from './server';
import {
get as getWindowState,
listen as listenToWindowState,
@@ -70,6 +79,11 @@ let clientWin: BrowserWindow | null;
let serverProcess: UtilityProcess | null;
let syncServerProcess: UtilityProcess | null;
+// The last startup failure reported by (or observed on) the backend process.
+// Kept so a renderer that connects after the failure was posted still gets
+// told about it instead of waiting forever for a reply.
+let lastAppInitFailure: AppInitFailurePayload | null = null;
+
let oAuthServer: ReturnType<typeof createServer> | null;
let queuedClientWinLogs: string[] = []; // logs that are queued up until the client window is ready
@@ -143,15 +157,13 @@ if (isDev) {
process.traceProcessWarnings = true;
}
+const getGlobalPrefsPath = () =>
+ path.join(process.env.ACTUAL_DATA_DIR!, 'global-store.json');
+
async function loadGlobalPrefs() {
let state: GlobalPrefsJson = {};
try {
- state = JSON.parse(
- fs.readFileSync(
- path.join(process.env.ACTUAL_DATA_DIR!, 'global-store.json'),
- 'utf8',
- ),
- );
+ state = JSON.parse(fs.readFileSync(getGlobalPrefsPath(), 'utf8'));
} catch {
logMessage('info', 'Could not load global state - using defaults');
state = {};
@@ -160,7 +172,55 @@ async function loadGlobalPrefs() {
return state;
}
+// Like loadGlobalPrefs, but only a missing file falls back to defaults; a
+// read or parse failure is propagated so callers doing read-modify-write don't
+// overwrite a store they couldn't read.
+async function loadGlobalPrefsStrict(): Promise<GlobalPrefsJson> {
+ let contents: string;
+ try {
+ contents = await readFile(getGlobalPrefsPath(), 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return {};
+ }
+ throw error;
+ }
+
+ const parsed: unknown = JSON.parse(contents);
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('Global preferences file is not a JSON object');
+ }
+ return parsed as GlobalPrefsJson;
+}
+
+// Writes the global preferences file atomically (temp file + rename), the same
+// way loot-core's asyncStorage does. Only meant to be used while the backend
+// process is not running, otherwise the two would race for the file.
+async function saveGlobalPrefs(state: GlobalPrefsJson) {
+ const globalPrefsPath = getGlobalPrefsPath();
+ const temporaryPath = `${globalPrefsPath}.${process.pid}.main.tmp`;
+
+ try {
+ await writeFile(temporaryPath, JSON.stringify(state), 'utf8');
+ await rename(temporaryPath, globalPrefsPath);
+ } catch (error) {
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
+ throw error;
+ }
+}
+
+function reportAppInitFailure(payload: AppInitFailurePayload) {
+ lastAppInitFailure = payload;
+ logMessage('error', `Backend failed to start: ${payload.message}`);
+
+ if (clientWin) {
+ clientWin.webContents.send('message', payload);
+ }
+}
+
async function createBackgroundProcess() {
+ lastAppInitFailure = null;
+
const globalPrefs = await loadGlobalPrefs(); // ensures we have the latest settings - even when restarting the server
let envVariables: Env = {
...process.env, // required
@@ -198,7 +258,9 @@ async function createBackgroundProcess() {
logMessage('error', `Server Log: ${chunk.toString('utf8')}`);
});
- serverProcess.on('message', msg => {
+ const startedProcess = serverProcess;
+
+ startedProcess.on('message', msg => {
switch (msg.type) {
case 'captureEvent':
case 'captureBreadcrumb':
@@ -210,10 +272,33 @@ async function createBackgroundProcess() {
clientWin.webContents.send('message', msg);
}
break;
+ case 'app-init-failure':
+ reportAppInitFailure(msg as AppInitFailurePayload);
+ break;
default:
logMessage('info', 'Unknown server message: ' + msg.type);
}
});
+
+ startedProcess.on('exit', code => {
+ // `serverProcess` is cleared before an intentional kill (restart / quit),
+ // so if it still points at this process the exit was unexpected.
+ if (serverProcess !== startedProcess) {
+ return;
+ }
+ serverProcess = null;
+
+ // A failure that was already reported is more specific than "it exited".
+ if (lastAppInitFailure) {
+ return;
+ }
+
+ reportAppInitFailure({
+ type: 'app-init-failure',
+ BackendInitFailure: true,
+ message: `The backend process exited unexpectedly (exit code ${code})`,
+ });
+ });
}
async function startSyncServer() {
@@ -534,8 +619,9 @@ app.on('window-all-closed', () => {
app.on('before-quit', () => {
if (serverProcess) {
- serverProcess.kill();
+ const processToKill = serverProcess;
serverProcess = null;
+ processToKill.kill();
}
});
@@ -575,13 +661,49 @@ ipcMain.handle('start-oauth-server', async () => {
ipcMain.handle('restart-server', () => {
if (serverProcess) {
- serverProcess.kill();
+ const processToKill = serverProcess;
serverProcess = null;
+ processToKill.kill();
}
void createBackgroundProcess();
});
+// Lets the user pick a new budget data folder from the startup error screen,
+// when the backend (which normally owns the global preferences) is not
+// running. The app is relaunched by the renderer afterwards.
+ipcMain.handle('set-document-dir', async (_event, directory: string) => {
+ if (!directory) {
+ throw new Error('A directory must be provided');
+ }
+
+ if (!fs.existsSync(directory)) {
+ throw new Error(`The directory does not exist: ${directory}`);
+ }
+
+ // Probe that we can actually create something inside the chosen folder.
+ // Permission checks alone don't catch things like Windows Controlled Folder
+ // Access, which blocks writes without changing the folder's permissions.
+ const probePrefix = path.join(directory, '.actual-write-test-');
+ let probeDirectory: string;
+ try {
+ probeDirectory = await mkdtemp(probePrefix);
+ } catch (error) {
+ throw new Error(
+ `Actual is not allowed to create files in ${directory}: ${String(error)}`,
+ );
+ }
+ await rm(probeDirectory, { recursive: true, force: true }).catch(
+ () => undefined,
+ );
+
+ // Strict read: a corrupt or unreadable store must not be silently replaced
+ // by `{ document-dir }`, which would wipe the user's other preferences.
+ const globalPrefs = await loadGlobalPrefsStrict();
+ await saveGlobalPrefs({ ...globalPrefs, 'document-dir': directory });
+ logMessage('info', `Budget data folder changed to: ${directory}`);
+});
+
ipcMain.handle('relaunch', () => {
app.relaunch();
app.exit();
@@ -640,7 +762,12 @@ ipcMain.handle('open-in-file-manager', (event, filepath) => {
});
ipcMain.on('message', (_event, msg) => {
- if (!serverProcess) {
+ if (!serverProcess || lastAppInitFailure) {
+ // The backend isn't there to answer. If we know why, tell the renderer
+ // (again) so its pending requests reject instead of hanging forever.
+ if (lastAppInitFailure && clientWin) {
+ clientWin.webContents.send('message', lastAppInitFailure);
+ }
return;
}
diff --git a/packages/desktop-electron/preload.ts b/packages/desktop-electron/preload.ts
index 456c1dbe30..b124bf441f 100644
--- a/packages/desktop-electron/preload.ts
+++ b/packages/desktop-electron/preload.ts
@@ -101,6 +101,10 @@ contextBridge.exposeInMainWorld('Actual', {
);
},
+ setDocumentDir: (directory: string) => {
+ return ipcRenderer.invoke('set-document-dir', directory);
+ },
+
reload: async () => {
throw new Error('Reload not implemented in electron app');
},
diff --git a/packages/desktop-electron/server.ts b/packages/desktop-electron/server.ts
index 403661546d..c5339b55c2 100644
--- a/packages/desktop-electron/server.ts
+++ b/packages/desktop-electron/server.ts
@@ -2,6 +2,60 @@ import { retry as promiseRetry } from './retry';
const BACKEND_IMPORT_MAX_RETRIES = 30;
+/**
+ * Posted to the main process (and relayed to the renderer) when the backend
+ * cannot start. Mirrors the `app-init-failure` message the web worker posts so
+ * the renderer's FatalError modal can handle both the same way.
+ */
+export type AppInitFailurePayload = {
+ type: 'app-init-failure';
+ /** The folder Actual stores budgets in could not be created or accessed. */
+ DocumentDirFailure?: true;
+ /** The folder that could not be created (set with DocumentDirFailure). */
+ path?: string;
+ /** Node filesystem error code, e.g. EPERM, EACCES, ENOENT, ENOTDIR. */
+ code?: string;
+ /** Any other startup failure (bundle import, crash, unexpected exit). */
+ BackendInitFailure?: true;
+ message: string;
+ stack?: string;
+};
+
+function toAppInitFailurePayload(error: unknown): AppInitFailurePayload {
+ const message = error instanceof Error ? error.message : String(error);
+ const stack = error instanceof Error ? error.stack : undefined;
+
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'type' in error &&
+ error.type === 'DocumentDirError' &&
+ 'path' in error
+ ) {
+ return {
+ type: 'app-init-failure',
+ DocumentDirFailure: true,
+ path: String(error.path),
+ code: 'code' in error && error.code ? String(error.code) : undefined,
+ message,
+ stack,
+ };
+ }
+
+ return {
+ type: 'app-init-failure',
+ BackendInitFailure: true,
+ message,
+ stack,
+ };
+}
+
+function reportInitFailure(error: unknown) {
+ const payload = toAppInitFailurePayload(error);
+ console.error('Failed to initialize the backend:', error);
+ process.parentPort.postMessage(payload);
+}
+
const lazyLoadBackend = async (isDev: boolean) => {
if (process.env.lootCoreScript === undefined) {
throw new Error(
@@ -9,10 +63,11 @@ const lazyLoadBackend = async (isDev: boolean) => {
);
}
+ let bundle;
try {
// These retries are primarily for dev mode, where we watch for changes in loot-core
// In a packaged build this should always work the first time.
- const bundle = await promiseRetry(
+ bundle = await promiseRetry(
async (retry, number) => {
try {
return await import(process.env.lootCoreScript!);
@@ -31,12 +86,23 @@ const lazyLoadBackend = async (isDev: boolean) => {
factor: 1, // No exponential backoff
},
);
- bundle.initApp(isDev);
} catch (error) {
- console.error('Failed to init the server bundle after all retries:', error);
- throw new Error(
- `Failed to init the server bundle after all retries: ${String(error)}`,
+ reportInitFailure(
+ new Error(
+ `Failed to init the server bundle after all retries: ${String(error)}`,
+ ),
);
+ return;
+ }
+
+ try {
+ await bundle.initApp(isDev);
+ } catch (error) {
+ // Don't let this become an unhandled rejection (which would kill the
+ // process silently). Report it so the renderer can show the user what
+ // went wrong, and stay alive so the "exit" handler in the main process
+ // doesn't overwrite this more specific failure.
+ reportInitFailure(error);
}
};
diff --git a/packages/docs/docs-sidebar.js b/packages/docs/docs-sidebar.js
index 8a085e36db..3eb3791428 100644
--- a/packages/docs/docs-sidebar.js
+++ b/packages/docs/docs-sidebar.js
@@ -306,6 +306,7 @@ const sidebars = {
items: [
'troubleshooting/server',
'troubleshooting/shared-array-buffer',
+ 'troubleshooting/data-folder-access',
'troubleshooting/reset_password',
'troubleshooting/edge-browser',
],
diff --git a/packages/docs/docs/troubleshooting/data-folder-access.md b/packages/docs/docs/troubleshooting/data-folder-access.md
new file mode 100644
index 0000000000..c3f05529d4
--- /dev/null
+++ b/packages/docs/docs/troubleshooting/data-folder-access.md
@@ -0,0 +1,46 @@
+# Data Folder Access
+
+The desktop app keeps your budget files in a folder on your computer. By default this is a folder named `Actual` inside your Documents folder. If Actual is not allowed to create, read, or write to that folder, it cannot start.
+
+When this happens, the app shows a **Data folder unavailable** message instead of loading forever. The message includes the exact folder that could not be used, so you know where to look.
+
+## Common Causes
+
+### Windows Controlled Folder Access
+
+Windows includes a ransomware protection feature called **Controlled Folder Access**. When it is turned on, it blocks apps it does not recognize from writing to protected folders such as Documents. Actual is blocked silently, so the only sign is the error message.
+
+To allow Actual through Controlled Folder Access:
+
+1. Open **Windows Security** from the Start menu.
+2. Select **Virus & threat protection**.
+3. Under **Ransomware protection**, select **Manage ransomware protection**.
+4. Select **Allow an app through Controlled folder access**.
+5. Select **Add an allowed app**, then **Recently blocked apps**, and choose Actual. If it is not listed, select **Browse all apps** and pick the Actual program file instead.
+6. Restart Actual.
+
+:::tip
+If you prefer to keep Actual out of the protected folders, you can choose a different data folder instead. See [Choosing a Different Folder](#choosing-a-different-folder) below.
+:::
+
+### Antivirus Software
+
+Some antivirus programs also block apps from creating folders and files. If you use one, check its settings for a list of blocked apps or protected folders and add Actual as an exception. Then restart Actual.
+
+### Folder Permissions or a Missing Location
+
+If the message shows an error code other than a permission error, the folder location itself may be the problem. For example, the Documents folder may have been moved or removed, or it may be on a network drive or cloud storage service that is not connected.
+
+Check that the parent folder shown in the message exists and that your user account can create files in it. If you cannot fix the location, choose a different folder as described below.
+
+## Choosing a Different Folder
+
+You do not have to fix the blocked folder to keep using Actual. From the error message, select **Choose a different folder** and pick any folder your user account can write to. Actual checks that it can create files there, saves the choice, and restarts.
+
+If you already have budget files in the old folder, copy them into the new folder after the app restarts, or use the **Move files to new directory** option when changing the folder from within the app.
+
+Once the app is running you can change the folder again at any time: open **Settings** from the budget list and select the pencil button next to **Actual's data directory**.
+
+## Still Stuck?
+
+Open the developer tools with <Key mod="ctrl shift" k="i" /> and look at the **Console** tab. Any errors from the backend are printed there. Share them on the [Actual Budget Discord](https://discord.gg/pRYNYr4W5A) and someone will help you out.
diff --git a/packages/loot-core/src/platform/client/connection/index.electron.ts b/packages/loot-core/src/platform/client/connection/index.electron.ts
index ce4c0cbd4d..308006ebc9 100644
--- a/packages/loot-core/src/platform/client/connection/index.electron.ts
+++ b/packages/loot-core/src/platform/client/connection/index.electron.ts
@@ -10,12 +10,27 @@ const listeners = new Map();
let messageQueue = [];
let socketClient = null;
+// Set once the backend process reports it could not start. From then on every
+// pending and future request is rejected with the failure payload so the app
+// surfaces it (via the FatalError modal) instead of waiting forever.
+let appInitFailure = null;
+
+function rejectAllPendingRequests(failure) {
+ for (const handler of replyHandlers.values()) {
+ handler.reject(failure);
+ }
+ replyHandlers.clear();
+}
+
function connectSocket(onOpen) {
global.Actual.ipcConnect(function (client) {
client.on('message', data => {
const msg = data;
- if (msg.type === 'error') {
+ if (msg.type === 'app-init-failure') {
+ appInitFailure = msg;
+ rejectAllPendingRequests(msg);
+ } else if (msg.type === 'error') {
// An error happened while handling a message so cleanup the
// current reply handler and reject the promise. The error will
// be propagated to the caller through this promise rejection.
@@ -90,6 +105,11 @@ export const send: T.Send = function (
): ReturnType<T.Send> {
const [name, args, { catchErrors = false } = {}] = params;
return new Promise((resolve, reject) => {
+ if (appInitFailure) {
+ reject(appInitFailure);
+ return;
+ }
+
const id = uuidv4();
replyHandlers.set(id, { resolve, reject });
diff --git a/packages/loot-core/src/server/errors.ts b/packages/loot-core/src/server/errors.ts
index 86ae93a37f..1915c226ba 100644
--- a/packages/loot-core/src/server/errors.ts
+++ b/packages/loot-core/src/server/errors.ts
@@ -69,6 +69,33 @@ export class SyncError extends Error {
}
}
+/**
+ * Thrown when the folder Actual stores budget files in cannot be created or
+ * accessed (for example, Windows Controlled Folder Access blocking
+ * `Documents\Actual`). Carries the path and the underlying filesystem error
+ * code so the UI can tell the user exactly what went wrong.
+ */
+export class DocumentDirError extends Error {
+ type: 'DocumentDirError';
+ path: string;
+ code: string | undefined;
+
+ constructor(path: string, cause: unknown) {
+ const code =
+ cause && typeof cause === 'object' && 'code' in cause
+ ? String(cause.code)
+ : undefined;
+ const causeMessage = cause instanceof Error ? cause.message : String(cause);
+
+ super(`DocumentDirError: could not access ${path} (${causeMessage})`, {
+ cause,
+ });
+ this.type = 'DocumentDirError';
+ this.path = path;
+ this.code = code;
+ }
+}
+
export class ValidationError extends Error {}
export class TransactionError extends Error {}
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index 6ba51b3802..ea7a9e2c35 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -20,7 +20,7 @@ import { app as dashboardApp } from './dashboard/app';
import * as db from './db';
import * as encryption from './encryption';
import { app as encryptionApp } from './encryption/app';
-import { withErrorCode } from './errors';
+import { DocumentDirError, withErrorCode } from './errors';
import { app as filtersApp } from './filters/app';
import { app as forecastApp } from './forecast/app';
import { app as formulasApp } from './formulas/app';
@@ -182,10 +182,35 @@ async function setupDocumentsDir() {
documentDir = getDefaultDocumentDir();
}
- await ensureExists(documentDir);
+ try {
+ await ensureExists(documentDir);
+ await ensureUsable(documentDir);
+ } catch (error) {
+ // Surface the exact folder and the filesystem error so the desktop app
+ // can show the user what is blocking startup (e.g. Windows Controlled
+ // Folder Access) instead of hanging on the loading screen.
+ throw new DocumentDirError(documentDir, error);
+ }
fs._setDocumentDir(documentDir);
}
+// Existence alone isn't enough: the folder may be there but unreadable (no
+// permissions) or unwritable (Windows Controlled Folder Access blocks writes
+// without changing permissions). Fail fast here rather than half-way through
+// loading budgets.
+async function ensureUsable(dir) {
+ await fs.listDir(dir);
+
+ // Unique per run so we never touch (let alone delete) something the user
+ // put there; only the directory this call created is removed.
+ const probeName = `.actual-write-test-${Date.now()}-${Math.random()
+ .toString(36)
+ .slice(2)}`;
+ const probeDir = fs.join(dir, probeName);
+ await fs.mkdir(probeDir);
+ await fs.removeDir(probeDir);
+}
+
export async function initApp(isDev, socketName) {
await sqlite.init();
asyncStorage.init();
diff --git a/packages/loot-core/typings/window.ts b/packages/loot-core/typings/window.ts
index 97e4038a7c..b5bbb374ab 100644
--- a/packages/loot-core/typings/window.ts
+++ b/packages/loot-core/typings/window.ts
@@ -31,6 +31,13 @@ type Actual = {
currentBudgetDirectory: string,
newDirectory: string,
) => Promise<void>;
+ /**
+ * Persists the budget data folder directly from the desktop app's main
+ * process, so it works even when the backend failed to start. Validates
+ * that the folder exists and is writable. The app must be relaunched
+ * afterwards for the change to take effect.
+ */
+ setDocumentDir: (directory: string) => Promise<void>;
applyAppUpdate: () => Promise<void>;
ipcConnect: (callback: (client: IpcClient) => void) => void;
getServerSocket: () => Promise<Worker | null>;
diff --git a/upcoming-release-notes/desktop-data-folder-error.md b/upcoming-release-notes/desktop-data-folder-error.md
new file mode 100644
index 0000000000..ef9714a7c2
--- /dev/null
+++ b/upcoming-release-notes/desktop-data-folder-error.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [MikesGlitch]
+---
+
+Show a clear error in the desktop app, with the folder path and an option to pick another folder, when Actual can't create its data folder instead of loading forever