Skip to content

recover from a corrupt desktop config.json instead of failing to start - #19501

Merged
kevinushey merged 6 commits into
mainfrom
bugfix/19496-corrupt-config-json
Nov 10, 2026
Merged

kevinushey merged 6 commits into
mainfrom
bugfix/19496-corrupt-config-json

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Fixes #19496.

When RStudio Desktop's settings file (config.json in the Electron user data directory, e.g. ~/.config/RStudio/config.json) is truncated or otherwise unreadable, RStudio never starts and shows no error. From a terminal the only output is:

[utils.ts] [createStandaloneErrorDialog] Error when creating Standalone Error Dialog:  Error: application not set
Unexpected end of JSON input

Two forum reports in the past year (209528, 209785); in both, the user eventually recovered by deleting ~/.config/rstudio (and the sibling ~/.config/RStudio). config.json is rewritten on every zoom change and window close, so a crash or power loss mid-write is enough to produce this.

Approach

Two defects combine to produce the silent failure:

  1. DesktopOptionsImpl constructs its electron-store with only a schema. conf parses and validates config.json inside the constructor and rethrows a JSON SyntaxError or a "Config schema violation". The first read happens in initializeRenderingEngine(), before the Application singleton exists, so the throw aborts startup.
  2. The catch in RStudioMain.main() calls createStandaloneErrorDialog, which needs appState().modalTracker. appState() throws "application not set" because setApplication() never ran, so the fallback dialog itself fails and the process exits with nothing shown.

Changes, all in src/node/desktop:

  • electron-desktop-options.ts: a createConfigStore() helper wraps the store construction. On failure, if config.json exists it is renamed to config.json.corrupt-<timestamp> (kept for inspection rather than silently discarded), a warning is written to the console and the logger, and the store is created again from defaults. If the rename itself fails (unwritable directory), the retry uses conf's clearInvalidConfig so the bad contents are ignored instead of thrown. The previous field-initializer plus constructor reassignment is replaced by a single constructor assignment; behavior for the unit-test directory argument is unchanged.

  • utils.ts: createStandaloneErrorDialog obtains the modal tracker in a try/catch and falls back to an untracked dialog.showMessageBox when the Application singleton is not set yet, so any future pre-ready startup failure still shows a dialog.

  • utils.ts: the same function's if (options.shouldCloseWindow) window.close(); referred to a global window that does not exist in the main process, so the close threw and was swallowed by the catch; it now closes options.window. No caller passes shouldCloseWindow: true today.

Automated Tests

Unit tests (npm test in src/node/desktop):

  • desktop-options.test.ts, new DesktopOptions with a corrupt config.json block: a truncated file, a NUL-filled file, and a schema-violating file each construct successfully, return defaults, and leave exactly one config.json.corrupt-* backup containing the original bytes; options persist again after recovery; a valid file is left alone. All five failed before the fix with the exact SyntaxError / schema-violation errors from the forum reports.
  • utils.test.ts: createStandaloneErrorDialog with the Application singleton cleared calls dialog.showMessageBox once and logs no error. Failed before the fix with "application not set". A second test passes a window with shouldCloseWindow: true and asserts that window's close is called and nothing is logged; before the fix the global-window ReferenceError was logged and the window stayed open.

npm run lint and npm run typecheck pass. The one unrelated unit test failing in this worktree (findComponents returns session and scripts paths) needs a build/ directory that the worktree does not have; it passes in the main checkout.

Not done: launching a packaged desktop build against a deliberately corrupted config.json. The unit tests exercise the exact constructor path that throws in production, but a manual check per the QA notes would confirm the end-to-end behavior.

QA Notes

  1. Quit RStudio Desktop.
  2. Truncate the settings file: on Linux : > ~/.config/RStudio/config.json; on macOS ~/Library/Application Support/RStudio/config.json; on Windows %APPDATA%\RStudio\config.json. Optionally write a few NUL bytes into it instead.
  3. Launch RStudio from a terminal. Before: no window, "application not set" on the console. After: RStudio starts with default zoom and window size, the console shows a warning naming the file it moved aside, and config.json.corrupt-<timestamp> sits next to a fresh config.json.
  4. Also try a schema violation, e.g. {"view":{"zoomLevel":"huge"}}: same recovery.

Documentation

None needed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards (no UI change)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

electron-store parses and validates config.json in its constructor and
rethrows a SyntaxError or schema violation. That first read happens in
initializeRenderingEngine(), before the Application singleton exists, so
a truncated file aborted startup; and createStandaloneErrorDialog needed
appState().modalTracker, so the fallback dialog failed too and the user
saw nothing but "application not set" on the console.

Move the damaged file aside as config.json.corrupt-<timestamp>, warn,
and start from defaults. Let createStandaloneErrorDialog show an
untracked dialog when the Application singleton is not set yet.

Addresses #19496
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 6, 2026
@kevinushey
kevinushey requested a review from gtritchie November 6, 2026 23:15
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
5454 0 242 5
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1366 0 45 1
✅ desktop-macos 1372 0 40 1
✅ desktop-windows 1360 0 56 2
✅ server-linux 1304 0 53 1
✅ setup 48 0 32 0

View report online


All platforms - commit cc898386a4462065c275031b19e1c44f3bf5f3d1 - Run #2154

createStandaloneErrorDialog referred to a global 'window' when shouldCloseWindow was set; the main process has none, so the close threw and was swallowed. No caller passes shouldCloseWindow today.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recovery works for the case the issue reports: a truncated or schema-violating config.json in a writable directory is moved aside, and startup continues. I checked this by running the createConfigStore logic against conf 15.1.0 (the lockfile version) with the real user-state schema.

The same run turned up two problems, both commented inline: the rename-failed fallback still throws, and errors other than corruption also trigger the reset. The other comments are smaller.


// with the bad file gone this is a fresh store; if it could not be moved,
// clearInvalidConfig makes conf ignore its contents instead of throwing
return create(true);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fallback doesn't help in the case the comment names (an unwritable directory). With clearInvalidConfig, conf's get store() returns {}. Then #initializeStore calls _validate, which runs Ajv with useDefaults: true and fills in the top-level schema defaults. deepEqual(fileStore, storeWithDefaults) then fails, so conf writes the file. In a read-only directory that write fails too.

Repro: truncated config.json in a 0555 directory. renameSync fails with EACCES, then create(true) throws EACCES: permission denied, open .../config.json.tmp-.... Startup still aborts, and the dialog shows the EACCES error, not the parse error.

Options: fall back to an in-memory store, or drop the fallback and its comment, since the improved dialog now surfaces the failure.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the fallback. If the rename fails the directory isn't writable, so conf's write of the defaults would fail too, as you found. a8ef3eb now throws one error naming the parse failure and the rename failure, and the startup dialog shows that.


try {
return create(false);
} catch (error: unknown) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This catch treats every constructor error as corruption. conf rethrows anything other than a SyntaxError or Config schema violation: even with clearInvalidConfig, but this code still renames the file.

Repro: a valid {"view":{"zoomLevel":1.25}} with mode 000 in a writable directory. The read throws EACCES, the file is moved to config.json.corrupt-*, and zoom comes back as 1. A write failure while conf fills defaults (e.g. ENOSPC) takes the same path, and then create(true) fails again, so startup still aborts with the settings already moved aside.

Suggest recovering only when error.name === 'SyntaxError' or the message starts with 'Config schema violation:', and rethrowing otherwise.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a8ef3eb: recovery is limited to SyntaxError and Config schema violation:, mirroring conf's own check, and anything else is rethrown. Covered by a test that chmods a valid config.json to 0000 and asserts EACCES with no backup written.


// the file logger is configured later in startup, so also say this on the console
console.warn(warning);
logger().logWarning(warning);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In production this always goes to the default NullLogger. The first ElectronDesktopOptions() call (in initializeRenderingEngine) runs before the only setLogger call, in ArgsManager.handleLogLevel(). So a user who launches from the dock or Start menu gets no record in rstudio.log and no notice in the UI that their desktop options were reset. Could the message be kept and logged once the logger is set up, or shown to the user?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6c5feb9. The store keeps the recovery details, and Application.beforeAppReady() logs them once the Winston logger is installed and shows a dialog after app ready, the same way state-folder problems are reported.


// conf parses config.json inside the ElectronStore constructor and throws on a
// damaged file; before #19496 that throw aborted startup with no dialog.
describe('DesktopOptions with a corrupt config.json', () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All five tests take the path where the rename succeeds. A chmod would cover the two cases above: 0o555 on kTestingConfigDirectory for the rename-failure fallback, and 0o000 on a valid config.json for an error that shouldn't trigger recovery.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added both in a8ef3eb: a 0555 directory, which now asserts the single combined error, and a 0000 file, which asserts no recovery. They skip on Windows and when running as root.

}
});

it('createStandaloneErrorDialog closes the window it was given when asked to', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Neither test has an Application singleton set: the first clears it, and nothing here calls setApplication. So the trackElectronModalAsync branch, which is the normal runtime path, isn't covered. A case with an Application set that asserts the tracker is used would cover it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 6c5feb9: a test that sets an Application and asserts the modal tracker is used once.

await showDialog();
}

if (options.shouldCloseWindow) options.window.close();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not introduced here, but next to this fix: when the caller doesn't pass a window, the default new BrowserWindow({ width: 0, height: 0 }) is created and never closed, because the default shouldCloseWindow is false. The non-fatal state-folder warning (application.ts:178) leaves that window open until closeAllSatellites runs. The function would ideally close the window it created itself, and the doc comment's "if you pass a custom window, you must pass shouldCloseWindow = true" has the ownership backwards. Fine as a follow-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it's pre-existing; filed #19535 for closing the default window and fixing the doc comment.

Comment thread src/node/desktop/src/main/utils.ts Outdated
// dialog is the only feedback the user gets, so show it untracked then
let modalTracker: ModalDialogTracker | undefined;
try {
modalTracker = appState().modalTracker;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: an exported hasApplication() in app-state.ts, next to clearApplicationSingleton(), would express this check directly and avoid using the exception for control flow. modalTracker = undefined in the catch is redundant, since the variable is already undefined.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 6c5feb9.

const backupPath = `${configPath}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
let warning: string;
try {
renameSync(configPath, backupPath);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, design trade-off: one schema violation resets every desktop option, including the valid ones (zoom, window bounds, fonts, the Windows R path). Today only view.zoomLevel's range and the renderer.engine enum can trigger it, so this mostly matters for downgrades after a schema change. Dropping only the paths Ajv reports would keep the rest. Not blocking.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving the whole-file reset for now. Only the zoom range and the renderer enum can trigger it today, the backup keeps every value, and dropping just the reported paths would need our own Ajv pass over the file. Happy to revisit if a schema change makes this more common.

… be moved aside

The catch around the store constructor treated every error as corruption: an unreadable (EACCES) or unwritable (ENOSPC) config.json was moved to config.json.corrupt-* and the user's settings discarded. Recover only from the two errors conf raises for a file it cannot use, a JSON SyntaxError or a schema violation, and rethrow the rest.

When the damaged file cannot be renamed, the directory is not writable, so the clearInvalidConfig fallback failed again while conf wrote the defaults, and the dialog showed that EACCES instead of the parse error. Drop the fallback and throw one error that names both problems.

Tests cover both paths with chmod; they skip on Windows and as root, where chmod cannot take access away.
The store is created in initializeRenderingEngine(), before handleLogLevel() installs the file logger and before the Application exists, so the warning only ever reached the NullLogger and the console. Keep the recovery details on DesktopOptionsImpl and have Application.beforeAppReady() log them and show a dialog after app ready, the same way state-folder problems are reported.

Also add hasApplication() so createStandaloneErrorDialog does not use the appState() throw for control flow, and cover the tracked-dialog path with an Application set.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. a8ef3eb and 6c5feb9 address the earlier comments. I re-ran the conf 15.1.0 reproduction against the new createConfigStore. Truncated, empty, NUL-filled and schema-violating files recover. A damaged file in a read-only directory gives the single combined error. A valid file with mode 000 rethrows EACCES and writes no backup. Agreed on deferring the default window to #19535 and on keeping the whole-file reset.

One new issue, in the reset dialog's text (inline).

.then(async () =>
createStandaloneErrorDialog(
i18next.t('applicationTs.desktopOptionsResetTitle'),
i18next.t('applicationTs.desktopOptionsResetMessage', {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i18next escapes interpolated values for HTML by default (escapeValue: true), and i18n-manager.ts doesn't change that. So the paths and the reason reach the native message box HTML-escaped. With i18next 26.4.2 and the same init options:

&#x2F;Users&#x2F;me&#x2F;Library&#x2F;Application Support&#x2F;RStudio&#x2F;config.json
(Config schema violation: `view&#x2F;zoomLevel` must be &lt;= 5)

On macOS and Linux that makes the backup path, the thing the dialog is there to show, hard to read. Passing interpolation: { escapeValue: false }, as gwt-callback.ts does for its interpolated paths, fixes it. The alternative is to concatenate the paths outside t(), as checkStateDirectories does.

A test that stubs dialog.showMessageBox and asserts the detail contains the literal backupPath would cover this, since nothing currently checks the text that reaches the dialog.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, thanks. Fixed in fb71812: the call now passes interpolation: { escapeValue: false }, as gwt-callback.ts does. Added a test in application.test.ts that stubs dialog.showMessageBox and asserts the detail contains the literal config path, backup path and reason, with no &#x2F; or &lt;; it fails without the fix.

The same escaping happens in rsessionNotFoundError (utils.ts), which interpolates the working directory the same way. Pre-existing, so I filed #19546 for it.

i18next escapes interpolated values for HTML by default, so the config
and backup paths reached the native message box as '&#x2F;Users&#x2F;...'.
Pass escapeValue: false, as gwt-callback.ts does, and cover the text that
reaches dialog.showMessageBox with a test.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fb71812 fixes the dialog text and the new test covers it. Optional nit: the while (!showMessageBox.called) loop in the new test has no bound, so if the dialog ever stopped appearing it would keep spinning after mocha times the test out.

@kevinushey
kevinushey merged commit 7370088 into main Nov 10, 2026
1 of 5 checks passed
@kevinushey
kevinushey deleted the bugfix/19496-corrupt-config-json branch November 10, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RStudio Desktop never starts when config.json is corrupt; the fallback error dialog throws "application not set"

2 participants