diff --git a/application/i18n/locales/en/vault.ts b/application/i18n/locales/en/vault.ts index 2463eaa83..acde6f52a 100644 --- a/application/i18n/locales/en/vault.ts +++ b/application/i18n/locales/en/vault.ts @@ -560,6 +560,11 @@ export const enVaultMessages: Messages = { 'settings.sftp.compressedUpload.enable': 'Enable folder compression', 'settings.sftp.compressedUpload.enableDesc': 'Automatically compress folders using tar before transfer. Requires tar support on the server. Falls back to regular transfer if not available.', + 'settings.sftp.folderPrescan.enable': 'Pre-scan folders before transfer', + 'settings.sftp.folderPrescan.enableDesc': 'Walk the full folder tree first so the transfer center shows a stable file total before bytes move. Slightly delays the first transfer on very large trees.', + '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.', + // Quick Switcher 'qs.search.placeholder': 'Search hosts or tabs', 'qs.jumpTo': 'Jump To', diff --git a/application/i18n/locales/ru/vault.ts b/application/i18n/locales/ru/vault.ts index 5e0a95527..0c610b268 100644 --- a/application/i18n/locales/ru/vault.ts +++ b/application/i18n/locales/ru/vault.ts @@ -597,6 +597,11 @@ export const ruVaultMessages: Messages = { 'settings.sftp.compressedUpload.enable': 'Включить сжатие папок', 'settings.sftp.compressedUpload.enableDesc': 'Автоматически сжимать папки с помощью tar перед передачей. Требует поддержки tar на сервере. Если она недоступна, будет использована обычная передача.', + 'settings.sftp.folderPrescan.enable': 'Предварительное сканирование папок', + 'settings.sftp.folderPrescan.enableDesc': 'Сначала обойти всё дерево папок, чтобы центр передачи показал стабильное число файлов до начала передачи байтов. На очень больших деревьях немного откладывает первую передачу.', + 'settings.sftp.skipUnchanged.enable': 'Пропускать неизменённые файлы', + 'settings.sftp.skipUnchanged.enableDesc': 'Пропускать файлы, у которых размер и время изменения уже совпадают с назначением (в стиле rsync). Отключается при замене папки во временный путь.', + // Quick Switcher 'qs.search.placeholder': 'Поиск хостов или вкладок', 'qs.jumpTo': 'Перейти к', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index b868580a3..23f5ab71a 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -206,6 +206,11 @@ export const zhCNTerminalMessages: Messages = { 'settings.sftp.compressedUpload.enable': '启用文件夹压缩', 'settings.sftp.compressedUpload.enableDesc': '自动使用 tar 压缩文件夹后再传输。需要服务器支持 tar 命令,不支持时自动回退到普通传输。', + 'settings.sftp.folderPrescan.enable': '传输前预扫描文件夹', + 'settings.sftp.folderPrescan.enableDesc': '先完整遍历文件夹树,传输中心在开始传字节前就能显示稳定的文件总数。超大目录会略微推迟首个文件开传。', + 'settings.sftp.skipUnchanged.enable': '跳过未改文件', + 'settings.sftp.skipUnchanged.enableDesc': '当目标文件的大小与修改时间已与源一致时跳过传输(类似 rsync)。替换到暂存路径时自动禁用。', + // Settings > Terminal 'settings.terminal.section.theme': '终端主题', 'settings.terminal.themeModal.title': '选择主题', diff --git a/application/i18n/locales/zh-TW/terminal.ts b/application/i18n/locales/zh-TW/terminal.ts index cf894c604..e52cf5117 100644 --- a/application/i18n/locales/zh-TW/terminal.ts +++ b/application/i18n/locales/zh-TW/terminal.ts @@ -206,6 +206,11 @@ export const zhTWTerminalMessages: Messages = { 'settings.sftp.compressedUpload.enable': '啟用資料夾壓縮', 'settings.sftp.compressedUpload.enableDesc': '自動使用 tar 壓縮資料夾後再傳輸。需要伺服器支援 tar 指令,不支援時自動回退到普通傳輸。', + 'settings.sftp.folderPrescan.enable': '傳輸前預掃描資料夾', + 'settings.sftp.folderPrescan.enableDesc': '先完整遍歷資料夾樹,傳輸中心在開始傳位元組前就能顯示穩定的檔案總數。超大目錄會略微推遲首個檔案開傳。', + 'settings.sftp.skipUnchanged.enable': '跳過未改檔案', + 'settings.sftp.skipUnchanged.enableDesc': '當目標檔案的大小與修改時間已與來源一致時跳過傳輸(類似 rsync)。替換到暫存路徑時自動停用。', + // Settings > Terminal 'settings.terminal.section.theme': '終端主題', 'settings.terminal.themeModal.title': '選擇主題', diff --git a/application/state/settingsStorageSync.ts b/application/state/settingsStorageSync.ts index ed3ff3a2a..fbee2e98d 100644 --- a/application/state/settingsStorageSync.ts +++ b/application/state/settingsStorageSync.ts @@ -28,6 +28,8 @@ import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY, STORAGE_KEY_SSH_TRANSPORT_IDLE_TTL_MS, STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD, + STORAGE_KEY_SFTP_FOLDER_PRESCAN, + STORAGE_KEY_SFTP_SKIP_UNCHANGED, STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT, STORAGE_KEY_SHOW_RECENT_HOSTS, STORAGE_KEY_HOST_CLICK_BEHAVIOR, @@ -79,6 +81,8 @@ interface UseSettingsStorageSyncParams { sftpAutoSync: boolean; sftpShowHiddenFiles: boolean; sftpUseCompressedUpload: boolean; + sftpFolderPrescan: boolean; + sftpSkipUnchanged: boolean; sftpAutoOpenSidebar: boolean; sftpFollowTerminalCwd: boolean; sftpDefaultViewMode: 'list' | 'tree'; @@ -125,6 +129,8 @@ interface UseSettingsStorageSyncParams { setSftpAutoSync: Dispatch>; setSftpShowHiddenFiles: Dispatch>; setSftpUseCompressedUpload: Dispatch>; + setSftpFolderPrescan: Dispatch>; + setSftpSkipUnchanged: Dispatch>; setSftpAutoOpenSidebar: Dispatch>; setSftpFollowTerminalCwd: Dispatch>; setSftpDefaultViewMode: Dispatch>; @@ -165,7 +171,7 @@ export function useSettingsStorageSync({ customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, - sftpUseCompressedUpload, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, + sftpUseCompressedUpload, sftpFolderPrescan, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled, globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant, @@ -174,7 +180,7 @@ export function useSettingsStorageSync({ setTerminalThemeId, setTerminalThemeDarkId, setTerminalThemeLightId, setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize, setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles, - setSftpUseCompressedUpload, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, + setSftpUseCompressedUpload, setSftpFolderPrescan, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setExplorerContextMenuEnabledState, setGlobalHotkeyEnabled, setWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState, @@ -189,7 +195,7 @@ export function useSettingsStorageSync({ customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, - sftpUseCompressedUpload, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, + sftpUseCompressedUpload, sftpFolderPrescan, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled, globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant, @@ -199,7 +205,7 @@ export function useSettingsStorageSync({ customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, - sftpUseCompressedUpload, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, + sftpUseCompressedUpload, sftpFolderPrescan, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled, globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant, @@ -379,6 +385,18 @@ export function useSettingsStorageSync({ setSftpUseCompressedUpload(newValue); } } + if (e.key === STORAGE_KEY_SFTP_FOLDER_PRESCAN && e.newValue !== null) { + const newValue = e.newValue === 'true'; + if (newValue !== s.sftpFolderPrescan) { + setSftpFolderPrescan(newValue); + } + } + if (e.key === STORAGE_KEY_SFTP_SKIP_UNCHANGED && e.newValue !== null) { + const newValue = e.newValue === 'true'; + if (newValue !== s.sftpSkipUnchanged) { + setSftpSkipUnchanged(newValue); + } + } // Sync SFTP auto-open sidebar setting from other windows if (e.key === STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR && e.newValue !== null) { const newValue = e.newValue === 'true'; @@ -542,6 +560,8 @@ export function useSettingsStorageSync({ setSftpTransferConcurrencyState, setSshTransportIdleTtlMsState, setSftpUseCompressedUpload, + setSftpFolderPrescan, + setSftpSkipUnchanged, setShowOnlyUngroupedHostsInRootState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, diff --git a/application/state/sftp/transferConcurrency.test.ts b/application/state/sftp/transferConcurrency.test.ts index 50c177352..16b995c88 100644 --- a/application/state/sftp/transferConcurrency.test.ts +++ b/application/state/sftp/transferConcurrency.test.ts @@ -4,7 +4,11 @@ import assert from "node:assert/strict"; import { DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY, DEFAULT_SFTP_FILE_TRANSFER_CONCURRENCY, + DEFAULT_SFTP_FOLDER_PRESCAN, + DEFAULT_SFTP_SKIP_UNCHANGED, resolveSftpDirectoryListingConcurrency, + resolveSftpFolderPrescanEnabled, + resolveSftpSkipUnchangedEnabled, resolveSftpTransferConcurrency, runBoundedConcurrency, runSftpTransferWorkers, @@ -23,6 +27,15 @@ test("defaults directory listing fanout to four concurrent readdirs", () => { assert.equal(DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY, 4); }); +test("defaults folder pre-scan and skip-unchanged to enabled", () => { + assert.equal(resolveSftpFolderPrescanEnabled(() => null), DEFAULT_SFTP_FOLDER_PRESCAN); + assert.equal(resolveSftpSkipUnchangedEnabled(() => null), DEFAULT_SFTP_SKIP_UNCHANGED); + assert.equal(DEFAULT_SFTP_FOLDER_PRESCAN, true); + assert.equal(DEFAULT_SFTP_SKIP_UNCHANGED, true); + assert.equal(resolveSftpFolderPrescanEnabled(() => false), false); + assert.equal(resolveSftpSkipUnchangedEnabled(() => false), false); +}); + test("keeps explicit folder transfer concurrency within the supported range", () => { assert.equal(resolveSftpTransferConcurrency(() => 1), 1); assert.equal(resolveSftpTransferConcurrency(() => 16), 16); diff --git a/application/state/sftp/transferConcurrency.ts b/application/state/sftp/transferConcurrency.ts index 9ccfa2123..5c14c3e11 100644 --- a/application/state/sftp/transferConcurrency.ts +++ b/application/state/sftp/transferConcurrency.ts @@ -13,6 +13,11 @@ export const DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY = 4; export const MIN_SFTP_DIRECTORY_LISTING_CONCURRENCY = 1; export const MAX_SFTP_DIRECTORY_LISTING_CONCURRENCY = 8; +/** Default on: accurate folder totals before first byte (rsync --no-i-r style). */ +export const DEFAULT_SFTP_FOLDER_PRESCAN = true; +/** Default on: skip size+mtime matches like rsync's generator. */ +export const DEFAULT_SFTP_SKIP_UNCHANGED = true; + export function resolveSftpTransferConcurrency(readStoredValue: () => number | null | undefined): number { const stored = readStoredValue(); return stored != null && @@ -33,6 +38,20 @@ export function resolveSftpDirectoryListingConcurrency( : DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY; } +export function resolveSftpFolderPrescanEnabled( + readStoredValue: () => boolean | null | undefined, +): boolean { + const stored = readStoredValue(); + return stored == null ? DEFAULT_SFTP_FOLDER_PRESCAN : stored; +} + +export function resolveSftpSkipUnchangedEnabled( + readStoredValue: () => boolean | null | undefined, +): boolean { + const stored = readStoredValue(); + return stored == null ? DEFAULT_SFTP_SKIP_UNCHANGED : stored; +} + export async function runSftpTransferWorkers( items: T[], readStoredConcurrency: () => number | null | undefined, diff --git a/application/state/sftp/transferDirectoryDiscovery.test.ts b/application/state/sftp/transferDirectoryDiscovery.test.ts new file mode 100644 index 000000000..03a26c3a5 --- /dev/null +++ b/application/state/sftp/transferDirectoryDiscovery.test.ts @@ -0,0 +1,125 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import type { SftpFileEntry } from "../../../domain/models"; +import { discoverTransferTree } from "./transferDirectoryDiscovery"; + +const directoryEntry = (name: string): SftpFileEntry => ({ + name, + type: "directory", + size: 0, + sizeFormatted: "0 B", + lastModified: 0, + lastModifiedFormatted: "", +}); + +const fileEntry = (name: string, size = 1, lastModified = 1_700_000_000): SftpFileEntry => ({ + name, + type: "file", + size, + sizeFormatted: `${size} B`, + lastModified, + lastModifiedFormatted: "", +}); + +test("discoverTransferTree returns a stable flat file list with bounded listings", async () => { + const previousWindow = (globalThis as { window?: unknown }).window; + (globalThis as { window?: unknown }).window = { + netcatty: { + realpathSftp: async (_sftpId: string, remotePath: string) => remotePath, + }, + }; + + let active = 0; + let maxActive = 0; + const listRemoteFiles = async (_sftpId: string, path: string): Promise => { + active += 1; + maxActive = Math.max(maxActive, active); + await new Promise((resolve) => setTimeout(resolve, 1)); + active -= 1; + if (path === "/source") { + return [directoryEntry("a"), directoryEntry("b"), fileEntry("root.txt")]; + } + if (path === "/source/a") return [fileEntry("a1.txt"), fileEntry("a2.txt")]; + if (path === "/source/b") return [fileEntry("b1.txt")]; + return []; + }; + + try { + const counts: number[] = []; + const result = await discoverTransferTree({ + sourcePath: "/source", + targetPath: "/target", + sourceIsLocal: false, + sourceSftpId: "sftp-1", + sourceEncoding: "auto", + listLocalFiles: async () => [], + listRemoteFiles, + listingConcurrency: 2, + onDiscoveredFiles: (total) => counts.push(total), + }); + + assert.deepEqual( + result.files.map((file) => file.sourcePath).sort(), + ["/source/a/a1.txt", "/source/a/a2.txt", "/source/b/b1.txt", "/source/root.txt"], + ); + assert.deepEqual( + result.directories.map((dir) => dir.sourcePath).sort(), + ["/source", "/source/a", "/source/b"], + ); + assert.equal(counts.at(-1), 4); + assert.ok(maxActive >= 2, `expected parallel listings, got ${maxActive}`); + assert.ok(maxActive <= 2, `listing concurrency exceeded: ${maxActive}`); + } finally { + (globalThis as { window?: unknown }).window = previousWindow; + } +}); + +test("discoverTransferTree skips symlink directory cycles across BFS waves", async () => { + const previousWindow = (globalThis as { window?: unknown }).window; + const listCalls = new Map(); + (globalThis as { window?: unknown }).window = { + netcatty: { + realpathSftp: async (_sftpId: string, remotePath: string) => ( + remotePath === "/source/loop" ? "/source" : remotePath + ), + }, + }; + + const listRemoteFiles = async (_sftpId: string, path: string): Promise => { + listCalls.set(path, (listCalls.get(path) ?? 0) + 1); + if (path === "/source") { + return [ + directoryEntry("child"), + { ...directoryEntry("loop"), type: "symlink", linkTarget: "directory" }, + fileEntry("root.txt"), + ]; + } + if (path === "/source/child") return [fileEntry("nested.txt")]; + throw new Error(`unexpected list of ${path}`); + }; + + try { + const result = await discoverTransferTree({ + sourcePath: "/source", + targetPath: "/target", + sourceIsLocal: false, + sourceSftpId: "sftp-1", + sourceEncoding: "auto", + followSymlinks: true, + listLocalFiles: async () => [], + listRemoteFiles, + listingConcurrency: 4, + }); + + assert.equal(listCalls.has("/source/loop"), false); + assert.equal(listCalls.get("/source"), 1); + assert.equal(listCalls.get("/source/child"), 1); + assert.deepEqual( + result.files.map((file) => file.sourcePath).sort(), + ["/source/child/nested.txt", "/source/root.txt"], + ); + } finally { + (globalThis as { window?: unknown }).window = previousWindow; + } +}); diff --git a/application/state/sftp/transferDirectoryDiscovery.ts b/application/state/sftp/transferDirectoryDiscovery.ts new file mode 100644 index 000000000..7ebe743e2 --- /dev/null +++ b/application/state/sftp/transferDirectoryDiscovery.ts @@ -0,0 +1,242 @@ +import type { SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models"; +import { + accountSftpDirectoryEntries, + claimSftpDirectoryVisit, + createSftpDirectoryTraversalBudget, + normalizeSftpCanonicalDirectoryPath, + releaseSftpDirectoryVisit, + shouldFollowSftpSymlinkDirectory, + type SftpDirectoryTraversalBudget, +} from "../../../domain/sftpDirectoryCheckpoint"; +import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; +import { logger } from "../../../lib/logger"; +import { + DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY, + resolveSftpDirectoryListingConcurrency, + runBoundedConcurrency, +} from "./transferConcurrency"; +import { joinPath, joinTransferTargetPath } from "./utils"; + +export type DiscoveredTransferFile = { + name: string; + sourcePath: string; + targetPath: string; + size: number; + lastModified: number; +}; + +export type DiscoveredTransferDirectory = { + sourcePath: string; + targetPath: string; +}; + +export type DiscoverTransferTreeResult = { + files: DiscoveredTransferFile[]; + directories: DiscoveredTransferDirectory[]; +}; + +type ListingGate = { + run: (fn: () => Promise) => Promise; +}; + +function createListingGate(concurrency = DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY): ListingGate { + const limit = Math.max(1, Math.floor(concurrency) || 1); + let active = 0; + const waiters: Array<() => void> = []; + const acquire = async () => { + if (active < limit) { + active += 1; + return; + } + await new Promise((resolve) => { + waiters.push(() => { + active += 1; + resolve(); + }); + }); + }; + const release = () => { + active = Math.max(0, active - 1); + const next = waiters.shift(); + if (next) next(); + }; + return { + async run(fn: () => Promise): Promise { + await acquire(); + try { + return await fn(); + } finally { + release(); + } + }, + }; +} + +function getEntrySize(entry: SftpFileEntry): number { + if (typeof entry.size === "string") { + const parsed = parseInt(entry.size, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : 0; + } + return typeof entry.size === "number" && entry.size > 0 ? entry.size : 0; +} + +export type DiscoverTransferTreeOptions = { + sourcePath: string; + targetPath: string; + sourceIsLocal: boolean; + sourceSftpId: string | null; + sourceEncoding: SftpFilenameEncoding; + followSymlinks?: boolean; + listLocalFiles: (path: string) => Promise; + listRemoteFiles: (sftpId: string, path: string, encoding?: SftpFilenameEncoding) => Promise; + shouldAbort?: () => boolean; + onDiscoveredFiles?: (totalFiles: number) => void; + listingConcurrency?: number; + traversalBudget?: SftpDirectoryTraversalBudget; +}; + +/** + * Full-tree discovery (rsync --no-inc-recursive style): walk every directory + * before transfer starts so the UI can show a stable file total. + * Listings are bounded-parallel; nested walks share one semaphore. + */ +export async function discoverTransferTree( + options: DiscoverTransferTreeOptions, +): Promise { + const followSymlinks = options.followSymlinks === true; + const listingConcurrency = options.listingConcurrency + ?? resolveSftpDirectoryListingConcurrency(); + const listingGate = createListingGate(listingConcurrency); + const traversal = options.traversalBudget ?? createSftpDirectoryTraversalBudget(); + // BFS releases each directory after listing, so active-only claims cannot + // catch symlink cycles the way the interleaved DFS stack does. Track every + // canonical path seen for the lifetime of this discovery. + const seenCanonicalDirectories = new Set(); + const files: DiscoveredTransferFile[] = []; + const directories: DiscoveredTransferDirectory[] = [ + { sourcePath: options.sourcePath, targetPath: options.targetPath }, + ]; + + type DirJob = { + sourcePath: string; + targetPath: string; + symlinkDepth: number; + }; + + const queue: DirJob[] = [{ + sourcePath: options.sourcePath, + targetPath: options.targetPath, + symlinkDepth: 0, + }]; + + const publishCount = () => { + options.onDiscoveredFiles?.(files.length); + }; + + const processDir = async (job: DirJob): Promise => { + if (options.shouldAbort?.()) throw new Error("Transfer cancelled"); + let claimedCanonicalPath: string | null = null; + try { + if (!options.sourceIsLocal && options.sourceSftpId) { + const bridge = netcattyBridge.get(); + const canonicalPath = await bridge?.realpathSftp?.( + options.sourceSftpId, + job.sourcePath, + options.sourceEncoding, + ).catch(() => job.sourcePath) ?? job.sourcePath; + const normalized = normalizeSftpCanonicalDirectoryPath(canonicalPath); + if (seenCanonicalDirectories.has(normalized)) return []; + claimedCanonicalPath = claimSftpDirectoryVisit(traversal, canonicalPath); + if (!claimedCanonicalPath) return []; + seenCanonicalDirectories.add(claimedCanonicalPath); + } + + const listed = await listingGate.run(async () => { + if (options.shouldAbort?.()) throw new Error("Transfer cancelled"); + if (options.sourceIsLocal) { + return options.listLocalFiles(job.sourcePath); + } + if (!options.sourceSftpId) throw new Error("No source connection"); + return options.listRemoteFiles( + options.sourceSftpId, + job.sourcePath, + options.sourceEncoding, + ); + }); + + const filtered = listed.filter((entry) => entry.name !== "." && entry.name !== ".."); + if (!options.sourceIsLocal) accountSftpDirectoryEntries(traversal, filtered.length); + + const childDirs: DirJob[] = []; + const regularFiles: SftpFileEntry[] = []; + for (const entry of filtered) { + if (entry.type === "directory") { + childDirs.push({ + sourcePath: joinPath(job.sourcePath, entry.name), + targetPath: joinTransferTargetPath(job.targetPath, entry.name), + symlinkDepth: job.symlinkDepth, + }); + } else if ( + followSymlinks + && entry.type === "symlink" + && entry.linkTarget === "directory" + ) { + if (shouldFollowSftpSymlinkDirectory(job.symlinkDepth)) { + childDirs.push({ + sourcePath: joinPath(job.sourcePath, entry.name), + targetPath: joinTransferTargetPath(job.targetPath, entry.name), + symlinkDepth: job.symlinkDepth + 1, + }); + } else { + logger.warn( + `[SFTP] Skipping symlink directory at max depth during pre-scan: ${joinPath(job.sourcePath, entry.name)}`, + ); + } + } else { + regularFiles.push(entry); + } + } + + childDirs.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)); + regularFiles.sort((left, right) => left.name.localeCompare(right.name)); + + for (const dir of childDirs) { + directories.push({ sourcePath: dir.sourcePath, targetPath: dir.targetPath }); + } + for (const entry of regularFiles) { + files.push({ + name: entry.name, + sourcePath: joinPath(job.sourcePath, entry.name), + targetPath: joinTransferTargetPath(job.targetPath, entry.name), + size: getEntrySize(entry), + lastModified: typeof entry.lastModified === "number" ? entry.lastModified : 0, + }); + } + publishCount(); + return childDirs; + } finally { + if (claimedCanonicalPath) { + releaseSftpDirectoryVisit(traversal, claimedCanonicalPath); + } + } + }; + + // BFS waves: each wave lists up to listingConcurrency directories in parallel. + while (queue.length > 0) { + if (options.shouldAbort?.()) throw new Error("Transfer cancelled"); + const wave = queue.splice(0, queue.length); + const nested: DirJob[][] = new Array(wave.length); + await runBoundedConcurrency( + wave, + listingConcurrency, + async (job, index) => { + nested[index] = await processDir(job); + }, + ); + for (const children of nested) { + for (const child of children) queue.push(child); + } + } + + return { files, directories }; +} diff --git a/application/state/sftp/transferDirectoryFileBatch.ts b/application/state/sftp/transferDirectoryFileBatch.ts new file mode 100644 index 000000000..ad4e97eb5 --- /dev/null +++ b/application/state/sftp/transferDirectoryFileBatch.ts @@ -0,0 +1,323 @@ +import type { Dispatch, MutableRefObject, SetStateAction } from "react"; +import type { + SftpFilenameEncoding, + TransferStatus, + TransferTask, +} from "../../../domain/models"; +import { createDirectoryEntryIdentity } from "../../../domain/sftpDirectoryCheckpoint"; +import { isUnchangedTransferCandidate } from "../../../domain/sftpTransferSkip"; +import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY } from "../../../infrastructure/config/storageKeys"; +import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; +import { logger } from "../../../lib/logger"; +import { isSessionError } from "./errors"; +import type { DiscoveredTransferFile } from "./transferDirectoryDiscovery"; +import { runSftpTransferWorkers } from "./transferConcurrency"; +import { isTransferCancelledError } from "./transferRetry"; + +type TransferOneFile = ( + task: TransferTask, + sourceSftpId: string | null, + targetSftpId: string | null, + sourceIsLocal: boolean, + targetIsLocal: boolean, + sourceEncoding: SftpFilenameEncoding, + targetEncoding: SftpFilenameEncoding, + rootTaskId: string, + sameHost?: boolean, +) => Promise; + +export type TransferDiscoveredFilesParams = { + rootTask: TransferTask; + files: DiscoveredTransferFile[]; + sourceSftpId: string | null; + targetSftpId: string | null; + sourceIsLocal: boolean; + targetIsLocal: boolean; + sourceEncoding: SftpFilenameEncoding; + targetEncoding: SftpFilenameEncoding; + rootTaskId: string; + sameHost?: boolean; + skipUnchanged: boolean; + startEntryIndex: number; + cancelledTasksRef: MutableRefObject>; + activeChildIdsRef: MutableRefObject>>; + transfersRef: MutableRefObject; + setTransfers: Dispatch>; + waitWhileTransferPaused: (rootTaskId: string, taskId?: string) => Promise; + isPauseLatched: (rootTaskId: string, taskId?: string) => boolean; + transferFile: TransferOneFile; + tryStatTarget: ( + targetPath: string, + ) => Promise<{ size: number; lastModified: number; type: string } | null>; +}; + +/** + * Transfer a flat pre-scanned file list with the same child-task bookkeeping as + * the interleaved directory walk. + */ +export async function transferDiscoveredFiles( + params: TransferDiscoveredFilesParams, +): Promise { + const { + rootTask, + files, + sourceSftpId, + targetSftpId, + sourceIsLocal, + targetIsLocal, + sourceEncoding, + targetEncoding, + rootTaskId, + sameHost, + skipUnchanged, + startEntryIndex, + cancelledTasksRef, + activeChildIdsRef, + transfersRef, + setTransfers, + waitWhileTransferPaused, + isPauseLatched, + transferFile, + tryStatTarget, + } = params; + + if (files.length === 0) return 0; + + setTransfers((prev) => prev.map((candidate) => candidate.id === rootTaskId + ? { ...candidate, phase: "transferring" } + : candidate)); + + const errors: Error[] = []; + let sessionLostError: Error | null = null; + + await runSftpTransferWorkers( + files, + () => localStorageAdapter.readNumber(STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY), + async (file, fileIndex) => { + if (sessionLostError) throw sessionLostError; + if (cancelledTasksRef.current.has(rootTask.id) || cancelledTasksRef.current.has(rootTaskId)) { + throw new Error("Transfer cancelled"); + } + + const fileSize = file.size; + const sourcePath = file.sourcePath; + const targetPath = file.targetPath; + const directoryEntryIndex = startEntryIndex + fileIndex; + const directoryEntryIdentity = createDirectoryEntryIdentity({ + sourcePath, + targetPath, + size: fileSize, + lastModified: file.lastModified, + }); + const persistedChild = transfersRef.current.find((candidate) => ( + candidate.parentTaskId === rootTaskId + && candidate.sourcePath === sourcePath + && candidate.targetPath === targetPath + )); + if (persistedChild?.status === "completed") return; + + await waitWhileTransferPaused(rootTaskId); + if (cancelledTasksRef.current.has(rootTask.id) || cancelledTasksRef.current.has(rootTaskId)) { + throw new Error("Transfer cancelled"); + } + if (isPauseLatched(rootTaskId)) { + await waitWhileTransferPaused(rootTaskId); + } + + if (skipUnchanged) { + const existing = await tryStatTarget(targetPath); + if ( + existing + && existing.type !== "directory" + && isUnchangedTransferCandidate( + { size: fileSize, lastModified: file.lastModified }, + { size: existing.size, lastModified: existing.lastModified }, + ) + ) { + const skippedId = persistedChild?.id ?? crypto.randomUUID(); + setTransfers((prev) => { + const hasChild = prev.some((row) => row.id === skippedId); + const next = hasChild + ? prev.map((row) => row.id === skippedId + ? { + ...row, + status: "completed" as TransferStatus, + transferredBytes: fileSize, + totalBytes: fileSize, + endTime: Date.now(), + speed: 0, + error: undefined, + } + : row) + : [...prev, { + ...rootTask, + id: skippedId, + fileName: file.name, + originalFileName: file.name, + sourcePath, + targetPath, + isDirectory: false, + progressMode: "bytes" as const, + parentTaskId: rootTaskId, + totalBytes: fileSize, + transferredBytes: fileSize, + sourceLastModified: file.lastModified, + directoryEntryIndex, + directoryEntryIdentity, + status: "completed" as TransferStatus, + speed: 0, + startTime: Date.now(), + endTime: Date.now(), + }]; + return next.map((row) => { + if (row.id !== rootTaskId) return row; + if (row.status === "paused" || row.status === "pausing" || isPauseLatched(rootTaskId)) { + return { ...row, speed: 0 }; + } + return { ...row, transferredBytes: row.transferredBytes + 1 }; + }); + }); + return; + } + } + + const fileId = persistedChild?.id ?? crypto.randomUUID(); + if (!activeChildIdsRef.current.has(rootTaskId)) { + activeChildIdsRef.current.set(rootTaskId, new Set()); + } + activeChildIdsRef.current.get(rootTaskId)!.add(fileId); + + const childTask: TransferTask = { + ...rootTask, + ...persistedChild, + id: fileId, + fileName: file.name, + originalFileName: file.name, + sourcePath, + targetPath, + isDirectory: false, + progressMode: "bytes", + parentTaskId: rootTaskId, + totalBytes: fileSize, + sourceLastModified: file.lastModified, + directoryEntryIndex, + directoryEntryIdentity, + retryable: rootTask.retryable, + lifecycleEpoch: undefined, + phase: undefined, + pauseUnavailableReason: undefined, + }; + + setTransfers((prev) => persistedChild + ? prev.map((candidate) => candidate.id === fileId ? { + ...childTask, + status: "queued" as TransferStatus, + speed: 0, + error: undefined, + endTime: undefined, + lifecycleEpoch: undefined, + } : candidate) + : [...prev, { + ...childTask, + status: "queued" as TransferStatus, + transferredBytes: 0, + speed: 0, + startTime: Date.now(), + lifecycleEpoch: undefined, + }]); + + try { + await transferFile( + childTask, + sourceSftpId, + targetSftpId, + sourceIsLocal, + targetIsLocal, + sourceEncoding, + targetEncoding, + rootTaskId, + sameHost, + ); + + activeChildIdsRef.current.get(rootTaskId)?.delete(fileId); + setTransfers((prev) => { + const parentRow = prev.find((row) => row.id === rootTaskId); + const parentFrozen = !!parentRow && ( + parentRow.status === "paused" + || parentRow.status === "pausing" + || isPauseLatched(rootTaskId) + ); + return prev.map((t) => { + if (t.id === fileId) { + return { + ...t, + status: "completed" as TransferStatus, + endTime: Date.now(), + transferredBytes: t.totalBytes, + }; + } + if (t.id === rootTaskId) { + if (parentFrozen) return { ...t, speed: 0 }; + return { ...t, transferredBytes: t.transferredBytes + 1, speed: t.speed }; + } + return t; + }); + }); + await waitWhileTransferPaused(rootTaskId); + } catch (err) { + activeChildIdsRef.current.get(rootTaskId)?.delete(fileId); + const message = err instanceof Error ? err.message : String(err); + if (isTransferCancelledError(err)) { + setTransfers((prev) => prev.map((t) => ( + t.id === fileId + ? { ...t, status: "cancelled" as TransferStatus, error: undefined, endTime: Date.now() } + : t + ))); + errors.push(err instanceof Error ? err : new Error(message)); + return; + } + setTransfers((prev) => prev.map((t) => ( + t.id === fileId + ? { ...t, status: "failed" as TransferStatus, error: message } + : t + ))); + if (isSessionError(err) && !sessionLostError) { + sessionLostError = err instanceof Error ? err : new Error(message); + setTransfers((prev) => prev.map((t) => ( + t.parentTaskId === rootTaskId + && (t.status === "queued" || t.status === "pending") + ? { + ...t, + status: "failed" as TransferStatus, + error: "SFTP session lost — reconnect and resume remaining files", + speed: 0, + endTime: Date.now(), + } + : t + ))); + } + errors.push(err instanceof Error ? err : new Error(message)); + if (sessionLostError) throw sessionLostError; + if (isPauseLatched(rootTaskId)) { + await waitWhileTransferPaused(rootTaskId); + } + } + }, + { + beforeClaim: async () => { + if (sessionLostError) return; + await waitWhileTransferPaused(rootTaskId); + }, + }, + ).catch((err) => { + if (sessionLostError || isTransferCancelledError(err)) return; + throw err; + }); + + if (sessionLostError) { + logger.warn("[SFTP] Directory transfer stopped early: session lost", sessionLostError.message); + } else if (errors.length > 0) { + logger.debug?.("[SFTP] Some files in directory transfer failed", errors); + } + return errors.length; +} diff --git a/application/state/sftp/transferDirectoryOps.ts b/application/state/sftp/transferDirectoryOps.ts index 803a86175..96d2e06c2 100644 --- a/application/state/sftp/transferDirectoryOps.ts +++ b/application/state/sftp/transferDirectoryOps.ts @@ -9,16 +9,28 @@ import { type SftpDirectoryTraversalBudget, shouldFollowSftpSymlinkDirectory, } from "../../../domain/sftpDirectoryCheckpoint"; -import { STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY } from "../../../infrastructure/config/storageKeys"; +import { isUnchangedTransferCandidate } from "../../../domain/sftpTransferSkip"; +import { + STORAGE_KEY_SFTP_FOLDER_PRESCAN, + STORAGE_KEY_SFTP_SKIP_UNCHANGED, + STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY, +} from "../../../infrastructure/config/storageKeys"; import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; import { logger } from "../../../lib/logger"; import { DEFAULT_SFTP_DIRECTORY_LISTING_CONCURRENCY, resolveSftpDirectoryListingConcurrency, + resolveSftpFolderPrescanEnabled, + resolveSftpSkipUnchangedEnabled, runBoundedConcurrency, runSftpTransferWorkers, } from "./transferConcurrency"; +import { + discoverTransferTree, + type DiscoveredTransferFile, +} from "./transferDirectoryDiscovery"; +import { transferDiscoveredFiles } from "./transferDirectoryFileBatch"; import { getSftpTransferResourceKeys, globalSftpTransferScheduler } from "./globalTransferScheduler"; import { resolveDedicatedStreamEndpointIds } from "../../../domain/sftpDedicatedStreamPolicy"; import { isSessionError } from "./errors"; @@ -93,6 +105,59 @@ function isCancelledLocalOrGlobal( return false; } +function readFolderPrescanEnabled(): boolean { + return resolveSftpFolderPrescanEnabled(() => localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_FOLDER_PRESCAN)); +} + +function readSkipUnchangedEnabled(): boolean { + return resolveSftpSkipUnchangedEnabled(() => localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_SKIP_UNCHANGED)); +} + +async function ensureTransferDirectory( + targetPath: string, + targetIsLocal: boolean, + targetSftpId: string | null, + targetEncoding: SftpFilenameEncoding, +): Promise { + if (targetIsLocal) { + try { + await netcattyBridge.get()?.mkdirLocal?.(targetPath); + } catch (mkdirErr: unknown) { + const isEEXIST = mkdirErr instanceof Error && mkdirErr.message.includes("EEXIST"); + if (!isEEXIST) throw mkdirErr; + const stat = await netcattyBridge.get()?.statLocal?.(targetPath); + if (stat && stat.type !== "directory") { + throw new Error(`Target path exists as a file: ${targetPath}`); + } + } + return; + } + if (targetSftpId) { + await netcattyBridge.get()?.mkdirSftp(targetSftpId, targetPath, targetEncoding); + } +} + +async function tryStatTransferTarget( + targetPath: string, + targetIsLocal: boolean, + targetSftpId: string | null, + targetEncoding: SftpFilenameEncoding, +): Promise<{ size: number; lastModified: number; type: string } | null> { + try { + if (targetIsLocal) { + const stat = await netcattyBridge.get()?.statLocal?.(targetPath); + if (!stat || stat.type === "directory") return null; + return { size: Number(stat.size) || 0, lastModified: Number(stat.lastModified) || 0, type: stat.type }; + } + if (!targetSftpId) return null; + const stat = await netcattyBridge.get()?.statSftp?.(targetSftpId, targetPath, targetEncoding); + if (!stat || stat.type === "directory") return null; + return { size: Number(stat.size) || 0, lastModified: Number(stat.lastModified) || 0, type: stat.type }; + } catch { + return null; + } +} + export type AcquireTransferSessionFn = ( hostId: string, transferId: string, @@ -505,6 +570,91 @@ export function useSftpDirectoryTransferOps({ throw new Error("Transfer cancelled"); } + // Root-only pre-scan (rsync --no-inc-recursive): discover the full tree first + // so the transfer center can show a stable file total before bytes move. + if (!discoveryProgress && readFolderPrescanEnabled()) { + const skipUnchanged = readSkipUnchangedEnabled() + && !task.replaceExistingTarget + && !String(task.targetPath).includes(".netcatty-"); + setTransfers((prev) => prev.map((candidate) => candidate.id === rootTaskId + ? { + ...candidate, + phase: "scanning", + totalBytes: Math.max(candidate.transferredBytes, candidate.totalBytes || 0), + } + : candidate)); + + const traversal = traversalBudget ?? createSftpDirectoryTraversalBudget(); + const discovered = await discoverTransferTree({ + sourcePath: task.sourcePath, + targetPath: task.targetPath, + sourceIsLocal, + sourceSftpId, + sourceEncoding, + followSymlinks, + listLocalFiles, + listRemoteFiles, + traversalBudget: traversal, + shouldAbort: () => ( + cancelledTasksRef.current.has(task.id) + || cancelledTasksRef.current.has(rootTaskId) + ), + onDiscoveredFiles: (totalFiles) => { + setTransfers((prev) => prev.map((candidate) => candidate.id === rootTaskId + ? { + ...candidate, + phase: "scanning", + totalBytes: Math.max(totalFiles, candidate.transferredBytes), + } + : candidate)); + }, + }); + + setTransfers((prev) => prev.map((candidate) => candidate.id === rootTaskId + ? { + ...candidate, + totalBytes: Math.max(discovered.files.length, candidate.transferredBytes), + } + : candidate)); + + // Create directories breadth-first so parents exist before children. + for (const dir of discovered.directories) { + if (cancelledTasksRef.current.has(task.id) || cancelledTasksRef.current.has(rootTaskId)) { + throw new Error("Transfer cancelled"); + } + await waitWhileTransferPaused(rootTaskId); + await ensureTransferDirectory(dir.targetPath, targetIsLocal, targetSftpId, targetEncoding); + } + + return transferDiscoveredFiles({ + rootTask: task, + files: discovered.files, + sourceSftpId, + targetSftpId, + sourceIsLocal, + targetIsLocal, + sourceEncoding, + targetEncoding, + rootTaskId, + sameHost, + skipUnchanged, + startEntryIndex: 0, + cancelledTasksRef, + activeChildIdsRef, + transfersRef, + setTransfers, + waitWhileTransferPaused, + isPauseLatched, + transferFile, + tryStatTarget: (targetPath) => tryStatTransferTarget( + targetPath, + targetIsLocal, + targetSftpId, + targetEncoding, + ), + }); + } + let totalErrors = 0; const progress = discoveryProgress ?? { discoveredFiles: 0, @@ -719,6 +869,72 @@ export function useSftpDirectoryTransferOps({ if (isPauseLatched(rootTaskId)) { await waitWhileTransferPaused(rootTaskId); } + + const skipUnchanged = readSkipUnchangedEnabled() + && !task.replaceExistingTarget + && !String(task.targetPath).includes(".netcatty-"); + if (skipUnchanged) { + const existing = await tryStatTransferTarget( + targetPath, + targetIsLocal, + targetSftpId, + targetEncoding, + ); + if ( + existing + && existing.type !== "directory" + && isUnchangedTransferCandidate( + { size: fileSize, lastModified: file.lastModified }, + { size: existing.size, lastModified: existing.lastModified }, + ) + ) { + const skippedId = persistedChild?.id ?? crypto.randomUUID(); + setTransfers((prev) => { + const hasChild = prev.some((row) => row.id === skippedId); + const base = hasChild + ? prev.map((row) => row.id === skippedId + ? { + ...row, + status: "completed" as TransferStatus, + transferredBytes: fileSize, + totalBytes: fileSize, + endTime: Date.now(), + speed: 0, + error: undefined, + } + : row) + : [...prev, { + ...task, + id: skippedId, + fileName: file.name, + originalFileName: file.name, + sourcePath, + targetPath, + isDirectory: false, + progressMode: "bytes" as const, + parentTaskId: rootTaskId, + totalBytes: fileSize, + transferredBytes: fileSize, + sourceLastModified: file.lastModified, + directoryEntryIndex, + directoryEntryIdentity, + status: "completed" as TransferStatus, + speed: 0, + startTime: Date.now(), + endTime: Date.now(), + }]; + return base.map((row) => { + if (row.id !== rootTaskId) return row; + if (row.status === "paused" || row.status === "pausing" || isPauseLatched(rootTaskId)) { + return { ...row, speed: 0 }; + } + return { ...row, transferredBytes: row.transferredBytes + 1 }; + }); + }); + return; + } + } + const fileId = persistedChild?.id ?? crypto.randomUUID(); // Track child ID outside React state for immediate cancellation visibility diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index e15feddd2..544e2dbf5 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -35,6 +35,8 @@ import { STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR, STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD, STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY, + STORAGE_KEY_SFTP_FOLDER_PRESCAN, + STORAGE_KEY_SFTP_SKIP_UNCHANGED, STORAGE_KEY_SSH_TRANSPORT_IDLE_TTL_MS, STORAGE_KEY_SFTP_TRANSFER_POOL_IDLE_TTL_MS, STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, @@ -84,7 +86,11 @@ import { DEFAULT_UI_FONT_ID, withWindowsEmojiFallback } from '../../infrastructu import { uiFontStore, useUIFontsLoaded } from './uiFontStore'; import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; -import { resolveSftpTransferConcurrency } from './sftp/transferConcurrency'; +import { + resolveSftpTransferConcurrency, + resolveSftpFolderPrescanEnabled, + resolveSftpSkipUnchangedEnabled, +} from './sftp/transferConcurrency'; import { resolveSshTransportIdleTtlMs } from '../../infrastructure/config/sshTransportIdleTtl'; import { DEFAULT_ACCENT_MODE, @@ -420,6 +426,12 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable // Folder transfer concurrency is renderer-only (runSftpTransferWorkers). // Do not push it into main-process host admission - that made multi-select // top-level files queue against each other and against folder children. + const [sftpFolderPrescan, setSftpFolderPrescan] = useState(() => + resolveSftpFolderPrescanEnabled(() => localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_FOLDER_PRESCAN)), + ); + const [sftpSkipUnchanged, setSftpSkipUnchanged] = useState(() => + resolveSftpSkipUnchangedEnabled(() => localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_SKIP_UNCHANGED)), + ); const [sshTransportIdleTtlMs, setSshTransportIdleTtlMsState] = useState(() => { // Prefer the new SSH transport key; if absent (upgrade), migrate the legacy @@ -890,6 +902,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable if (storedHidden === 'true' || storedHidden === 'false') setSftpShowHiddenFiles(storedHidden === 'true'); const storedCompress = readStoredString(STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD); if (storedCompress === 'true' || storedCompress === 'false') setSftpUseCompressedUpload(storedCompress === 'true'); + const storedFolderPrescan = localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_FOLDER_PRESCAN); + if (storedFolderPrescan != null) setSftpFolderPrescan(storedFolderPrescan); + const storedSkipUnchanged = localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_SKIP_UNCHANGED); + if (storedSkipUnchanged != null) setSftpSkipUnchanged(storedSkipUnchanged); const storedAutoOpenSidebar = readStoredString(STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR); if (storedAutoOpenSidebar === 'true' || storedAutoOpenSidebar === 'false') setSftpAutoOpenSidebar(storedAutoOpenSidebar === 'true'); const storedFollowTerminalCwd = readStoredString(STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD); @@ -1121,7 +1137,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable customCSS, uiFontFamilyId, hotkeyScheme, uiLanguage, terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize, sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, - sftpUseCompressedUpload, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, + sftpUseCompressedUpload, sftpFolderPrescan, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled, globalHotkeyEnabled, autoUpdateEnabled, windowOpacity, appIconVariant, @@ -1131,7 +1147,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable setTerminalThemeId, setTerminalThemeDarkId, setTerminalThemeLightId, setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize, setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles, - setSftpUseCompressedUpload, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, + setSftpUseCompressedUpload, setSftpFolderPrescan, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode, setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled, setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled, setGlobalHotkeyEnabled, setWindowOpacity: applyIncomingWindowOpacity, setAppIconVariant, setAutoUpdateEnabled, setWorkspaceFocusStyleState, @@ -1359,6 +1375,18 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable notifySettingsChanged(STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD, sftpUseCompressedUpload); }, [sftpUseCompressedUpload, notifySettingsChanged]); + useEffect(() => { + localStorageAdapter.writeBoolean(STORAGE_KEY_SFTP_FOLDER_PRESCAN, sftpFolderPrescan); + if (!persistMountedRef.current) return; + notifySettingsChanged(STORAGE_KEY_SFTP_FOLDER_PRESCAN, sftpFolderPrescan); + }, [sftpFolderPrescan, notifySettingsChanged]); + + useEffect(() => { + localStorageAdapter.writeBoolean(STORAGE_KEY_SFTP_SKIP_UNCHANGED, sftpSkipUnchanged); + if (!persistMountedRef.current) return; + notifySettingsChanged(STORAGE_KEY_SFTP_SKIP_UNCHANGED, sftpSkipUnchanged); + }, [sftpSkipUnchanged, notifySettingsChanged]); + // Persist SFTP auto-open sidebar setting useEffect(() => { localStorageAdapter.writeString(STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR, sftpAutoOpenSidebar ? 'true' : 'false'); @@ -1744,6 +1772,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable setSftpShowHiddenFiles, sftpUseCompressedUpload, setSftpUseCompressedUpload, + sftpFolderPrescan, + setSftpFolderPrescan, + sftpSkipUnchanged, + setSftpSkipUnchanged, sftpAutoOpenSidebar, setSftpAutoOpenSidebar, sftpFollowTerminalCwd, @@ -1828,7 +1860,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable uiFontFamilyId, uiLanguage, customCSS, terminalThemeId, terminalFontFamilyId, terminalFontSize, terminalSettings, customKeyBindings, editorWordWrap, - sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, + sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles, sftpUseCompressedUpload, sftpFolderPrescan, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode, showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, disableTerminalFontZoom, customThemes, workspaceFocusStyle, sessionLogsTimestampsEnabled, sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, explorerContextMenuEnabled, ]), diff --git a/application/syncPayload.ts b/application/syncPayload.ts index 3a552944d..7d889e2e6 100644 --- a/application/syncPayload.ts +++ b/application/syncPayload.ts @@ -71,6 +71,8 @@ import { STORAGE_KEY_SFTP_AUTO_SYNC, STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES, STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD, + STORAGE_KEY_SFTP_FOLDER_PRESCAN, + STORAGE_KEY_SFTP_SKIP_UNCHANGED, STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR, STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD, STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, @@ -283,6 +285,8 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [ STORAGE_KEY_SFTP_AUTO_SYNC, STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES, STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD, + STORAGE_KEY_SFTP_FOLDER_PRESCAN, + STORAGE_KEY_SFTP_SKIP_UNCHANGED, STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR, STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD, STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, @@ -487,6 +491,10 @@ export function collectSyncableSettings(): SyncPayload['settings'] { if (hidden === 'true' || hidden === 'false') settings.sftpShowHiddenFiles = hidden === 'true'; const compress = localStorageAdapter.readString(STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD); if (compress === 'true' || compress === 'false') settings.sftpUseCompressedUpload = compress === 'true'; + const folderPrescan = localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_FOLDER_PRESCAN); + if (folderPrescan != null) settings.sftpFolderPrescan = folderPrescan; + const skipUnchanged = localStorageAdapter.readBoolean(STORAGE_KEY_SFTP_SKIP_UNCHANGED); + if (skipUnchanged != null) settings.sftpSkipUnchanged = skipUnchanged; const autoOpenSidebar = localStorageAdapter.readString(STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR); if (autoOpenSidebar === 'true' || autoOpenSidebar === 'false') settings.sftpAutoOpenSidebar = autoOpenSidebar === 'true'; const followTerminalCwd = localStorageAdapter.readString(STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD); @@ -723,6 +731,8 @@ async function applySyncableSettings(settings: NonNullable + + + + + + { + assert.equal(normalizeTransferMtimeSeconds(1_700_000_000), 1_700_000_000); + assert.equal(normalizeTransferMtimeSeconds(1_700_000_000_500), 1_700_000_000); +}); + +test("isUnchangedTransferCandidate requires matching size and second mtime", () => { + assert.equal( + isUnchangedTransferCandidate( + { size: 10, lastModified: 1_700_000_000_200 }, + { size: 10, lastModified: 1_700_000_000 }, + ), + true, + ); + assert.equal( + isUnchangedTransferCandidate( + { size: 10, lastModified: 1_700_000_000 }, + { size: 11, lastModified: 1_700_000_000 }, + ), + false, + ); + assert.equal( + isUnchangedTransferCandidate( + { size: 10, lastModified: 1_700_000_000 }, + { size: 10, lastModified: 1_700_000_001 }, + ), + false, + ); + assert.equal( + isUnchangedTransferCandidate( + { size: 0, lastModified: 1_700_000_000 }, + { size: 0, lastModified: 1_700_000_000 }, + ), + true, + ); + assert.equal( + isUnchangedTransferCandidate( + { size: 10, lastModified: 0 }, + { size: 10, lastModified: 0 }, + ), + false, + ); +}); diff --git a/domain/sftpTransferSkip.ts b/domain/sftpTransferSkip.ts new file mode 100644 index 000000000..5866cd444 --- /dev/null +++ b/domain/sftpTransferSkip.ts @@ -0,0 +1,33 @@ +/** + * rsync-style "generator" skip: when size and mtime already match the target, + * the file does not need to be transferred again. + * + * SFTP mtimes are typically second-precision; compare on whole seconds so a + * local millisecond timestamp does not defeat an otherwise identical remote. + */ + +export interface TransferSkipIdentity { + size: number; + lastModified: number; +} + +export function normalizeTransferMtimeSeconds(lastModified: number): number { + if (!Number.isFinite(lastModified) || lastModified <= 0) return 0; + // Values below 1e12 are already seconds (SFTP / some bridges); larger are ms. + return lastModified >= 1e12 ? Math.floor(lastModified / 1000) : Math.floor(lastModified); +} + +export function isUnchangedTransferCandidate( + source: TransferSkipIdentity, + target: TransferSkipIdentity, +): boolean { + const sourceSize = Number(source.size); + const targetSize = Number(target.size); + if (!Number.isFinite(sourceSize) || !Number.isFinite(targetSize)) return false; + if (sourceSize !== targetSize) return false; + if (sourceSize < 0 || targetSize < 0) return false; + const sourceMtime = normalizeTransferMtimeSeconds(source.lastModified); + const targetMtime = normalizeTransferMtimeSeconds(target.lastModified); + if (sourceMtime <= 0 || targetMtime <= 0) return false; + return sourceMtime === targetMtime; +} diff --git a/domain/sync.ts b/domain/sync.ts index a72773c12..6eef9c8b4 100644 --- a/domain/sync.ts +++ b/domain/sync.ts @@ -324,6 +324,8 @@ export interface SyncPayload { sftpAutoSync?: boolean; sftpShowHiddenFiles?: boolean; sftpUseCompressedUpload?: boolean; + sftpFolderPrescan?: boolean; + sftpSkipUnchanged?: boolean; sftpAutoOpenSidebar?: boolean; sftpFollowTerminalCwd?: boolean; sftpDefaultViewMode?: 'list' | 'tree'; diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index 31f70d4eb..972c0482a 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -204,6 +204,10 @@ export const STORAGE_KEY_AI_EXTERNAL_MCP_SILENT_SESSIONS = 'netcatty_ai_external // SFTP Transfer Concurrency export const STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY = 'netcatty_sftp_transfer_concurrency_v1'; +/** Folder transfers: scan the full tree before moving bytes (stable file totals). */ +export const STORAGE_KEY_SFTP_FOLDER_PRESCAN = 'netcatty_sftp_folder_prescan_v1'; +/** Skip files when target size + mtime already match the source (rsync-like). */ +export const STORAGE_KEY_SFTP_SKIP_UNCHANGED = 'netcatty_sftp_skip_unchanged_v1'; /** * @deprecated Legacy transfer-pool idle TTL. No longer read; SSH keep-alive uses * STORAGE_KEY_SSH_TRANSPORT_IDLE_TTL_MS. Kept so old localStorage entries are ignored safely.