Compare commits

...
Author SHA1 Message Date
陈大猫 b7ca3f4bd5 feat(sftp): add default download folder setting (#4353) 2026-11-25 22:16:48 +08:00
23 changed files with 592 additions and 24 deletions

No files matched your search

+7
View File
@@ -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.',
+7
View File
@@ -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.',
+7
View File
@@ -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). Отключается при замене папки во временный путь.',
@@ -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)。替换到暂存路径时自动禁用。',
@@ -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)。替換到暫存路徑時自動停用。',
@@ -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);
};
+9 -4
View File
@@ -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 {
+11
View File
@@ -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");
});
@@ -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<string>(STORAGE_KEY_SFTP_USE_PACKED_DOWNLOAD, "true");
const [storedDownloadDir, setStoredDownloadDir] = useStoredString<string>(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() {
</SettingRow>
</SettingCard>
<SectionHeader title={t('settings.sftp.downloadLocation')} />
<SettingCard className="py-3">
<SettingsAnchor anchorId="sftp-default-download-directory" className="space-y-2">
<div>
<div className="text-sm font-medium">{t('settings.sftp.downloadLocation.directory')}</div>
<div className="text-xs text-muted-foreground mt-0.5">
{t('settings.sftp.downloadLocation.directoryDesc')}
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex-1 min-w-0">
{defaultDownloadDir ? (
<Tooltip>
<TooltipTrigger asChild>
<div className="bg-background border border-input rounded-md px-3 py-2 text-sm font-mono truncate">
{defaultDownloadDir}
</div>
</TooltipTrigger>
<TooltipContent>{defaultDownloadDir}</TooltipContent>
</Tooltip>
) : (
<div className="bg-background border border-input rounded-md px-3 py-2 text-sm text-muted-foreground truncate">
{t('settings.sftp.downloadLocation.systemDefault')}
</div>
)}
</div>
<Button
variant="outline"
size="sm"
onClick={() => void handleSelectDownloadDir()}
disabled={isSelectingDownloadDir}
className="shrink-0"
>
{t('settings.sftp.downloadLocation.browse')}
</Button>
{defaultDownloadDir && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() => setStoredDownloadDir("")}
aria-label={t('settings.sftp.downloadLocation.reset')}
className="shrink-0"
>
<RotateCcw size={16} />
</Button>
</TooltipTrigger>
<TooltipContent>{t('settings.sftp.downloadLocation.reset')}</TooltipContent>
</Tooltip>
)}
</div>
</SettingsAnchor>
</SettingCard>
<SectionHeader title={t('settings.sftp.packedDownload')} />
<SettingCard>
<SettingRow
+21 -4
View File
@@ -12,6 +12,7 @@ import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"
import { getFileExtension, getLanguageId, FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
import { isNavigableDirectory } from "../utils";
import { resolveDownloadSourceSnapshot } from "../../../application/state/sftp/downloadSourceSnapshot";
import { getSftpDownloadDialogDirectoryOptions } from "../../../application/state/sftp/downloadLocation";
import { reportSftpUploadResults } from "../reportSftpUploadResults";
import { editorTabStore } from "../../../application/state/editorTabStore";
import { popOutEditorTab } from "../../../application/state/editorWindowClient";
@@ -462,7 +463,11 @@ export const useSftpViewFileOps = ({
const status = await sftpRef.current.tryPackedDownload?.({ ...request, localDirectory }) ?? "regular";
if (status === "conflict") {
if (!window.confirm(t("sftp.packedDownload.conflict"))) return null;
const destination = await selectDirectory?.(t("sftp.context.download"));
const destination = await selectDirectory?.(
t("sftp.context.download"),
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!destination) return null;
localDirectory = destination;
continue;
@@ -536,7 +541,11 @@ export const useSftpViewFileOps = ({
return;
}
const selectedDirectory = await selectDirectory(t("sftp.context.download"));
const selectedDirectory = await selectDirectory(
t("sftp.context.download"),
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!selectedDirectory) return;
// The picker may stay open while the remote entry changes again.
@@ -586,7 +595,11 @@ export const useSftpViewFileOps = ({
return;
}
const targetPath = await showSaveDialog(file.name);
const targetPath = await showSaveDialog(
file.name,
undefined,
getSftpDownloadDialogDirectoryOptions(),
);
if (!targetPath) return;
const selectedSnapshot = await resolveDownloadSourceSnapshot(
@@ -774,7 +787,11 @@ export const useSftpViewFileOps = ({
return;
}
const parents = paths.map((path) => 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")) {
@@ -19,8 +19,16 @@ export interface UseSftpViewFileOpsParams {
systemApp?: SystemAppInfo,
) => void;
t: (key: string, vars?: Record<string, string | number>) => string;
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
showSaveDialog?: (
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
selectDirectory?: (
title?: string,
defaultPath?: string,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
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<SftpStatResult>;
@@ -25,8 +25,16 @@ interface UseSftpViewPaneCallbacksParams {
) => void;
t: (key: string, vars?: Record<string, string | number>) => string;
listSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<RemoteFile[]>;
showSaveDialog?: (defaultPath: string, filters?: Array<{ name: string; extensions: string[] }>) => Promise<string | null>;
selectDirectory?: (title?: string, defaultPath?: string) => Promise<string | null>;
showSaveDialog?: (
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
selectDirectory?: (
title?: string,
defaultPath?: string,
directoryOptions?: NetcattyDialogDirectoryOptions,
) => Promise<string | null>;
getSftpIdForConnection?: (connectionId: string) => string | undefined;
statSftp?: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise<SftpStatResult>;
listLocalFiles: (path: string) => Promise<RemoteFile[]>;
@@ -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<string, string>();
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<string, SftpStatResult>([
["/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<typeof useSftpViewFileOps> | 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<void>;
const batch = ops!.onDownloadFilesLeft as unknown as (entries: SftpFileEntry[]) => Promise<void>;
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;
}
}
});
+15
View File
@@ -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");
}
}
});
+8
View File
@@ -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",
+24
View File
@@ -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",
});
});
+29
View File
@@ -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" };
};
+104
View File
@@ -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,
};
+90
View File
@@ -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");
});
});
+8 -4
View File
@@ -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"],
});
+4 -4
View File
@@ -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 }),
+6
View File
@@ -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';
+16 -2
View File
@@ -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<string | null>;
selectDirectory?(title?: string, defaultPath?: string): Promise<string | null>;
showSaveDialog?(
defaultPath: string,
filters?: Array<{ name: string; extensions: string[] }>,
directoryOptions?: NetcattyDialogDirectoryOptions,
): Promise<string | null>;
selectDirectory?(title?: string, defaultPath?: string, directoryOptions?: NetcattyDialogDirectoryOptions): Promise<string | null>;
selectFile?(title?: string, defaultPath?: string, filters?: Array<{ name: string; extensions: string[] }>): Promise<string | null>;
// File watcher for auto-sync feature