From 4daa841475279350b9fe17cceb898c7e0b1e560f Mon Sep 17 00:00:00 2001 From: Shubham <87247136+shuseng8@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:51:04 +0530 Subject: [PATCH] Remember the last used folder per purpose in Desktop file dialogs. #10381 Native file dialogs in the desktop runtime shared a single remembered directory, so saving an ERD changed where the next Backup dialog opened. Callers now pass a purpose (e.g. 'backup', 'erd', 'query_tool') through FileManagerModule.showNative() and the preload shims, and the runtime keeps the last directory per purpose in its config store, falling back to the global last visited directory when a purpose has nothing saved yet. Signed-off-by: Shubham <87247136+shuseng8@users.noreply.github.com> --- runtime/src/js/pgadmin.js | 65 ++++++++++++----- runtime/src/js/pgadmin_preload.js | 4 +- .../static/js/subscription.ui.js | 8 +- .../servers/static/js/server.ui.js | 2 +- .../servers/static/js/variable.ui.js | 1 + .../misc/cloud/static/js/google_schema.ui.js | 1 + .../static/js/FileManagerModule.jsx | 6 +- .../static/js/components/binary_path.ui.jsx | 1 + .../static/js/components/FormComponents.jsx | 1 + .../tools/backup/static/js/backup.ui.js | 1 + .../tools/backup/static/js/backupGlobal.ui.js | 1 + .../static/js/erd_tool/components/ERDTool.jsx | 2 + .../static/js/import_export.ui.js | 1 + .../static/js/import_export_selection.ui.js | 2 + .../tools/restore/static/js/restore.ui.js | 1 + .../js/components/QueryToolComponent.jsx | 2 + .../components/FormComponents.spec.js | 13 ++++ .../file_manager/FileManagerModule.spec.js | 73 +++++++++++++++++++ 18 files changed, 157 insertions(+), 28 deletions(-) create mode 100644 web/regression/javascript/file_manager/FileManagerModule.spec.js diff --git a/runtime/src/js/pgadmin.js b/runtime/src/js/pgadmin.js index 4bd0e3a73c9..929b9a98ef1 100644 --- a/runtime/src/js/pgadmin.js +++ b/runtime/src/js/pgadmin.js @@ -545,34 +545,61 @@ function notifyUpdateInstalled() { // Native file dialogs don't reliably remember the last used directory across // calls, so we track it ourselves and use it as the default when the caller -// hasn't asked for a specific location. -async function withLastVisitedDirectory(options) { +// hasn't asked for a specific location. Callers may pass a purpose (e.g. +// 'backup' or 'erd') so that each kind of dialog remembers its own directory; +// a purpose with nothing saved yet falls back to the last directory used by +// any dialog. +function isValidDialogPurpose(purpose) { + return typeof purpose === 'string' && /^[a-z][a-z0-9_]*$/.test(purpose); +} + +async function isExistingDirectory(dirPath) { + if (!dirPath) { + return false; + } + try { + const stats = await fs.promises.stat(dirPath); + return stats.isDirectory(); + } catch { + // Remembered directory no longer exists (e.g. removable/network drive). + return false; + } +} + +async function withLastVisitedDirectory(options, purpose) { if (options.defaultPath) { return options; } - const lastVisitedDirectory = configStore.get('lastVisitedDirectory'); - if (!lastVisitedDirectory) { - return options; + const candidates = []; + if (isValidDialogPurpose(purpose)) { + candidates.push(configStore.get('lastVisitedDirectories')?.[purpose]); } - try { - const stats = await fs.promises.stat(lastVisitedDirectory); - if (stats.isDirectory()) { - return { ...options, defaultPath: lastVisitedDirectory }; + candidates.push(configStore.get('lastVisitedDirectory')); + for (const candidate of candidates) { + if (await isExistingDirectory(candidate)) { + return { ...options, defaultPath: candidate }; } - } catch { - // Remembered directory no longer exists (e.g. removable/network drive) - fall through. } return options; } -function rememberVisitedDirectory(options, result) { +function rememberVisitedDirectory(options, result, purpose) { const chosenPath = result.filePath || result.filePaths?.[0]; if (!chosenPath) { return; } const isDirectory = options.properties?.includes('openDirectory'); + const visitedDirectory = isDirectory ? chosenPath : path.dirname(chosenPath); try { - configStore.set('lastVisitedDirectory', isDirectory ? chosenPath : path.dirname(chosenPath)); + configStore.set('lastVisitedDirectory', visitedDirectory); + if (isValidDialogPurpose(purpose)) { + // Set the whole map rather than a dotted key path, so a purpose can never + // be interpreted as a nested property path by the store. + configStore.set('lastVisitedDirectories', { + ...configStore.get('lastVisitedDirectories'), + [purpose]: visitedDirectory, + }); + } } catch (error) { try { misc.writeServerLog(`Error remembering last visited directory: ${error}`); @@ -583,17 +610,17 @@ function rememberVisitedDirectory(options, result) { } // setup preload events. -ipcMain.handle('showOpenDialog', async (e, options) => { - const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options)); +ipcMain.handle('showOpenDialog', async (e, options, purpose) => { + const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options, purpose)); if (!result.canceled) { - rememberVisitedDirectory(options, result); + rememberVisitedDirectory(options, result, purpose); } return result; }); -ipcMain.handle('showSaveDialog', async (e, options) => { - const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options)); +ipcMain.handle('showSaveDialog', async (e, options, purpose) => { + const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options, purpose)); if (!result.canceled) { - rememberVisitedDirectory(options, result); + rememberVisitedDirectory(options, result, purpose); } return result; }); diff --git a/runtime/src/js/pgadmin_preload.js b/runtime/src/js/pgadmin_preload.js index 3b2d23e6682..c9ca7697d78 100644 --- a/runtime/src/js/pgadmin_preload.js +++ b/runtime/src/js/pgadmin_preload.js @@ -21,8 +21,8 @@ contextBridge.exposeInMainWorld('electronUI', { setMenuItems: (menu, menuItems) => { ipcRenderer.send('set-menu-items', menu, menuItems); }, - showOpenDialog: (options) => ipcRenderer.invoke('showOpenDialog', options), - showSaveDialog: (options) => ipcRenderer.invoke('showSaveDialog', options), + showOpenDialog: (options, purpose) => ipcRenderer.invoke('showOpenDialog', options, purpose), + showSaveDialog: (options, purpose) => ipcRenderer.invoke('showSaveDialog', options, purpose), log: (text)=> ipcRenderer.send('log', text), reloadApp: ()=>{ipcRenderer.send('reloadApp');}, // Download related functions diff --git a/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js b/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js index 89651e932dd..fabeb6c935e 100644 --- a/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js +++ b/web/pgadmin/browser/server_groups/servers/databases/subscriptions/static/js/subscription.ui.js @@ -219,7 +219,7 @@ export default class SubscriptionSchema extends BaseUISchema{ group: gettext('SSL'), mode: ['edit', 'create'], disabled: obj.isSSL, controlProps: { - dialogType: 'select_file', supportedTypes: ['*'], + dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'], }, deps: ['sslmode'], }, @@ -228,7 +228,7 @@ export default class SubscriptionSchema extends BaseUISchema{ group: gettext('SSL'), mode: ['edit', 'create'], disabled: obj.isSSL, controlProps: { - dialogType: 'select_file', supportedTypes: ['*'], + dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'], }, deps: ['sslmode'], },{ @@ -236,7 +236,7 @@ export default class SubscriptionSchema extends BaseUISchema{ group: gettext('SSL'), mode: ['edit', 'create'], disabled: obj.isSSL, controlProps: { - dialogType: 'select_file', supportedTypes: ['*'], + dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'], }, deps: ['sslmode'], },{ @@ -244,7 +244,7 @@ export default class SubscriptionSchema extends BaseUISchema{ group: gettext('SSL'), mode: ['edit', 'create'], disabled: obj.isSSL, controlProps: { - dialogType: 'select_file', supportedTypes: ['*'], + dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'], }, deps: ['sslmode'], }, diff --git a/web/pgadmin/browser/server_groups/servers/static/js/server.ui.js b/web/pgadmin/browser/server_groups/servers/static/js/server.ui.js index f72f6134c36..d8935700298 100644 --- a/web/pgadmin/browser/server_groups/servers/static/js/server.ui.js +++ b/web/pgadmin/browser/server_groups/servers/static/js/server.ui.js @@ -513,7 +513,7 @@ export default class ServerSchema extends BaseUISchema { id: 'tunnel_identity_file', label: gettext('Identity file'), type: 'file', group: gettext('SSH Tunnel'), mode: ['properties', 'edit', 'create'], controlProps: { - dialogType: 'select_file', supportedTypes: ['*'], + dialogType: 'select_file', dialogPurpose: 'ssh_identity', supportedTypes: ['*'], }, deps: ['tunnel_authentication', 'use_ssh_tunnel'], depChange: (state)=>{ diff --git a/web/pgadmin/browser/server_groups/servers/static/js/variable.ui.js b/web/pgadmin/browser/server_groups/servers/static/js/variable.ui.js index e8dfc3474ff..cd1968d63cc 100644 --- a/web/pgadmin/browser/server_groups/servers/static/js/variable.ui.js +++ b/web/pgadmin/browser/server_groups/servers/static/js/variable.ui.js @@ -140,6 +140,7 @@ export default class VariableSchema extends BaseUISchema { cell: 'file', controlProps: { dialogType: 'select_file', + dialogPurpose: 'certificates', supportedTypes: ['*'], placeholder: this.getPlaceHolderMsg(variable) } diff --git a/web/pgadmin/misc/cloud/static/js/google_schema.ui.js b/web/pgadmin/misc/cloud/static/js/google_schema.ui.js index 4c4fe7161ed..5696f20791e 100644 --- a/web/pgadmin/misc/cloud/static/js/google_schema.ui.js +++ b/web/pgadmin/misc/cloud/static/js/google_schema.ui.js @@ -41,6 +41,7 @@ class GoogleCredSchema extends BaseUISchema{ helpMessage: gettext('Select a client secrets file containing the client ID, client secret, and other OAuth 2.0 parameters for Google authentication. See Manage OAuth Clients in the Google Cloud documentation for how to create one.'), controlProps: { dialogType: 'select_file', + dialogPurpose: 'cloud_credentials', supportedTypes: ['json'], dialogTitle: 'Select file', }, diff --git a/web/pgadmin/misc/file_manager/static/js/FileManagerModule.jsx b/web/pgadmin/misc/file_manager/static/js/FileManagerModule.jsx index 61c7a17762c..063d0783a05 100644 --- a/web/pgadmin/misc/file_manager/static/js/FileManagerModule.jsx +++ b/web/pgadmin/misc/file_manager/static/js/FileManagerModule.jsx @@ -95,14 +95,16 @@ export default class FileManagerModule { {name: `${v.toUpperCase()} File .${v}`, extensions:[v]} )); + // The purpose lets the desktop runtime remember the last used folder + // separately for each kind of dialog (e.g. backups vs ERD diagrams). if(params.dialog_type == 'create_file') { - res = await window.electronUI.showSaveDialog(options); + res = await window.electronUI.showSaveDialog(options, params.purpose); } else { options['properties'] = ['openFile']; if(params.dialog_type == 'select_folder') { options['properties'] = ['openDirectory']; } - res = await window.electronUI.showOpenDialog(options); + res = await window.electronUI.showOpenDialog(options, params.purpose); } if(res.canceled) { diff --git a/web/pgadmin/preferences/static/js/components/binary_path.ui.jsx b/web/pgadmin/preferences/static/js/components/binary_path.ui.jsx index da4291fda5d..f791a2d2a05 100644 --- a/web/pgadmin/preferences/static/js/components/binary_path.ui.jsx +++ b/web/pgadmin/preferences/static/js/components/binary_path.ui.jsx @@ -56,6 +56,7 @@ export default class BinaryPathSchema extends BaseUISchema { }, controlProps: { dialogType: 'select_folder', + dialogPurpose: 'binary_path', supportedTypes: ['*', 'sql', 'backup'], dialogTitle: gettext('Select folder'), placeholder: pgAdmin.server_mode == 'False' ? gettext('Select binary path...') : gettext('Enter binary path...') diff --git a/web/pgadmin/static/js/components/FormComponents.jsx b/web/pgadmin/static/js/components/FormComponents.jsx index 29b129e1bf3..38122e008c9 100644 --- a/web/pgadmin/static/js/components/FormComponents.jsx +++ b/web/pgadmin/static/js/components/FormComponents.jsx @@ -544,6 +544,7 @@ export function InputFileSelect({ controlProps, onChange, disabled, readonly, is dialog_type: controlProps.dialogType || 'select_file', dialog_title: controlProps.dialogTitle || '', btn_primary: controlProps.btnPrimary || '', + purpose: controlProps.dialogPurpose, }; showFileManager(params, (fileName, dir)=>{ if (dir && dir != MY_STORAGE){ diff --git a/web/pgadmin/tools/backup/static/js/backup.ui.js b/web/pgadmin/tools/backup/static/js/backup.ui.js index 494ef50b144..8b6af5a0705 100644 --- a/web/pgadmin/tools/backup/static/js/backup.ui.js +++ b/web/pgadmin/tools/backup/static/js/backup.ui.js @@ -606,6 +606,7 @@ export default class BackupSchema extends BaseUISchema { disabled: false, controlProps: { dialogType: 'create_file', + dialogPurpose: 'backup', supportedTypes: ['*', 'sql', 'backup'], dialogTitle: 'Select file', }, diff --git a/web/pgadmin/tools/backup/static/js/backupGlobal.ui.js b/web/pgadmin/tools/backup/static/js/backupGlobal.ui.js index 6c05cf3437b..d0d56888c17 100644 --- a/web/pgadmin/tools/backup/static/js/backupGlobal.ui.js +++ b/web/pgadmin/tools/backup/static/js/backupGlobal.ui.js @@ -73,6 +73,7 @@ export default class BackupGlobalSchema extends BaseUISchema { disabled: false, controlProps: { dialogType: 'create_file', + dialogPurpose: 'backup', supportedTypes: ['*', 'sql', 'backup'], dialogTitle: 'Select file', }, diff --git a/web/pgadmin/tools/erd/static/js/erd_tool/components/ERDTool.jsx b/web/pgadmin/tools/erd/static/js/erd_tool/components/ERDTool.jsx index 78ed092955b..8967f7b0fb4 100644 --- a/web/pgadmin/tools/erd/static/js/erd_tool/components/ERDTool.jsx +++ b/web/pgadmin/tools/erd/static/js/erd_tool/components/ERDTool.jsx @@ -715,6 +715,7 @@ export default class ERDTool extends React.Component { const params = { 'supported_types': ['*','pgerd'], // file types allowed 'dialog_type': 'select_file', // open select file dialog + 'purpose': 'erd', }; this.props.pgAdmin.Tools.FileManager.show(params, this.openFile.bind(this), null, this.context); } @@ -750,6 +751,7 @@ export default class ERDTool extends React.Component { 'dialog_type': 'create_file', 'dialog_title': 'Save File', 'btn_primary': 'Save', + 'purpose': 'erd', }; this.props.pgAdmin.Tools.FileManager.show(params, this.saveFile.bind(this), null, this.context); } diff --git a/web/pgadmin/tools/import_export/static/js/import_export.ui.js b/web/pgadmin/tools/import_export/static/js/import_export.ui.js index 4742b71117d..4aa8bb42483 100644 --- a/web/pgadmin/tools/import_export/static/js/import_export.ui.js +++ b/web/pgadmin/tools/import_export/static/js/import_export.ui.js @@ -79,6 +79,7 @@ export default class ImportExportSchema extends BaseUISchema { type: 'file', controlProps: { dialogType: state.is_import && !state?.is_query_export ? 'select_file' : 'create_file', + dialogPurpose: 'import_export_data', supportedTypes: ['csv', 'text','bin', '*'], dialogTitle: 'Select file', } diff --git a/web/pgadmin/tools/import_export_servers/static/js/import_export_selection.ui.js b/web/pgadmin/tools/import_export_servers/static/js/import_export_selection.ui.js index 80d870eda42..885ca0bfa08 100644 --- a/web/pgadmin/tools/import_export_servers/static/js/import_export_selection.ui.js +++ b/web/pgadmin/tools/import_export_servers/static/js/import_export_selection.ui.js @@ -42,6 +42,7 @@ export default class ImportExportSelectionSchema extends BaseUISchema { type: 'file', controlProps: { dialogType: 'create_file', + dialogPurpose: 'import_export_servers', supportedTypes: ['json'], dialogTitle: 'Create file', }, @@ -51,6 +52,7 @@ export default class ImportExportSelectionSchema extends BaseUISchema { type: 'file', controlProps: { dialogType: 'select_file', + dialogPurpose: 'import_export_servers', supportedTypes: ['json'], dialogTitle: 'Select file', }, diff --git a/web/pgadmin/tools/restore/static/js/restore.ui.js b/web/pgadmin/tools/restore/static/js/restore.ui.js index 5d0d2dd0ca4..485435f2496 100644 --- a/web/pgadmin/tools/restore/static/js/restore.ui.js +++ b/web/pgadmin/tools/restore/static/js/restore.ui.js @@ -460,6 +460,7 @@ export default class RestoreSchema extends BaseUISchema { type: 'file', controlProps: { dialogType: state.format == 'directory' ? 'select_folder' : 'select_file', + dialogPurpose: 'backup', supportedTypes: ['*', 'backup', 'sql', 'patch'], dialogTitle: 'Select file', } diff --git a/web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx b/web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx index fad7268ab27..26f309ca7c6 100644 --- a/web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx +++ b/web/pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx @@ -698,6 +698,7 @@ export default function QueryToolComponent({params, pgWindow, pgAdmin, selectedN let fileParams = { 'supported_types': ['sql', '*'], // file types allowed 'dialog_type': 'open_file', // open select file dialog + 'purpose': 'query_tool', }; if(openInNewTab){ pgAdmin.Tools.FileManager.show(fileParams, (fileName, storage)=>{ @@ -718,6 +719,7 @@ export default function QueryToolComponent({params, pgWindow, pgAdmin, selectedN 'dialog_type': 'create_file', 'dialog_title': 'Save File', 'btn_primary': 'Save', + 'purpose': 'query_tool', }; pgAdmin.Tools.FileManager.show(fileParams, (fileName)=>{ eventBus.current.fireEvent(QUERY_TOOL_EVENTS.SAVE_FILE, fileName); diff --git a/web/regression/javascript/components/FormComponents.spec.js b/web/regression/javascript/components/FormComponents.spec.js index 9d10bb6b382..8b3617e6b68 100644 --- a/web/regression/javascript/components/FormComponents.spec.js +++ b/web/regression/javascript/components/FormComponents.spec.js @@ -169,6 +169,19 @@ describe('FormComponents', ()=>{ expect(onChange).toHaveBeenCalledWith('selected/file'); }); + it('file select passes the dialog purpose', ()=>{ + ctrlRerender({ + controlProps: { + dialogType: 'create_file', dialogPurpose: 'backup', supportedTypes: ['*'], + }, + }); + fireEvent.click(screen.getByRole('button')); + expect(showFileManager.showFileManager).toHaveBeenLastCalledWith( + expect.objectContaining({dialog_type: 'create_file', purpose: 'backup'}), + expect.any(Function), + ); + }); + it('accessibility', ()=>{ onAccessibility(); }); diff --git a/web/regression/javascript/file_manager/FileManagerModule.spec.js b/web/regression/javascript/file_manager/FileManagerModule.spec.js new file mode 100644 index 00000000000..e70eca57d29 --- /dev/null +++ b/web/regression/javascript/file_manager/FileManagerModule.spec.js @@ -0,0 +1,73 @@ +///////////////////////////////////////////////////////////// +// +// pgAdmin 4 - PostgreSQL Tools +// +// Copyright (C) 2013 - 2026, The pgAdmin Development Team +// This software is released under the PostgreSQL Licence +// +////////////////////////////////////////////////////////////// + +import FileManagerModule from '../../../pgadmin/misc/file_manager/static/js/FileManagerModule'; + +// The dialog component is not needed for the native path, and importing it +// here would create a circular import back to the module under test. +jest.mock('../../../pgadmin/misc/file_manager/static/js/components/FileManager', ()=>()=>null); + +describe('FileManagerModule', ()=>{ + describe('showNative', ()=>{ + let fmModule; + + beforeEach(()=>{ + fmModule = new FileManagerModule({}); + window.electronUI = { + showSaveDialog: jest.fn().mockResolvedValue({canceled: false, filePath: '/backups/db.backup'}), + showOpenDialog: jest.fn().mockResolvedValue({canceled: false, filePaths: ['/diagrams/model.pgerd']}), + }; + }); + + afterEach(()=>{ + delete window.electronUI; + }); + + it('passes the purpose to the save dialog', async ()=>{ + const onOK = jest.fn(); + await fmModule.showNative({dialog_type: 'create_file', supported_types: ['backup'], purpose: 'backup'}, onOK); + expect(window.electronUI.showSaveDialog).toHaveBeenCalledWith( + expect.objectContaining({filters: [{name: 'BACKUP File .backup', extensions: ['backup']}]}), + 'backup', + ); + expect(onOK).toHaveBeenCalledWith('/backups/db.backup'); + }); + + it('passes the purpose to the open dialog', async ()=>{ + const onOK = jest.fn(); + await fmModule.showNative({dialog_type: 'select_file', supported_types: ['pgerd'], purpose: 'erd'}, onOK); + expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith( + expect.objectContaining({properties: ['openFile']}), + 'erd', + ); + expect(onOK).toHaveBeenCalledWith('/diagrams/model.pgerd'); + }); + + it('passes the purpose to the folder dialog', async ()=>{ + await fmModule.showNative({dialog_type: 'select_folder', purpose: 'binary_path'}); + expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith( + expect.objectContaining({properties: ['openDirectory']}), + 'binary_path', + ); + }); + + it('passes no purpose when the caller does not give one', async ()=>{ + await fmModule.showNative({dialog_type: 'open_file'}); + expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith(expect.any(Object), undefined); + }); + + it('calls onCancel when the dialog is cancelled', async ()=>{ + const onOK = jest.fn(), onCancel = jest.fn(); + window.electronUI.showSaveDialog.mockResolvedValue({canceled: true}); + await fmModule.showNative({dialog_type: 'create_file', purpose: 'query_tool'}, onOK, onCancel); + expect(onCancel).toHaveBeenCalled(); + expect(onOK).not.toHaveBeenCalled(); + }); + }); +});