Repository navigation
recover from a corrupt desktop config.json instead of failing to start - #19501
Conversation
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
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
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
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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', () => { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 () => { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Agreed it's pre-existing; filed #19535 for closing the default window and fixing the doc comment.
| // dialog is the only feedback the user gets, so show it untracked then | ||
| let modalTracker: ModalDialogTracker | undefined; | ||
| try { | ||
| modalTracker = appState().modalTracker; |
There was a problem hiding this comment.
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.
| const backupPath = `${configPath}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`; | ||
| let warning: string; | ||
| try { | ||
| renameSync(configPath, backupPath); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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', { |
There was a problem hiding this comment.
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:
/Users/me/Library/Application Support/RStudio/config.json
(Config schema violation: `view/zoomLevel` must be <= 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.
There was a problem hiding this comment.
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 / or <; 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 '/Users/...'. Pass escapeValue: false, as gwt-callback.ts does, and cover the text that reaches dialog.showMessageBox with a test.
gtritchie
left a comment
There was a problem hiding this comment.
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.
Intent
Fixes #19496.
When RStudio Desktop's settings file (
config.jsonin 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: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.jsonis 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:
DesktopOptionsImplconstructs its electron-store with only a schema. conf parses and validatesconfig.jsoninside the constructor and rethrows a JSONSyntaxErroror a "Config schema violation". The first read happens ininitializeRenderingEngine(), before the Application singleton exists, so the throw aborts startup.RStudioMain.main()callscreateStandaloneErrorDialog, which needsappState().modalTracker.appState()throws "application not set" becausesetApplication()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: acreateConfigStore()helper wraps the store construction. On failure, ifconfig.jsonexists it is renamed toconfig.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'sclearInvalidConfigso 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-testdirectoryargument is unchanged.utils.ts:createStandaloneErrorDialogobtains the modal tracker in a try/catch and falls back to an untrackeddialog.showMessageBoxwhen the Application singleton is not set yet, so any future pre-ready startup failure still shows a dialog.utils.ts: the same function'sif (options.shouldCloseWindow) window.close();referred to a globalwindowthat does not exist in the main process, so the close threw and was swallowed by the catch; it now closesoptions.window. No caller passesshouldCloseWindow: truetoday.Automated Tests
Unit tests (
npm testinsrc/node/desktop):desktop-options.test.ts, newDesktopOptions with a corrupt config.jsonblock: a truncated file, a NUL-filled file, and a schema-violating file each construct successfully, return defaults, and leave exactly oneconfig.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 exactSyntaxError/ schema-violation errors from the forum reports.utils.test.ts:createStandaloneErrorDialogwith the Application singleton cleared callsdialog.showMessageBoxonce and logs no error. Failed before the fix with "application not set". A second test passes a window withshouldCloseWindow: trueand asserts that window'scloseis called and nothing is logged; before the fix the global-windowReferenceError was logged and the window stayed open.npm run lintandnpm run typecheckpass. The one unrelated unit test failing in this worktree (findComponents returns session and scripts paths) needs abuild/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
: > ~/.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.config.json.corrupt-<timestamp>sits next to a freshconfig.json.{"view":{"zoomLevel":"huge"}}: same recovery.Documentation
None needed.
Checklist
NEWS.md