From b7ca3f4bd5ff7a83aa2f437a211d4e8cf890d495 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:10:27 +0000 Subject: [PATCH] feat(sftp): add default download folder setting (#4353) --- application/i18n/locales/en/vault.ts | 7 ++ application/i18n/locales/es/vault.ts | 7 ++ application/i18n/locales/ru/vault.ts | 7 ++ application/i18n/locales/zh-CN/terminal.ts | 7 ++ application/i18n/locales/zh-TW/terminal.ts | 7 ++ application/state/sftp/downloadLocation.ts | 21 ++++ application/state/useSftpBackend.ts | 13 ++- application/syncPayload.test.ts | 11 ++ .../tabs/SettingsFileAssociationsTab.tsx | 88 ++++++++++++++- components/sftp/hooks/useSftpViewFileOps.ts | 25 ++++- .../sftp/hooks/useSftpViewFileOps.types.ts | 12 +- .../sftp/hooks/useSftpViewPaneCallbacks.ts | 12 +- .../sftp/useSftpViewFileOps.download.test.ts | 85 ++++++++++++++ domain/settingsSearch.test.ts | 15 +++ domain/settingsSearchCatalog.ts | 8 ++ domain/sftpDownloadLocation.test.ts | 24 ++++ domain/sftpDownloadLocation.ts | 29 +++++ electron/main/dialogDefaultPath.cjs | 104 ++++++++++++++++++ electron/main/dialogDefaultPath.test.cjs | 90 +++++++++++++++ electron/main/registerBridges.cjs | 12 +- electron/preload/api.cjs | 8 +- infrastructure/config/storageKeys.ts | 6 + types/global/netcatty-bridge-files.d.ts | 18 ++- 23 files changed, 592 insertions(+), 24 deletions(-) create mode 100644 application/state/sftp/downloadLocation.ts create mode 100644 domain/sftpDownloadLocation.test.ts create mode 100644 domain/sftpDownloadLocation.ts create mode 100644 electron/main/dialogDefaultPath.cjs create mode 100644 electron/main/dialogDefaultPath.test.cjs diff --git a/application/i18n/locales/en/vault.ts b/application/i18n/locales/en/vault.ts index c565c9c91..611cfcfc9 100644 --- a/application/i18n/locales/en/vault.ts +++ b/application/i18n/locales/en/vault.ts @@ -619,6 +619,13 @@ export const enVaultMessages: Messages = { 'settings.sftp.packedDownload': 'Packed downloads', 'settings.sftp.packedDownload.enable': 'Pack folders and multiple items for download', 'settings.sftp.packedDownload.enableDesc': 'Download the selection in one stream and restore its original layout on this device. If the server cannot pack it, download files individually.', + 'settings.sftp.downloadLocation': 'Download location', + 'settings.sftp.downloadLocation.directory': 'Default download folder', + 'settings.sftp.downloadLocation.directoryDesc': 'SFTP download dialogs open in this folder. If it is not set or no longer exists, the system Downloads folder is used.', + 'settings.sftp.downloadLocation.systemDefault': 'System Downloads folder', + 'settings.sftp.downloadLocation.browse': 'Browse…', + 'settings.sftp.downloadLocation.reset': 'Use the system Downloads folder', + 'settings.sftp.downloadLocation.select': 'Choose default download folder', 'settings.sftp.skipUnchanged.enable': 'Skip unchanged files', 'settings.sftp.skipUnchanged.enableDesc': 'Skip files whose size and modification time already match the destination (rsync-style). Disabled when replacing a folder into a staging path.', diff --git a/application/i18n/locales/es/vault.ts b/application/i18n/locales/es/vault.ts index 57fa787fb..1d990ee44 100644 --- a/application/i18n/locales/es/vault.ts +++ b/application/i18n/locales/es/vault.ts @@ -619,6 +619,13 @@ export const esVaultMessages: Messages = { 'settings.sftp.packedDownload': 'Descargas empaquetadas', 'settings.sftp.packedDownload.enable': 'Empaquetar carpetas y selecciones múltiples para descargar', 'settings.sftp.packedDownload.enableDesc': 'Descarga la selección en una sola transferencia y restaura su estructura original en este dispositivo. Si el servidor no puede empaquetarla, los archivos se descargan por separado.', + 'settings.sftp.downloadLocation': 'Ubicación de descarga', + 'settings.sftp.downloadLocation.directory': 'Carpeta de descarga predeterminada', + 'settings.sftp.downloadLocation.directoryDesc': 'Los diálogos de descarga SFTP se abren en esta carpeta. Si no está configurada o ya no existe, se usa la carpeta Descargas del sistema.', + 'settings.sftp.downloadLocation.systemDefault': 'Carpeta Descargas del sistema', + 'settings.sftp.downloadLocation.browse': 'Examinar…', + 'settings.sftp.downloadLocation.reset': 'Usar la carpeta Descargas del sistema', + 'settings.sftp.downloadLocation.select': 'Elegir la carpeta de descarga predeterminada', 'settings.sftp.skipUnchanged.enable': 'Omitir archivos sin cambios', 'settings.sftp.skipUnchanged.enableDesc': 'Omite los archivos cuyo tamaño y hora de modificación ya coinciden con el destino (estilo rsync). Deshabilitado al reemplazar una carpeta en una ruta de staging.', diff --git a/application/i18n/locales/ru/vault.ts b/application/i18n/locales/ru/vault.ts index 330996b66..c0f78cd65 100644 --- a/application/i18n/locales/ru/vault.ts +++ b/application/i18n/locales/ru/vault.ts @@ -662,6 +662,13 @@ export const ruVaultMessages: Messages = { 'settings.sftp.packedDownload': 'Скачивание архивом', 'settings.sftp.packedDownload.enable': 'Упаковывать папки и выбранные вместе файлы перед скачиванием', 'settings.sftp.packedDownload.enableDesc': 'Выбранные файлы передаются одним потоком и распаковываются с сохранением структуры папок. Если сервер не поддерживает упаковку, файлы скачиваются по отдельности.', + 'settings.sftp.downloadLocation': 'Папка для загрузок', + 'settings.sftp.downloadLocation.directory': 'Папка загрузок по умолчанию', + 'settings.sftp.downloadLocation.directoryDesc': 'Диалоги скачивания по SFTP открываются в этой папке. Если она не задана или больше не существует, используется системная папка «Загрузки».', + 'settings.sftp.downloadLocation.systemDefault': 'Системная папка «Загрузки»', + 'settings.sftp.downloadLocation.browse': 'Обзор…', + 'settings.sftp.downloadLocation.reset': 'Использовать системную папку «Загрузки»', + 'settings.sftp.downloadLocation.select': 'Выберите папку загрузок по умолчанию', 'settings.sftp.skipUnchanged.enable': 'Пропускать неизменённые файлы', 'settings.sftp.skipUnchanged.enableDesc': 'Пропускать файлы, у которых размер и время изменения уже совпадают с назначением (в стиле rsync). Отключается при замене папки во временный путь.', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 4919eb009..ab72d4713 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -225,6 +225,13 @@ export const zhCNTerminalMessages: Messages = { 'settings.sftp.packedDownload': '打包下载', 'settings.sftp.packedDownload.enable': '下载文件夹或多选项目时打包', 'settings.sftp.packedDownload.enableDesc': '将所选内容一次传回,在本地自动还原原有目录结构。服务器不支持打包时,自动逐文件下载。', + 'settings.sftp.downloadLocation': '下载位置', + 'settings.sftp.downloadLocation.directory': '默认下载文件夹', + 'settings.sftp.downloadLocation.directoryDesc': '下载 SFTP 文件时,保存对话框默认打开此文件夹。未设置或文件夹已不存在时,使用系统“下载”文件夹。', + 'settings.sftp.downloadLocation.systemDefault': '系统“下载”文件夹', + 'settings.sftp.downloadLocation.browse': '浏览…', + 'settings.sftp.downloadLocation.reset': '恢复为系统“下载”文件夹', + 'settings.sftp.downloadLocation.select': '选择默认下载文件夹', 'settings.sftp.skipUnchanged.enable': '跳过未改文件', 'settings.sftp.skipUnchanged.enableDesc': '当目标文件的大小与修改时间已与源一致时跳过传输(类似 rsync)。替换到暂存路径时自动禁用。', diff --git a/application/i18n/locales/zh-TW/terminal.ts b/application/i18n/locales/zh-TW/terminal.ts index 5fb0c8eb8..18bf625cb 100644 --- a/application/i18n/locales/zh-TW/terminal.ts +++ b/application/i18n/locales/zh-TW/terminal.ts @@ -225,6 +225,13 @@ export const zhTWTerminalMessages: Messages = { 'settings.sftp.packedDownload': '打包下載', 'settings.sftp.packedDownload.enable': '下載資料夾或多個項目時打包', 'settings.sftp.packedDownload.enableDesc': '一次傳回所選內容,並在本機自動還原原本的資料夾結構。若伺服器不支援打包,會自動逐檔下載。', + 'settings.sftp.downloadLocation': '下載位置', + 'settings.sftp.downloadLocation.directory': '預設下載資料夾', + 'settings.sftp.downloadLocation.directoryDesc': '下載 SFTP 檔案時,儲存對話框預設開啟此資料夾。未設定或資料夾已不存在時,使用系統「下載」資料夾。', + 'settings.sftp.downloadLocation.systemDefault': '系統「下載」資料夾', + 'settings.sftp.downloadLocation.browse': '瀏覽…', + 'settings.sftp.downloadLocation.reset': '恢復為系統「下載」資料夾', + 'settings.sftp.downloadLocation.select': '選擇預設下載資料夾', 'settings.sftp.skipUnchanged.enable': '跳過未改檔案', 'settings.sftp.skipUnchanged.enableDesc': '當目標檔案的大小與修改時間已與來源一致時跳過傳輸(類似 rsync)。替換到暫存路徑時自動停用。', diff --git a/application/state/sftp/downloadLocation.ts b/application/state/sftp/downloadLocation.ts new file mode 100644 index 000000000..51d1a823b --- /dev/null +++ b/application/state/sftp/downloadLocation.ts @@ -0,0 +1,21 @@ +import { + buildSftpDownloadDialogDirectoryOptions, + type SftpDownloadDialogDirectoryOptions, +} from "../../../domain/sftpDownloadLocation"; +import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys"; +import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; + +/** + * Read the device-local default download folder at call time so every SFTP + * surface (main view, terminal side panel, other windows) sees the latest + * value without threading it through props. + */ +export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => { + let stored: string | null = null; + try { + stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR); + } catch { + // Storage unavailable (non-browser host); fall back to system Downloads. + } + return buildSftpDownloadDialogDirectoryOptions(stored); +}; diff --git a/application/state/useSftpBackend.ts b/application/state/useSftpBackend.ts index 9f6e8840f..7cb307363 100644 --- a/application/state/useSftpBackend.ts +++ b/application/state/useSftpBackend.ts @@ -159,17 +159,22 @@ export const useSftpBackend = () => { const showSaveDialog = useCallback(async ( defaultPath: string, - filters?: Array<{ name: string; extensions: string[] }> + filters?: Array<{ name: string; extensions: string[] }>, + directoryOptions?: NetcattyDialogDirectoryOptions, ) => { const bridge = netcattyBridge.get(); if (!bridge?.showSaveDialog) return null; - return bridge.showSaveDialog(defaultPath, filters); + return bridge.showSaveDialog(defaultPath, filters, directoryOptions); }, []); - const selectDirectory = async (title?: string, defaultPath?: string) => { + const selectDirectory = async ( + title?: string, + defaultPath?: string, + directoryOptions?: NetcattyDialogDirectoryOptions, + ) => { const bridge = netcattyBridge.get(); if (!bridge?.selectDirectory) return null; - return bridge.selectDirectory(title, defaultPath); + return bridge.selectDirectory(title, defaultPath, directoryOptions); }; return { diff --git a/application/syncPayload.test.ts b/application/syncPayload.test.ts index f3fdd7b62..b008f635d 100644 --- a/application/syncPayload.test.ts +++ b/application/syncPayload.test.ts @@ -2389,3 +2389,14 @@ test('sync prepares header encryption once before importing and leaves input unc assert.equal(JSON.stringify(payload), original); assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed }); }); + +test("SFTP default download folder stays device-local and is never synced", async () => { + const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR; + assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false); + localStorage.clear(); + localStorage.setItem(key, "/Users/me/server-files"); + const payload = buildSyncPayload(vault()); + assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false); + await applySyncPayload(payload, { importVaultData: () => {} }); + assert.equal(localStorage.getItem(key), "/Users/me/server-files"); +}); diff --git a/components/settings/tabs/SettingsFileAssociationsTab.tsx b/components/settings/tabs/SettingsFileAssociationsTab.tsx index 903819ac1..84e24b7b4 100644 --- a/components/settings/tabs/SettingsFileAssociationsTab.tsx +++ b/components/settings/tabs/SettingsFileAssociationsTab.tsx @@ -1,13 +1,20 @@ /** * SettingsFileAssociationsTab - Manage SFTP file opener associations and behavior */ -import { FileType, Pencil, Trash2 } from "lucide-react"; +import { FileType, Pencil, RotateCcw, Trash2 } from "lucide-react"; import React, { useCallback, useMemo, useState } from "react"; import { useI18n } from "../../../application/i18n/I18nProvider"; import { useSftpFileAssociations } from "../../../application/state/useSftpFileAssociations"; import { useSettingsState } from "../../../application/state/useSettingsState"; import { useStoredString } from "../../../application/state/useStoredString"; -import { STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD } from "../../../infrastructure/config/storageKeys"; +import { + STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR, + STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD, +} from "../../../infrastructure/config/storageKeys"; +import { + buildSftpDownloadDialogDirectoryOptions, + normalizeSftpDefaultDownloadDirectory, +} from "../../../domain/sftpDownloadLocation"; import type { FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; import { Button } from "../../ui/button"; @@ -16,6 +23,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip"; import { SectionHeader, SettingCard, + SettingsAnchor, SettingsTabContent, SettingRow, Toggle, @@ -38,6 +46,9 @@ const getOpenerLabel = ( export default function SettingsFileAssociationsTab() { const { t } = useI18n(); const [packedDownload, setPackedDownload] = useStoredString(STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD, "true"); + const [storedDownloadDir, setStoredDownloadDir] = useStoredString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR, ""); + const defaultDownloadDir = normalizeSftpDefaultDownloadDirectory(storedDownloadDir); + const [isSelectingDownloadDir, setIsSelectingDownloadDir] = useState(false); const { getAllAssociations, removeAssociation, setOpenerForExtension, getDefaultOpener, setDefaultOpener, removeDefaultOpener } = useSftpFileAssociations(); const { sftpDoubleClickBehavior, setSftpDoubleClickBehavior, @@ -102,6 +113,24 @@ export default function SettingsFileAssociationsTab() { void handleSelectDefaultSystemApp(); }, [handleSelectDefaultSystemApp, removeDefaultOpener, setDefaultOpener]); + const handleSelectDownloadDir = useCallback(async () => { + const bridge = netcattyBridge.get(); + if (!bridge?.selectDirectory) return; + setIsSelectingDownloadDir(true); + try { + const selected = await bridge.selectDirectory( + t('settings.sftp.downloadLocation.select'), + undefined, + buildSftpDownloadDialogDirectoryOptions(defaultDownloadDir), + ); + if (selected) setStoredDownloadDir(selected); + } catch (e) { + console.error('Failed to select download directory:', e); + } finally { + setIsSelectingDownloadDir(false); + } + }, [defaultDownloadDir, setStoredDownloadDir, t]); + const handleEdit = useCallback(async (extension: string) => { setEditingExtension(extension); try { @@ -191,6 +220,61 @@ export default function SettingsFileAssociationsTab() { + + + +
+
{t('settings.sftp.downloadLocation.directory')}
+
+ {t('settings.sftp.downloadLocation.directoryDesc')} +
+
+
+
+ {defaultDownloadDir ? ( + + +
+ {defaultDownloadDir} +
+
+ {defaultDownloadDir} +
+ ) : ( +
+ {t('settings.sftp.downloadLocation.systemDefault')} +
+ )} +
+ + {defaultDownloadDir && ( + + + + + {t('settings.sftp.downloadLocation.reset')} + + )} +
+
+
+ getParentPath(path)); - let selectedDirectory = await selectDirectory(t("sftp.context.download")); + let selectedDirectory = await selectDirectory( + t("sftp.context.download"), + undefined, + getSftpDownloadDialogDirectoryOptions(), + ); if (!selectedDirectory) return; if (parents.every((parent) => parent === parents[0]) && files.every((file) => file.type !== "symlink")) { diff --git a/components/sftp/hooks/useSftpViewFileOps.types.ts b/components/sftp/hooks/useSftpViewFileOps.types.ts index 5b885ec55..cb5459890 100644 --- a/components/sftp/hooks/useSftpViewFileOps.types.ts +++ b/components/sftp/hooks/useSftpViewFileOps.types.ts @@ -19,8 +19,16 @@ export interface UseSftpViewFileOpsParams { systemApp?: SystemAppInfo, ) => void; t: (key: string, vars?: Record) => string; - showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise; - selectDirectory?: (title?: string, defaultPath?: string) => Promise; + showSaveDialog?: ( + defaultPath: string, + filters?: Array<{ name: string; extensions: string[] }>, + directoryOptions?: NetcattyDialogDirectoryOptions, + ) => Promise; + selectDirectory?: ( + title?: string, + defaultPath?: string, + directoryOptions?: NetcattyDialogDirectoryOptions, + ) => Promise; getSftpIdForConnection?: (connectionId: string) => string | undefined; /** Application-layer fresh stat for download source snapshots (kept off the raw bridge). */ statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise; diff --git a/components/sftp/hooks/useSftpViewPaneCallbacks.ts b/components/sftp/hooks/useSftpViewPaneCallbacks.ts index 2d893aee6..bd4090a2c 100644 --- a/components/sftp/hooks/useSftpViewPaneCallbacks.ts +++ b/components/sftp/hooks/useSftpViewPaneCallbacks.ts @@ -25,8 +25,16 @@ interface UseSftpViewPaneCallbacksParams { ) => void; t: (key: string, vars?: Record) => string; listSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise; - showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise; - selectDirectory?: (title?: string, defaultPath?: string) => Promise; + showSaveDialog?: ( + defaultPath: string, + filters?: Array<{ name: string; extensions: string[] }>, + directoryOptions?: NetcattyDialogDirectoryOptions, + ) => Promise; + selectDirectory?: ( + title?: string, + defaultPath?: string, + directoryOptions?: NetcattyDialogDirectoryOptions, + ) => Promise; getSftpIdForConnection?: (connectionId: string) => string | undefined; statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise; listLocalFiles: (path: string) => Promise; diff --git a/components/sftp/useSftpViewFileOps.download.test.ts b/components/sftp/useSftpViewFileOps.download.test.ts index 677f66cc4..8b48d8a5b 100644 --- a/components/sftp/useSftpViewFileOps.download.test.ts +++ b/components/sftp/useSftpViewFileOps.download.test.ts @@ -212,3 +212,88 @@ test("duplicate-name downloads keep captured paths and stop when the source conn globals.IS_REACT_ACT_ENVIRONMENT = previousAct; } }); + +test("download dialogs open in the configured default download folder", async () => { + const globals = globalThis as typeof globalThis & { + IS_REACT_ACT_ENVIRONMENT?: boolean; + localStorage?: Storage; + }; + const previousAct = globals.IS_REACT_ACT_ENVIRONMENT; + const hadLocalStorage = Object.prototype.hasOwnProperty.call(globals, "localStorage"); + const previousLocalStorage = globals.localStorage; + globals.IS_REACT_ACT_ENVIRONMENT = true; + const store = new Map(); + Object.defineProperty(globals, "localStorage", { + configurable: true, + writable: true, + value: { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => { store.set(key, String(value)); }, + removeItem: (key: string) => { store.delete(key); }, + clear: () => store.clear(), + key: () => null, + get length() { return store.size; }, + } as Storage, + }); + + const types = new Map([ + ["/remote/a.txt", { name: "a.txt", size: 1, sizeKnown: true, type: "file", lastModified: 0 }], + ["/remote/b.txt", { name: "b.txt", size: 1, sizeKnown: true, type: "file", lastModified: 0 }], + ["/remote/dir", { name: "dir", size: 0, sizeKnown: true, type: "directory", lastModified: 0 }], + ]); + const saveOptions: unknown[] = []; + const directoryOptions: unknown[] = []; + const connection = { id: "conn-1", hostId: "host-1", hostLabel: "Host", currentPath: "/remote", isLocal: false }; + const pane = { connection, filenameEncoding: "auto" }; + const sftpRef = { current: { + leftPane: pane, rightPane: pane, + joinPath: (parent: string, name: string) => `${parent}/${name}`, + tryPackedDownload: async () => "regular", + downloadToLocal: async () => "completed", + } as unknown as SftpStateApi }; + let ops: ReturnType | undefined; + let renderer: ReactTestRenderer | undefined; + function Probe() { + ops = useSftpViewFileOps({ + sftpRef, + behaviorRef: { current: "" }, + autoSyncRef: { current: false }, + getOpenerForFileRef: { current: () => null }, + setOpenerForExtension: () => undefined, + t: (key) => key, + showSaveDialog: async (name, _filters, options) => { saveOptions.push(options); return `/picked/${name}`; }, + selectDirectory: async (_title, _defaultPath, options) => { directoryOptions.push(options); return "/picked"; }, + getSftpIdForConnection: () => "sftp-1", + statSftp: async (_id, path) => types.get(path) ?? null as unknown as SftpStatResult, + listSftp: async () => [], + }); + return null; + } + + try { + await act(async () => { renderer = create(React.createElement(Probe)); }); + const single = ops!.onDownloadFileLeft as unknown as (entry: SftpFileEntry) => Promise; + const batch = ops!.onDownloadFilesLeft as unknown as (entries: SftpFileEntry[]) => Promise; + + await act(async () => { await single(file("a.txt", 1)); }); + assert.deepEqual(saveOptions.at(-1), { fallbackDirectory: "downloads" }, + "unset preference falls back to the system Downloads folder"); + + store.set("netcatty_sftp_default_download_dir_v1", "/home/me/server-files"); + const configured = { preferredDirectory: "/home/me/server-files", fallbackDirectory: "downloads" }; + await act(async () => { await single(file("a.txt", 1)); }); + assert.deepEqual(saveOptions.at(-1), configured, "Save As opens in the configured folder"); + await act(async () => { await single(file("dir", 0, "directory")); }); + assert.deepEqual(directoryOptions.at(-1), configured, "folder downloads use the configured folder"); + await act(async () => { await batch([file("a.txt", 1), file("b.txt", 1)]); }); + assert.deepEqual(directoryOptions.at(-1), configured, "multi-select downloads use the configured folder"); + } finally { + await act(async () => { renderer?.unmount(); }); + globals.IS_REACT_ACT_ENVIRONMENT = previousAct; + if (hadLocalStorage) { + Object.defineProperty(globals, "localStorage", { configurable: true, writable: true, value: previousLocalStorage }); + } else { + delete (globals as { localStorage?: Storage }).localStorage; + } + } +}); diff --git a/domain/settingsSearch.test.ts b/domain/settingsSearch.test.ts index 75df63adb..9b99d93a0 100644 --- a/domain/settingsSearch.test.ts +++ b/domain/settingsSearch.test.ts @@ -324,3 +324,18 @@ test("resolveSettingsPlatform maps Electron-style platform strings", () => { assert.equal(resolveSettingsPlatform("Linux x86_64"), "linux"); assert.equal(resolveSettingsPlatform(""), "linux"); }); + +test("settings search finds the SFTP default download folder from the real locales", () => { + const tZhReal = (key: string) => zhCN[key] ?? key; + const tEnReal = (key: string) => en[key] ?? key; + for (const [t, queries] of [ + [tZhReal, ["默认下载文件夹", "下载位置", "下载目录"]], + [tEnReal, ["default download folder", "download location", "Downloads folder"]], + ] as const) { + for (const query of queries) { + const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === "sftp-default-download-directory"); + assert.ok(hit, `${query} should find sftp-default-download-directory`); + assert.equal(hit.entry.tab, "file-associations"); + } + } +}); diff --git a/domain/settingsSearchCatalog.ts b/domain/settingsSearchCatalog.ts index 8a71525b9..9b12a1134 100644 --- a/domain/settingsSearchCatalog.ts +++ b/domain/settingsSearchCatalog.ts @@ -1011,6 +1011,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [ descriptionKey: "settings.sftp.compressedUpload.enableDesc", sectionKey: "settings.sftp.compressedUpload", }, + { + id: "sftp-default-download-directory", + tab: "file-associations", + labelKey: "settings.sftp.downloadLocation.directory", + descriptionKey: "settings.sftp.downloadLocation.directoryDesc", + sectionKey: "settings.sftp.downloadLocation", + keywords: ["download folder", "download path", "save location", "下载目录", "保存位置", "下載目錄", "儲存位置"], + }, { id: "sftp-packed-download", tab: "file-associations", diff --git a/domain/sftpDownloadLocation.test.ts b/domain/sftpDownloadLocation.test.ts new file mode 100644 index 000000000..dc7509e49 --- /dev/null +++ b/domain/sftpDownloadLocation.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + buildSftpDownloadDialogDirectoryOptions, + normalizeSftpDefaultDownloadDirectory, +} from "./sftpDownloadLocation"; + +test("normalizeSftpDefaultDownloadDirectory trims strings and rejects other values", () => { + assert.equal(normalizeSftpDefaultDownloadDirectory(" /Users/me/Downloads "), "/Users/me/Downloads"); + assert.equal(normalizeSftpDefaultDownloadDirectory(" "), ""); + assert.equal(normalizeSftpDefaultDownloadDirectory(null), ""); + assert.equal(normalizeSftpDefaultDownloadDirectory(undefined), ""); + assert.equal(normalizeSftpDefaultDownloadDirectory(42), ""); +}); + +test("buildSftpDownloadDialogDirectoryOptions always falls back to system Downloads", () => { + assert.deepEqual(buildSftpDownloadDialogDirectoryOptions(null), { fallbackDirectory: "downloads" }); + assert.deepEqual(buildSftpDownloadDialogDirectoryOptions(""), { fallbackDirectory: "downloads" }); + assert.deepEqual(buildSftpDownloadDialogDirectoryOptions("D:\\Downloads\\servers "), { + preferredDirectory: "D:\\Downloads\\servers", + fallbackDirectory: "downloads", + }); +}); diff --git a/domain/sftpDownloadLocation.ts b/domain/sftpDownloadLocation.ts new file mode 100644 index 000000000..49f80f468 --- /dev/null +++ b/domain/sftpDownloadLocation.ts @@ -0,0 +1,29 @@ +/** + * Pure rules for where SFTP download dialogs open (#4353). + * + * The user may pick a default local download folder in SFTP settings. When it + * is unset (or no longer exists on disk, which the main process verifies), the + * dialog falls back to the system Downloads folder instead of letting the OS + * choose -- on Windows that could be the application install directory. + */ + +export type SftpDownloadDialogDirectoryOptions = { + preferredDirectory?: string; + fallbackDirectory: "downloads"; +}; + +/** Trim a stored directory value; blank / non-string values mean "unset". */ +export const normalizeSftpDefaultDownloadDirectory = (value: unknown): string => { + if (typeof value !== "string") return ""; + return value.trim(); +}; + +/** Build the dialog directory hints from the stored setting. */ +export const buildSftpDownloadDialogDirectoryOptions = ( + storedDirectory: unknown, +): SftpDownloadDialogDirectoryOptions => { + const preferredDirectory = normalizeSftpDefaultDownloadDirectory(storedDirectory); + return preferredDirectory + ? { preferredDirectory, fallbackDirectory: "downloads" } + : { fallbackDirectory: "downloads" }; +}; diff --git a/electron/main/dialogDefaultPath.cjs b/electron/main/dialogDefaultPath.cjs new file mode 100644 index 000000000..77a8a0dd8 --- /dev/null +++ b/electron/main/dialogDefaultPath.cjs @@ -0,0 +1,104 @@ +"use strict"; + +/** + * Resolve the `defaultPath` handed to native open/save dialogs. + * + * Callers that do not pass any directory options keep their legacy behavior + * (the raw `defaultPath` is forwarded untouched). Callers that opt in can ask + * for a preferred local directory (for example the user's configured SFTP + * download folder) with a well-known fallback such as the system Downloads + * folder. Without a directory the OS picks where the dialog opens, which on + * Windows can be the application install directory (#4353). + */ + +const FALLBACK_DIRECTORY_NAMES = new Set(["downloads"]); + +function isExistingDirectory(fs, candidate) { + try { + return fs.statSync(candidate).isDirectory(); + } catch { + return false; + } +} + +function normalizeDirectoryOptions(options) { + if (!options || typeof options !== "object") return null; + const preferredDirectory = typeof options.preferredDirectory === "string" + ? options.preferredDirectory.trim() + : ""; + const fallbackDirectory = typeof options.fallbackDirectory === "string" + && FALLBACK_DIRECTORY_NAMES.has(options.fallbackDirectory) + ? options.fallbackDirectory + : null; + if (!preferredDirectory && !fallbackDirectory) return null; + return { preferredDirectory, fallbackDirectory }; +} + +function resolveFallbackDirectory(app, name) { + if (!name || !app || typeof app.getPath !== "function") return null; + try { + const resolved = app.getPath(name); + return typeof resolved === "string" && resolved ? resolved : null; + } catch { + return null; + } +} + +/** + * Pick the directory a dialog should open in. + * @returns {string | null} An existing absolute directory, or null. + */ +function resolveDialogDirectory(options, { app, fs, path }) { + const normalized = normalizeDirectoryOptions(options); + if (!normalized) return null; + const { preferredDirectory, fallbackDirectory } = normalized; + if ( + preferredDirectory + && path.isAbsolute(preferredDirectory) + && isExistingDirectory(fs, preferredDirectory) + ) { + return preferredDirectory; + } + const fallback = resolveFallbackDirectory(app, fallbackDirectory); + if (fallback && path.isAbsolute(fallback) && isExistingDirectory(fs, fallback)) { + return fallback; + } + return null; +} + +function isBareFileName(path, value) { + return typeof value === "string" + && value.length > 0 + && value !== "." + && value !== ".." + && path.basename(value) === value; +} + +/** + * Resolve the `defaultPath` for `dialog.showSaveDialog`. + * A bare file name is placed inside the resolved directory; an explicit path + * (or a call without directory options) is returned unchanged. + */ +function resolveSaveDialogDefaultPath(defaultPath, options, deps) { + const legacy = typeof defaultPath === "string" ? defaultPath : undefined; + const directory = resolveDialogDirectory(options, deps); + if (!directory) return legacy; + if (legacy === undefined || legacy === "") return directory; + if (!isBareFileName(deps.path, legacy)) return legacy; + return deps.path.join(directory, legacy); +} + +/** + * Resolve the `defaultPath` for directory pickers. An explicit `defaultPath` + * always wins; otherwise the resolved directory (if any) is used. + */ +function resolveDirectoryDialogDefaultPath(defaultPath, options, deps) { + if (typeof defaultPath === "string" && defaultPath) return defaultPath; + return resolveDialogDirectory(options, deps) ?? undefined; +} + +module.exports = { + resolveDialogDirectory, + resolveSaveDialogDefaultPath, + resolveDirectoryDialogDefaultPath, +}; diff --git a/electron/main/dialogDefaultPath.test.cjs b/electron/main/dialogDefaultPath.test.cjs new file mode 100644 index 000000000..805ef999e --- /dev/null +++ b/electron/main/dialogDefaultPath.test.cjs @@ -0,0 +1,90 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const test = require("node:test"); + +const { + resolveDialogDirectory, + resolveSaveDialogDefaultPath, + resolveDirectoryDialogDefaultPath, +} = require("./dialogDefaultPath.cjs"); + +function withDirs(fn) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-dialog-default-")); + const preferred = path.join(root, "preferred"); + const downloads = path.join(root, "downloads"); + fs.mkdirSync(preferred); + fs.mkdirSync(downloads); + const app = { getPath: (name) => (name === "downloads" ? downloads : path.join(root, "unused")) }; + try { + return fn({ root, preferred, downloads, deps: { app, fs, path } }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +} + +test("callers without directory options keep the legacy defaultPath", () => { + withDirs(({ deps }) => { + assert.equal(resolveSaveDialogDefaultPath("report.txt", undefined, deps), "report.txt"); + assert.equal(resolveSaveDialogDefaultPath("report.txt", {}, deps), "report.txt"); + assert.equal(resolveSaveDialogDefaultPath(undefined, null, deps), undefined); + assert.equal(resolveDirectoryDialogDefaultPath(undefined, undefined, deps), undefined); + assert.equal(resolveDirectoryDialogDefaultPath("/explicit", undefined, deps), "/explicit"); + }); +}); + +test("preferred directory is used when it exists", () => { + withDirs(({ preferred, deps }) => { + const options = { preferredDirectory: preferred, fallbackDirectory: "downloads" }; + assert.equal(resolveDialogDirectory(options, deps), preferred); + assert.equal(resolveSaveDialogDefaultPath("report.txt", options, deps), path.join(preferred, "report.txt")); + assert.equal(resolveDirectoryDialogDefaultPath(undefined, options, deps), preferred); + }); +}); + +test("missing, relative or file preferred directories fall back to system Downloads", () => { + withDirs(({ root, downloads, deps }) => { + const file = path.join(root, "not-a-dir.txt"); + fs.writeFileSync(file, "x"); + for (const preferredDirectory of [path.join(root, "gone"), "relative/dir", file, "", " ", 7]) { + const options = { preferredDirectory, fallbackDirectory: "downloads" }; + assert.equal(resolveDialogDirectory(options, deps), downloads, String(preferredDirectory)); + assert.equal( + resolveSaveDialogDefaultPath("a.bin", options, deps), + path.join(downloads, "a.bin"), + ); + } + }); +}); + +test("unknown fallback names are ignored and missing fallbacks keep the legacy path", () => { + withDirs(({ root, deps }) => { + assert.equal(resolveDialogDirectory({ fallbackDirectory: "home" }, deps), null); + assert.equal(resolveSaveDialogDefaultPath("a.bin", { fallbackDirectory: "home" }, deps), "a.bin"); + + const brokenApp = { getPath: () => { throw new Error("unavailable"); } }; + const brokenDeps = { ...deps, app: brokenApp }; + assert.equal(resolveSaveDialogDefaultPath("a.bin", { fallbackDirectory: "downloads" }, brokenDeps), "a.bin"); + + const missingApp = { getPath: () => path.join(root, "missing-downloads") }; + assert.equal( + resolveDirectoryDialogDefaultPath(undefined, { fallbackDirectory: "downloads" }, { ...deps, app: missingApp }), + undefined, + ); + }); +}); + +test("explicit paths are never rewritten and empty names open the directory", () => { + withDirs(({ preferred, deps }) => { + const options = { preferredDirectory: preferred, fallbackDirectory: "downloads" }; + const explicit = path.join(os.tmpdir(), "elsewhere", "file.txt"); + assert.equal(resolveSaveDialogDefaultPath(explicit, options, deps), explicit); + assert.equal(resolveSaveDialogDefaultPath("nested/file.txt", options, deps), "nested/file.txt"); + assert.equal(resolveSaveDialogDefaultPath("", options, deps), preferred); + assert.equal(resolveSaveDialogDefaultPath("..", options, deps), ".."); + assert.equal(resolveDirectoryDialogDefaultPath("/explicit", options, deps), "/explicit"); + }); +}); diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index e6d96f090..7bad201fb 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -9,6 +9,10 @@ const { registerExternalMcpApprovalAlertHandlers, } = require("../bridges/windowAttention.cjs"); const { handleZmodemDragDropUpload } = require("../bridges/zmodemDragDropHandler.cjs"); +const { + resolveSaveDialogDefaultPath, + resolveDirectoryDialogDefaultPath, +} = require("./dialogDefaultPath.cjs"); const excludedFigSpecPrefixes = ["aws", "gcloud", "az"]; @@ -1222,11 +1226,11 @@ function createBridgeRegistrar(context) { }); // Show save file dialog and return selected path - ipcMain.handle("netcatty:showSaveDialog", async (_event, { defaultPath, filters }) => { + ipcMain.handle("netcatty:showSaveDialog", async (_event, { defaultPath, filters, directoryOptions }) => { const { dialog } = electronModule; const result = await dialog.showSaveDialog({ - defaultPath, + defaultPath: resolveSaveDialogDefaultPath(defaultPath, directoryOptions, { app, fs, path }), filters: filters || [{ name: "All Files", extensions: ["*"] }], }); @@ -1256,12 +1260,12 @@ function createBridgeRegistrar(context) { }); // Select a directory and return the selected path - ipcMain.handle("netcatty:selectDirectory", async (_event, { title, defaultPath }) => { + ipcMain.handle("netcatty:selectDirectory", async (_event, { title, defaultPath, directoryOptions }) => { const { dialog } = electronModule; const result = await dialog.showOpenDialog({ title: title || "Select Directory", - defaultPath, + defaultPath: resolveDirectoryDialogDefaultPath(defaultPath, directoryOptions, { app, fs, path }), properties: ["openDirectory", "createDirectory"], }); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index d16deaf5b..fba8468bf 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -1731,10 +1731,10 @@ function createPreloadApi(ctx) { }), // Save dialog for file downloads - showSaveDialog: (defaultPath, filters) => - ipcRenderer.invoke("netcatty:showSaveDialog", { defaultPath, filters }), - selectDirectory: (title, defaultPath) => - ipcRenderer.invoke("netcatty:selectDirectory", { title, defaultPath }), + showSaveDialog: (defaultPath, filters, directoryOptions) => + ipcRenderer.invoke("netcatty:showSaveDialog", { defaultPath, filters, directoryOptions }), + selectDirectory: (title, defaultPath, directoryOptions) => + ipcRenderer.invoke("netcatty:selectDirectory", { title, defaultPath, directoryOptions }), selectFile: (title, defaultPath, filters) => ipcRenderer.invoke("netcatty:selectFile", { title, defaultPath, filters }), diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index b82b8a582..0fe922060 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -139,6 +139,12 @@ export const STORAGE_KEY_SFTP_AUTO_SYNC = 'netcatty_sftp_auto_sync_v1'; export const STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES = 'netcatty_sftp_show_hidden_files_v1'; export const STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD = 'netcatty_sftp_use_compressed_upload_v1'; export const STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD = 'netcatty_sftp_use_packed_download_v1'; +/** + * Default local folder for SFTP download dialogs. Device-local on purpose: + * absolute paths differ between machines, so this key is never cloud-synced. + * Empty / missing means "system Downloads folder". + */ +export const STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR = 'netcatty_sftp_default_download_dir_v1'; export const STORAGE_KEY_SFTP_TRANSFER_CENTER = 'netcatty_sftp_transfer_center_v1'; export const STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR = 'netcatty_sftp_auto_open_sidebar_v1'; export const STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD = 'netcatty_sftp_follow_terminal_cwd_v1'; diff --git a/types/global/netcatty-bridge-files.d.ts b/types/global/netcatty-bridge-files.d.ts index 9ee4d1d71..6ea15fc2a 100644 --- a/types/global/netcatty-bridge-files.d.ts +++ b/types/global/netcatty-bridge-files.d.ts @@ -1,6 +1,16 @@ import type { SftpFilenameEncoding } from "../../types"; declare global { + /** + * Opt-in directory hints for native open/save dialogs. The main process + * opens `preferredDirectory` when it is an existing absolute directory and + * otherwise falls back to the named system folder. + */ + interface NetcattyDialogDirectoryOptions { + preferredDirectory?: string; + fallbackDirectory?: "downloads"; + } + interface NetcattyBridge { // File opener helpers (for "Open With" feature) selectApplication?(): Promise<{ path: string; name: string } | null>; @@ -15,8 +25,12 @@ declare global { ): Promise<{ localPath: string; cancelled: boolean }>; // Save dialog for file downloads - showSaveDialog?(defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>): Promise; - selectDirectory?(title?: string, defaultPath?: string): Promise; + showSaveDialog?( + defaultPath: string, + filters?: Array<{ name: string; extensions: string[] }>, + directoryOptions?: NetcattyDialogDirectoryOptions, + ): Promise; + selectDirectory?(title?: string, defaultPath?: string, directoryOptions?: NetcattyDialogDirectoryOptions): Promise; selectFile?(title?: string, defaultPath?: string, filters?: Array<{ name: string; extensions: string[] }>): Promise; // File watcher for auto-sync feature