mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-17 13:01:24 +00:00
* refactor: unify directory download with upload transfer system Directory downloads previously used a completely separate implementation with custom queue management, progress tracking, and concurrency control (~390 lines in useSftpViewFileOps.ts). This caused the download UI to show only a single aggregate task without child file details, unlike uploads which showed parent + child tasks. Replace the custom download implementation with a new downloadToLocal() method in useSftpTransfers that reuses the existing transferDirectory/ transferFile infrastructure. Downloads now: - Show parent task with child file tasks (same as uploads) - Use the configurable transfer concurrency setting - Support cancellation through the same mechanism - Share progress tracking and conflict detection code Net reduction of ~260 lines. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove dead code from directory download refactor Remove listSftp, mkdirLocal, and RemoteFile imports that were only used by the old custom directory download implementation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: handle symlink directories in transfers and remove dead code - Use isNavigableDirectory() instead of type === "directory" in transferDirectory so symlinks pointing to directories are recursed into correctly (fixes both upload and download paths) - Remove unused deleteLocalFile prop from useSftpViewFileOps Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use connection ID for download tasks and cancel child streams - Use pane connection ID (not SFTP session ID) as sourceConnectionId so download tasks are properly associated with the host and visible in filtered transfer views - Cancel all active child transfer streams at the backend when parent is cancelled, not just the parent ID — stops data transfer immediately Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add symlink cycle detection and propagate child failures - Add visitedPaths Set to transferDirectory to detect and skip symlink directory cycles that would cause infinite recursion - Check for failed child tasks after transferDirectory completes and mark parent as failed instead of falsely reporting success Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use depth limit for symlink loops and handle EEXIST on mkdir - Replace visited-paths cycle detection with a depth limit (64), which reliably catches symlink loops that generate new path strings each hop (e.g. /dir/link/link/link...) - Handle EEXIST errors in mkdirLocal gracefully so re-downloading to an existing directory doesn't abort the entire transfer Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: throw on depth limit exceeded and mark downloads non-retryable - Depth limit now throws instead of silently returning, so exceeding it surfaces as a failed transfer rather than an incomplete success - Set retryable: false on downloadToLocal tasks since retryTransfer cannot resolve the synthetic "local" connection ID Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: track symlink depth only and verify EEXIST target is directory - Change depth guard to only count symlink directory hops, not total directory depth, so legitimate deep trees are not rejected - After catching EEXIST on mkdirLocal, stat the path to verify it is actually a directory — throw if a regular file exists at that path Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove dead props from callbacks and surface download failures - Remove mkdirLocal and deleteLocalFile from useSftpViewPaneCallbacks interface and passthrough (fixes TS2353 build error) - Show error toast when downloadToLocal returns "failed" status, not just when it throws Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: track child transfer IDs outside React state for reliable cancel Child transfer IDs were only discoverable via transfersRef.current, which lags behind setTransfers due to React batching. This caused two race conditions: 1. Cancellation: child streams started between setTransfers and render were not cancelled at the backend, continuing to write data. 2. Failure detection: hasFailedChildren checked transfersRef which might not reflect recently-failed children, marking partial downloads as successful. Fix: track active child IDs in activeChildIdsRef (a mutable Map outside React state) for immediate visibility during cancellation. Check child failure status inside setTransfers functional updater where the latest state is guaranteed. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: preserve actual progress on partial failure and count symlink dirs - Don't force transferredBytes to totalBytes when some children failed, so the progress bar accurately reflects the partial completion - Use isNavigableDirectory in countDirectoryFiles and estimateDirectoryBytes so symlink directories are included in size/count estimates Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: symlink count, progress on fast downloads, and child cancellation 1. countDirectoryFiles: use isNavigableDirectory so symlink dirs are recursed into, keeping totals consistent with transferDirectory 2. Final status: compute actual completedCount from children instead of relying on totalBytes which may be 0 if the background scan hasn't finished yet 3. Catch block: detect cancellation from error message (not just cancelledTasksRef) so child-initiated cancels don't show as errors Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add symlink depth guard to countDirectoryFiles and estimateDirectoryBytes Both helper functions now track symlink depth and stop recursing when MAX_SYMLINK_DEPTH is exceeded, consistent with transferDirectory. Prevents infinite recursion on symlink directory cycles during the background file count/size scan. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: reliable final status and non-retryable child tasks 1. transferDirectory now returns the count of failed child transfers, tracked outside React state. downloadToLocal uses this count directly instead of reading from setTransfers updater (which may be deferred by React batching), ensuring the correct status is returned to the caller for toast messages. 2. Child tasks explicitly inherit retryable from the parent task. For downloadToLocal (retryable: false), this prevents showing retry actions on failed children whose "local" targetConnectionId cannot be resolved by retryTransfer. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add ancestor path cycle detection for symlink directories The depth-only guard allowed up to 32 pointless traversals before stopping a symlink cycle (e.g. dir/link -> .). Add an ancestorPaths Set that tracks the current recursion stack — if a directory's source path is already in the set, it's an immediate cycle and is skipped with zero wasted traversals. The depth limit remains as a hard backstop. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: don't recurse into symlink directories during transfers Revert to only recursing into real directories (type === "directory") in transferDirectory, countDirectoryFiles, and estimateDirectoryBytes. Symlink directories are now transferred as regular entries instead of being followed, eliminating all symlink cycle risks without needing complex cycle detection that can't reliably work with unresolved remote paths. Also clean up activeChildIdsRef in processTransfer (both success and error paths) to prevent memory leaks from pane-to-pane directory transfers. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: filter "." entries and recurse into symlink dirs with depth guard 1. Filter both "." and ".." in all recursive functions — some SFTP servers include "." in readdir, causing infinite self-recursion. 2. Restore symlink directory recursion in transferDirectory with a symlinkDepth counter (max 32). Symlink dirs that exceed the limit are excluded from the dirs list (treated as files). This is needed because startStreamTransfer cannot transfer a directory as a file, so skipping symlink dirs caused child transfer failures. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add symlink depth guard to count/estimate helpers countDirectoryFiles and estimateDirectoryBytes now track symlinkDepth consistently with transferDirectory, preventing infinite recursion on symlink cycles in the background file count/size estimation. Also fixes: - Remove fragile string-based cancellation detection in downloadToLocal - Clean up cancelledTasksRef in downloadToLocal catch block - Move MAX_SYMLINK_DEPTH before its first use Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use path reconstruction instead of string replace for duplicate conflicts resolveConflict's "duplicate" action used String.replace to swap the filename in the target path, but this replaces the first occurrence which can corrupt the path if the filename also appears in a parent directory name. Use joinPath(getParentPath(...), newName) instead. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: skip over-depth symlink directories instead of treating as files When symlinkDepth exceeds MAX_SYMLINK_DEPTH, symlink directories were falling through to regularFiles and being passed to transferFile, which cannot transfer directories and would produce confusing errors. Now they are skipped entirely with a warning log. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: count skipped symlinks as errors and process subdirs concurrently 1. Symlink directories skipped at MAX_SYMLINK_DEPTH now increment totalErrors so the parent task is marked failed instead of silently reporting success with incomplete content. 2. Sibling subdirectories are now processed with Promise.all instead of sequential await, restoring cross-directory concurrency that the old download implementation had. Files within each directory still use the configurable worker pool concurrency. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: sequential subdirs to prevent SFTP overload and check dir errors in processTransfer 1. Revert subdirectory processing to sequential (for...of await) to prevent unbounded concurrent SFTP requests from nested Promise.all + worker pools across the directory tree. File-level concurrency within each directory is still governed by getTransferConcurrency(). 2. processTransfer now captures transferDirectory's error count return value and marks the parent task as "failed" when child transfers fail, instead of unconditionally marking "completed". Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: remove redundant completed state update for directory transfers Directory success path no longer writes "completed" in both the directory-specific block and the generic block. The directory-specific block now only handles the failure case with early return; success falls through to the generic completed block. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: route partial directory failures through shared completion path The early return for directory transfer failures skipped cache invalidation, target pane refresh, and onTransferComplete callbacks (needed by cut/paste to clear clipboard). Now partial failures flow through the same cleanup path as successes — cache is cleared, target is refreshed, and completionHandler is called with the correct "failed" status. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restrict symlink directory recursion to downloadToLocal only Add followSymlinks parameter (default false) to transferDirectory, countDirectoryFiles, and estimateDirectoryBytes. Only downloadToLocal passes true — uploads and pane-to-pane copies retain their original behavior of treating symlink directories as regular entries. This prevents existing upload/copy flows from expanding symlinked directory trees (which could duplicate content or trigger cycles), while still allowing local downloads to recursively copy through symlink directories with depth protection. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: disable retry for partial dir failures and fix symlink file count 1. Mark partially failed directory transfers as retryable: false to prevent retry from replaying the entire directory without conflict checks, which would silently overwrite already-copied files. 2. In countDirectoryFiles and estimateDirectoryBytes, skip over-depth symlink directories entirely instead of counting them as files. This makes the totals consistent with transferDirectory which also skips these entries, preventing impossible progress like "10/11". Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
685 lines
24 KiB
TypeScript
685 lines
24 KiB
TypeScript
import React, { useCallback, useRef, useState } from "react";
|
|
import type { MutableRefObject } from "react";
|
|
import type { SftpFileEntry, SftpFilenameEncoding } from "../../../types";
|
|
import { getParentPath, joinPath as joinFsPath } from "../../../application/state/sftp/utils";
|
|
import type { SftpStateApi } from "../../../application/state/useSftpState";
|
|
import { logger } from "../../../lib/logger";
|
|
import { toast } from "../../ui/toast";
|
|
import { getFileExtension, FileOpenerType, SystemAppInfo } from "../../../lib/sftpFileUtils";
|
|
import { isNavigableDirectory } from "../index";
|
|
|
|
interface UseSftpViewFileOpsParams {
|
|
sftpRef: MutableRefObject<SftpStateApi>;
|
|
behaviorRef: MutableRefObject<string>;
|
|
autoSyncRef: MutableRefObject<boolean>;
|
|
getOpenerForFileRef: MutableRefObject<
|
|
(fileName: string) => { openerType?: FileOpenerType; systemApp?: SystemAppInfo } | null
|
|
>;
|
|
setOpenerForExtension: (
|
|
extension: string,
|
|
openerType: FileOpenerType,
|
|
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>;
|
|
startStreamTransfer?: (
|
|
options: {
|
|
transferId: string;
|
|
sourcePath: string;
|
|
targetPath: string;
|
|
sourceType: 'local' | 'sftp';
|
|
targetType: 'local' | 'sftp';
|
|
sourceSftpId?: string;
|
|
targetSftpId?: string;
|
|
totalBytes?: number;
|
|
sourceEncoding?: SftpFilenameEncoding;
|
|
targetEncoding?: SftpFilenameEncoding;
|
|
},
|
|
onProgress?: (transferred: number, total: number, speed: number) => void,
|
|
onComplete?: () => void,
|
|
onError?: (error: string) => void
|
|
) => Promise<{ transferId: string; totalBytes?: number; error?: string }>;
|
|
getSftpIdForConnection?: (connectionId: string) => string | undefined;
|
|
}
|
|
|
|
interface UseSftpViewFileOpsResult {
|
|
permissionsState: { file: SftpFileEntry; side: "left" | "right"; fullPath: string } | null;
|
|
setPermissionsState: React.Dispatch<
|
|
React.SetStateAction<{ file: SftpFileEntry; side: "left" | "right"; fullPath: string } | null>
|
|
>;
|
|
showTextEditor: boolean;
|
|
setShowTextEditor: React.Dispatch<React.SetStateAction<boolean>>;
|
|
textEditorTarget: {
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null;
|
|
setTextEditorTarget: React.Dispatch<
|
|
React.SetStateAction<{
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null>
|
|
>;
|
|
textEditorContent: string;
|
|
setTextEditorContent: React.Dispatch<React.SetStateAction<string>>;
|
|
loadingTextContent: boolean;
|
|
showFileOpenerDialog: boolean;
|
|
setShowFileOpenerDialog: React.Dispatch<React.SetStateAction<boolean>>;
|
|
fileOpenerTarget: {
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null;
|
|
setFileOpenerTarget: React.Dispatch<
|
|
React.SetStateAction<{
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null>
|
|
>;
|
|
handleSaveTextFile: (content: string) => Promise<void>;
|
|
handleFileOpenerSelect: (
|
|
openerType: FileOpenerType,
|
|
setAsDefault: boolean,
|
|
systemApp?: SystemAppInfo,
|
|
) => Promise<void>;
|
|
handleSelectSystemApp: () => Promise<SystemAppInfo | null>;
|
|
onEditPermissionsLeft: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onEditPermissionsRight: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenEntryLeft: (entry: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenEntryRight: (entry: SftpFileEntry, fullPath?: string) => void;
|
|
onEditFileLeft: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onEditFileRight: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenFileLeft: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenFileRight: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenFileWithLeft: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onOpenFileWithRight: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onDownloadFileLeft: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onDownloadFileRight: (file: SftpFileEntry, fullPath?: string) => void;
|
|
onUploadExternalFilesLeft: (dataTransfer: DataTransfer, targetPath?: string) => void;
|
|
onUploadExternalFilesRight: (dataTransfer: DataTransfer, targetPath?: string) => void;
|
|
}
|
|
|
|
export const useSftpViewFileOps = ({
|
|
sftpRef,
|
|
behaviorRef,
|
|
autoSyncRef,
|
|
getOpenerForFileRef,
|
|
setOpenerForExtension,
|
|
t,
|
|
showSaveDialog,
|
|
selectDirectory,
|
|
startStreamTransfer,
|
|
getSftpIdForConnection,
|
|
}: UseSftpViewFileOpsParams): UseSftpViewFileOpsResult => {
|
|
const [permissionsState, setPermissionsState] = useState<{
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null>(null);
|
|
|
|
const [showTextEditor, setShowTextEditor] = useState(false);
|
|
const [textEditorTarget, setTextEditorTarget] = useState<{
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
/** Host ID at the time the file was opened, to prevent saving to wrong host.
|
|
* Uses hostId (not connectionId) because auto-reconnect after a transient
|
|
* disconnect generates a fresh connectionId for the same endpoint. */
|
|
hostId?: string;
|
|
} | null>(null);
|
|
const [textEditorContent, setTextEditorContent] = useState("");
|
|
const [loadingTextContent, setLoadingTextContent] = useState(false);
|
|
|
|
const [showFileOpenerDialog, setShowFileOpenerDialog] = useState(false);
|
|
const [fileOpenerTarget, setFileOpenerTarget] = useState<{
|
|
file: SftpFileEntry;
|
|
side: "left" | "right";
|
|
fullPath: string;
|
|
} | null>(null);
|
|
|
|
// Refs for frequently-changing state used inside stable callbacks
|
|
const fileOpenerTargetRef = useRef(fileOpenerTarget);
|
|
fileOpenerTargetRef.current = fileOpenerTarget;
|
|
const textEditorTargetRef = useRef(textEditorTarget);
|
|
textEditorTargetRef.current = textEditorTarget;
|
|
|
|
const onEditPermissionsLeft = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = sftpRef.current.leftPane;
|
|
if (!pane.connection) return;
|
|
setPermissionsState({
|
|
file,
|
|
side: "left",
|
|
fullPath: fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name),
|
|
});
|
|
},
|
|
[sftpRef],
|
|
);
|
|
const onEditPermissionsRight = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = sftpRef.current.rightPane;
|
|
if (!pane.connection) return;
|
|
setPermissionsState({
|
|
file,
|
|
side: "right",
|
|
fullPath: fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name),
|
|
});
|
|
},
|
|
[sftpRef],
|
|
);
|
|
|
|
const handleEditFileForSide = useCallback(
|
|
async (side: "left" | "right", file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = side === "left" ? sftpRef.current.leftPane : sftpRef.current.rightPane;
|
|
if (!pane.connection) return;
|
|
|
|
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name);
|
|
|
|
try {
|
|
setLoadingTextContent(true);
|
|
setTextEditorTarget({ file, side, fullPath: resolvedFullPath, hostId: pane.connection.hostId });
|
|
|
|
const content = await sftpRef.current.readTextFile(side, resolvedFullPath);
|
|
|
|
setTextEditorContent(content);
|
|
setShowTextEditor(true);
|
|
} catch (e) {
|
|
toast.error(e instanceof Error ? e.message : "Failed to load file", "SFTP");
|
|
setTextEditorTarget(null);
|
|
} finally {
|
|
setLoadingTextContent(false);
|
|
}
|
|
},
|
|
[sftpRef],
|
|
);
|
|
|
|
const handleOpenFileForSide = useCallback(
|
|
async (side: "left" | "right", file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = side === "left" ? sftpRef.current.leftPane : sftpRef.current.rightPane;
|
|
if (!pane.connection) return;
|
|
|
|
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name);
|
|
const savedOpener = getOpenerForFileRef.current(file.name);
|
|
|
|
if (savedOpener && savedOpener.openerType) {
|
|
if (savedOpener.openerType === "builtin-editor") {
|
|
handleEditFileForSide(side, file, resolvedFullPath);
|
|
return;
|
|
} else if (savedOpener.openerType === "system-app" && savedOpener.systemApp) {
|
|
try {
|
|
await sftpRef.current.downloadToTempAndOpen(
|
|
side,
|
|
resolvedFullPath,
|
|
file.name,
|
|
savedOpener.systemApp.path,
|
|
{ enableWatch: autoSyncRef.current },
|
|
);
|
|
} catch (e) {
|
|
toast.error(e instanceof Error ? e.message : "Failed to open file", "SFTP");
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
setFileOpenerTarget({ file, side, fullPath: resolvedFullPath });
|
|
setShowFileOpenerDialog(true);
|
|
},
|
|
[sftpRef, handleEditFileForSide, getOpenerForFileRef, autoSyncRef],
|
|
);
|
|
|
|
const handleFileOpenerSelect = useCallback(
|
|
async (openerType: FileOpenerType, setAsDefault: boolean, systemApp?: SystemAppInfo) => {
|
|
const target = fileOpenerTargetRef.current;
|
|
if (!target) return;
|
|
|
|
if (setAsDefault) {
|
|
const ext = getFileExtension(target.file.name);
|
|
setOpenerForExtension(ext, openerType, systemApp);
|
|
}
|
|
|
|
setShowFileOpenerDialog(false);
|
|
|
|
if (openerType === "builtin-editor") {
|
|
handleEditFileForSide(target.side, target.file, target.fullPath);
|
|
} else if (openerType === "system-app" && systemApp) {
|
|
try {
|
|
await sftpRef.current.downloadToTempAndOpen(
|
|
target.side,
|
|
target.fullPath,
|
|
target.file.name,
|
|
systemApp.path,
|
|
{ enableWatch: autoSyncRef.current },
|
|
);
|
|
} catch (e) {
|
|
toast.error(e instanceof Error ? e.message : "Failed to open file", "SFTP");
|
|
}
|
|
}
|
|
|
|
setFileOpenerTarget(null);
|
|
},
|
|
[setOpenerForExtension, handleEditFileForSide, autoSyncRef, sftpRef],
|
|
);
|
|
|
|
const handleSelectSystemApp = useCallback(async (): Promise<SystemAppInfo | null> => {
|
|
const result = await sftpRef.current.selectApplication();
|
|
if (result) {
|
|
return { path: result.path, name: result.name };
|
|
}
|
|
return null;
|
|
}, [sftpRef]);
|
|
|
|
const handleSaveTextFile = useCallback(
|
|
async (content: string) => {
|
|
const target = textEditorTargetRef.current;
|
|
if (!target) return;
|
|
|
|
// Verify the SFTP connection hasn't switched to a different host.
|
|
// We check hostId (not connectionId) because auto-reconnect after a
|
|
// transient disconnect generates a fresh connectionId for the same
|
|
// endpoint. The auto-connect effect in SftpSidePanel blocks
|
|
// host-switching while the editor is open, so a hostId mismatch here
|
|
// reliably indicates a genuinely different endpoint.
|
|
const currentPane = target.side === "left"
|
|
? sftpRef.current.leftPane
|
|
: sftpRef.current.rightPane;
|
|
if (target.hostId && currentPane.connection?.hostId !== target.hostId) {
|
|
throw new Error("SFTP connection changed while editing — file not saved to prevent writing to wrong host");
|
|
}
|
|
|
|
await sftpRef.current.writeTextFile(
|
|
target.side,
|
|
target.fullPath,
|
|
content,
|
|
);
|
|
},
|
|
[sftpRef],
|
|
);
|
|
|
|
const onEditFileLeft = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleEditFileForSide("left", file, fullPath),
|
|
[handleEditFileForSide],
|
|
);
|
|
const onEditFileRight = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleEditFileForSide("right", file, fullPath),
|
|
[handleEditFileForSide],
|
|
);
|
|
const onOpenFileLeft = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleOpenFileForSide("left", file, fullPath),
|
|
[handleOpenFileForSide],
|
|
);
|
|
const onOpenFileRight = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleOpenFileForSide("right", file, fullPath),
|
|
[handleOpenFileForSide],
|
|
);
|
|
|
|
const handleOpenFileWithForSide = useCallback(
|
|
(side: "left" | "right", file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = side === "left" ? sftpRef.current.leftPane : sftpRef.current.rightPane;
|
|
if (!pane.connection) return;
|
|
|
|
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name);
|
|
setFileOpenerTarget({ file, side, fullPath: resolvedFullPath });
|
|
setShowFileOpenerDialog(true);
|
|
},
|
|
[sftpRef],
|
|
);
|
|
|
|
const onOpenFileWithLeft = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleOpenFileWithForSide("left", file, fullPath),
|
|
[handleOpenFileWithForSide],
|
|
);
|
|
const onOpenFileWithRight = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleOpenFileWithForSide("right", file, fullPath),
|
|
[handleOpenFileWithForSide],
|
|
);
|
|
|
|
const handleUploadExternalFilesForSide = useCallback(
|
|
async (side: "left" | "right", dataTransfer: DataTransfer, targetPath?: string) => {
|
|
try {
|
|
const results = await sftpRef.current.uploadExternalFiles(side, dataTransfer, targetPath);
|
|
|
|
// Check if upload was cancelled
|
|
if (results.some((r) => r.cancelled)) {
|
|
toast.info(t("sftp.upload.cancelled"), "SFTP");
|
|
return;
|
|
}
|
|
|
|
const failCount = results.filter((r) => !r.success && !r.cancelled).length;
|
|
const successCount = results.filter((r) => r.success).length;
|
|
|
|
if (failCount === 0) {
|
|
const message =
|
|
successCount === 1
|
|
? `${t("sftp.upload")}: ${results[0].fileName}`
|
|
: `${t("sftp.uploadFiles")}: ${successCount}`;
|
|
toast.success(message, "SFTP");
|
|
} else {
|
|
const failedFiles = results.filter((r) => !r.success && !r.cancelled);
|
|
failedFiles.forEach((failed) => {
|
|
const errorMsg = failed.error ? ` - ${failed.error}` : "";
|
|
toast.error(
|
|
`${t("sftp.error.uploadFailed")}: ${failed.fileName}${errorMsg}`,
|
|
"SFTP",
|
|
);
|
|
});
|
|
}
|
|
} catch (error) {
|
|
logger.error("[SftpView] Failed to upload external files:", error);
|
|
toast.error(
|
|
error instanceof Error ? error.message : t("sftp.error.uploadFailed"),
|
|
"SFTP",
|
|
);
|
|
}
|
|
},
|
|
[sftpRef, t],
|
|
);
|
|
|
|
const onUploadExternalFilesLeft = useCallback(
|
|
(dataTransfer: DataTransfer, targetPath?: string) => handleUploadExternalFilesForSide("left", dataTransfer, targetPath),
|
|
[handleUploadExternalFilesForSide],
|
|
);
|
|
|
|
const onUploadExternalFilesRight = useCallback(
|
|
(dataTransfer: DataTransfer, targetPath?: string) => handleUploadExternalFilesForSide("right", dataTransfer, targetPath),
|
|
[handleUploadExternalFilesForSide],
|
|
);
|
|
|
|
const handleDownloadFileForSide = useCallback(
|
|
async (side: "left" | "right", file: SftpFileEntry, fullPath?: string) => {
|
|
const pane = side === "left" ? sftpRef.current.leftPane : sftpRef.current.rightPane;
|
|
if (!pane.connection) return;
|
|
|
|
const resolvedFullPath = fullPath ?? sftpRef.current.joinPath(pane.connection.currentPath, file.name);
|
|
const isDirectory = isNavigableDirectory(file);
|
|
|
|
try {
|
|
// For local files, use blob download.
|
|
if (pane.connection.isLocal) {
|
|
if (isDirectory) {
|
|
toast.error(t("sftp.error.downloadFailed"), "SFTP");
|
|
return;
|
|
}
|
|
|
|
const content = await sftpRef.current.readBinaryFile(side, resolvedFullPath);
|
|
|
|
const blob = new Blob([content], { type: "application/octet-stream" });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement("a");
|
|
a.href = url;
|
|
a.download = file.name;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
|
|
toast.success(`${t("sftp.context.download")}: ${file.name}`, "SFTP");
|
|
return;
|
|
}
|
|
|
|
// For remote SFTP files/directories, use streaming download with save dialog.
|
|
if (!showSaveDialog || !startStreamTransfer || !getSftpIdForConnection) {
|
|
toast.error(t("sftp.error.downloadFailed"), "SFTP");
|
|
return;
|
|
}
|
|
|
|
const sftpId = getSftpIdForConnection(pane.connection.id);
|
|
if (!sftpId) {
|
|
throw new Error("SFTP session not found");
|
|
}
|
|
|
|
if (isDirectory) {
|
|
if (!selectDirectory) {
|
|
toast.error(t("sftp.error.downloadFailed"), "SFTP");
|
|
return;
|
|
}
|
|
|
|
const selectedDirectory = await selectDirectory(t("sftp.context.download"));
|
|
if (!selectedDirectory) return;
|
|
|
|
const targetPath = joinFsPath(selectedDirectory, file.name);
|
|
|
|
try {
|
|
const status = await sftpRef.current.downloadToLocal({
|
|
fileName: file.name,
|
|
sourcePath: resolvedFullPath,
|
|
targetPath,
|
|
sftpId,
|
|
connectionId: pane.connection.id,
|
|
sourceEncoding: pane.filenameEncoding,
|
|
isDirectory: true,
|
|
});
|
|
if (status === "completed") {
|
|
toast.success(`${t("sftp.context.download")}: ${file.name}`, "SFTP");
|
|
} else if (status === "failed") {
|
|
toast.error(`${t("sftp.error.downloadFailed")}: ${file.name}`, "SFTP");
|
|
}
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : t("sftp.error.downloadFailed");
|
|
if (!errorMessage.includes("cancelled") && !errorMessage.includes("canceled")) {
|
|
toast.error(errorMessage, "SFTP");
|
|
}
|
|
}
|
|
|
|
return;
|
|
}
|
|
// Show save dialog to get target path
|
|
const targetPath = await showSaveDialog(file.name);
|
|
if (!targetPath) {
|
|
// User cancelled
|
|
return;
|
|
}
|
|
|
|
const transferId = `download-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
const fileSize = typeof file.size === 'string' ? parseInt(file.size, 10) || 0 : (file.size || 0);
|
|
|
|
// Add download task to transfer queue for progress display
|
|
sftpRef.current.addExternalUpload({
|
|
id: transferId,
|
|
fileName: file.name,
|
|
sourcePath: resolvedFullPath,
|
|
targetPath,
|
|
sourceConnectionId: pane.connection.id,
|
|
targetConnectionId: 'local',
|
|
direction: 'download',
|
|
status: 'transferring',
|
|
totalBytes: fileSize,
|
|
transferredBytes: 0,
|
|
speed: 0,
|
|
startTime: Date.now(),
|
|
isDirectory: false,
|
|
});
|
|
|
|
// Track if error was already handled by callback
|
|
let errorHandled = false;
|
|
|
|
const result = await startStreamTransfer(
|
|
{
|
|
transferId,
|
|
sourcePath: resolvedFullPath,
|
|
targetPath,
|
|
sourceType: 'sftp',
|
|
targetType: 'local',
|
|
sourceSftpId: sftpId,
|
|
totalBytes: fileSize,
|
|
sourceEncoding: pane.filenameEncoding,
|
|
},
|
|
(transferred, total, speed) => {
|
|
// Update transfer progress in the queue
|
|
sftpRef.current.updateExternalUpload(transferId, {
|
|
transferredBytes: transferred,
|
|
totalBytes: total,
|
|
speed,
|
|
});
|
|
},
|
|
() => {
|
|
// Mark as completed
|
|
sftpRef.current.updateExternalUpload(transferId, {
|
|
status: 'completed',
|
|
transferredBytes: fileSize,
|
|
endTime: Date.now(),
|
|
});
|
|
toast.success(`${t("sftp.context.download")}: ${file.name}`, "SFTP");
|
|
},
|
|
(error) => {
|
|
errorHandled = true;
|
|
// Check if this is a cancellation - don't show error toast for cancellations
|
|
const isCancelError = error.includes('cancelled') || error.includes('canceled');
|
|
sftpRef.current.updateExternalUpload(transferId, {
|
|
status: isCancelError ? 'cancelled' : 'failed',
|
|
error: isCancelError ? undefined : error,
|
|
endTime: Date.now(),
|
|
});
|
|
if (!isCancelError) {
|
|
toast.error(error, "SFTP");
|
|
}
|
|
}
|
|
);
|
|
|
|
// Check if bridge doesn't support streaming (returns undefined)
|
|
if (result === undefined) {
|
|
sftpRef.current.updateExternalUpload(transferId, {
|
|
status: 'failed',
|
|
error: t("sftp.error.downloadFailed"),
|
|
endTime: Date.now(),
|
|
});
|
|
toast.error(t("sftp.error.downloadFailed"), "SFTP");
|
|
return;
|
|
}
|
|
|
|
// Handle error from result only if onError callback wasn't called
|
|
if (result?.error && !errorHandled) {
|
|
const isCancelError = result.error.includes('cancelled') || result.error.includes('canceled');
|
|
sftpRef.current.updateExternalUpload(transferId, {
|
|
status: isCancelError ? 'cancelled' : 'failed',
|
|
error: isCancelError ? undefined : result.error,
|
|
endTime: Date.now(),
|
|
});
|
|
if (!isCancelError) {
|
|
toast.error(result.error, "SFTP");
|
|
}
|
|
}
|
|
} catch (e) {
|
|
logger.error("[SftpView] Failed to download file:", e);
|
|
toast.error(
|
|
e instanceof Error ? e.message : t("sftp.error.downloadFailed"),
|
|
"SFTP",
|
|
);
|
|
}
|
|
},
|
|
[
|
|
sftpRef,
|
|
t,
|
|
showSaveDialog,
|
|
selectDirectory,
|
|
startStreamTransfer,
|
|
getSftpIdForConnection,
|
|
],
|
|
);
|
|
|
|
const onDownloadFileLeft = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleDownloadFileForSide("left", file, fullPath),
|
|
[handleDownloadFileForSide],
|
|
);
|
|
|
|
const onDownloadFileRight = useCallback(
|
|
(file: SftpFileEntry, fullPath?: string) => handleDownloadFileForSide("right", file, fullPath),
|
|
[handleDownloadFileForSide],
|
|
);
|
|
|
|
const onOpenEntryLeft = useCallback(
|
|
(entry: SftpFileEntry, fullPath?: string) => {
|
|
const pane = sftpRef.current.leftPane;
|
|
const isDir = isNavigableDirectory(entry);
|
|
|
|
if (entry.name === ".." || isDir) {
|
|
sftpRef.current.openEntry("left", entry);
|
|
return;
|
|
}
|
|
|
|
if (behaviorRef.current === "transfer") {
|
|
const sourcePath = fullPath ? getParentPath(fullPath) : pane.connection?.currentPath;
|
|
const sourceConnectionId = pane.connection?.id;
|
|
const fileData = [{
|
|
name: entry.name,
|
|
isDirectory: isDir,
|
|
sourceConnectionId,
|
|
sourcePath,
|
|
}];
|
|
sftpRef.current.startTransfer(fileData, "left", "right", {
|
|
sourceConnectionId,
|
|
sourcePath,
|
|
});
|
|
} else {
|
|
onOpenFileLeft(entry, fullPath);
|
|
}
|
|
},
|
|
[sftpRef, onOpenFileLeft, behaviorRef],
|
|
);
|
|
|
|
const onOpenEntryRight = useCallback(
|
|
(entry: SftpFileEntry, fullPath?: string) => {
|
|
const pane = sftpRef.current.rightPane;
|
|
const isDir = isNavigableDirectory(entry);
|
|
|
|
if (entry.name === ".." || isDir) {
|
|
sftpRef.current.openEntry("right", entry);
|
|
return;
|
|
}
|
|
|
|
if (behaviorRef.current === "transfer") {
|
|
const sourcePath = fullPath ? getParentPath(fullPath) : pane.connection?.currentPath;
|
|
const sourceConnectionId = pane.connection?.id;
|
|
const fileData = [{
|
|
name: entry.name,
|
|
isDirectory: isDir,
|
|
sourceConnectionId,
|
|
sourcePath,
|
|
}];
|
|
sftpRef.current.startTransfer(fileData, "right", "left", {
|
|
sourceConnectionId,
|
|
sourcePath,
|
|
});
|
|
} else {
|
|
onOpenFileRight(entry, fullPath);
|
|
}
|
|
},
|
|
[sftpRef, onOpenFileRight, behaviorRef],
|
|
);
|
|
|
|
return {
|
|
permissionsState,
|
|
setPermissionsState,
|
|
showTextEditor,
|
|
setShowTextEditor,
|
|
textEditorTarget,
|
|
setTextEditorTarget,
|
|
textEditorContent,
|
|
setTextEditorContent,
|
|
loadingTextContent,
|
|
showFileOpenerDialog,
|
|
setShowFileOpenerDialog,
|
|
fileOpenerTarget,
|
|
setFileOpenerTarget,
|
|
handleSaveTextFile,
|
|
handleFileOpenerSelect,
|
|
handleSelectSystemApp,
|
|
onEditPermissionsLeft,
|
|
onEditPermissionsRight,
|
|
onOpenEntryLeft,
|
|
onOpenEntryRight,
|
|
onEditFileLeft,
|
|
onEditFileRight,
|
|
onOpenFileLeft,
|
|
onOpenFileRight,
|
|
onOpenFileWithLeft,
|
|
onOpenFileWithRight,
|
|
onDownloadFileLeft,
|
|
onDownloadFileRight,
|
|
onUploadExternalFilesLeft,
|
|
onUploadExternalFilesRight,
|
|
};
|
|
};
|