diff --git a/application/state/useSftpState.ts b/application/state/useSftpState.ts index dc33bb0f0..c5d4ecda4 100644 --- a/application/state/useSftpState.ts +++ b/application/state/useSftpState.ts @@ -110,6 +110,31 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { // SFTP session refs const sftpSessionsRef = useRef>(new Map()); // connectionId -> sftpId + // Directory listing cache (connectionId + path) + const DIR_CACHE_TTL_MS = 10_000; + const dirCacheRef = useRef< + Map + >(new Map()); + + // Navigation sequence per pane, used to ignore stale async results + const navSeqRef = useRef<{ left: number; right: number }>({ + left: 0, + right: 0, + }); + + const makeCacheKey = useCallback( + (connectionId: string, path: string) => `${connectionId}::${path}`, + [], + ); + + const clearCacheForConnection = useCallback((connectionId: string) => { + for (const key of dirCacheRef.current.keys()) { + if (key.startsWith(`${connectionId}::`)) { + dirCacheRef.current.delete(key); + } + } + }, []); + // Progress simulation refs const progressIntervalsRef = useRef>(new Map()); @@ -201,8 +226,12 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { if (pane.connection) { // Clean up stale session reference sftpSessionsRef.current.delete(pane.connection.id); + clearCacheForConnection(pane.connection.id); } + // Invalidate pending navigation/results for this side + navSeqRef.current[side] += 1; + // Check if we have host info to attempt reconnection const lastHost = lastConnectedHostRef.current[side]; if (lastHost && pane.files.length > 0 && !reconnectingRef.current[side]) { @@ -226,7 +255,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { }); } }, - [leftPane, rightPane], + [leftPane, rightPane, clearCacheForConnection], ); // Cleanup on unmount @@ -279,10 +308,17 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { const setPane = side === "left" ? setLeftPane : setRightPane; const connectionId = `${side}-${Date.now()}`; + // Invalidate any pending navigation for this side + navSeqRef.current[side] += 1; + const connectRequestId = navSeqRef.current[side]; + // Save host info for potential reconnection lastConnectedHostRef.current[side] = host; // First, disconnect any existing connection + if (currentPane.connection) { + clearCacheForConnection(currentPane.connection.id); + } if (currentPane.connection && !currentPane.connection.isLocal) { const oldSftpId = sftpSessionsRef.current.get( currentPane.connection.id, @@ -327,6 +363,11 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { try { const files = await listLocalFiles(homeDir); + if (navSeqRef.current[side] !== connectRequestId) return; + dirCacheRef.current.set(makeCacheKey(connectionId, homeDir), { + files, + timestamp: Date.now(), + }); // Clear reconnecting flag on success reconnectingRef.current[side] = false; setPane((prev) => ({ @@ -336,6 +377,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { reconnecting: false, })); } catch (err) { + if (navSeqRef.current[side] !== connectRequestId) return; reconnectingRef.current[side] = false; setPane((prev) => ({ ...prev, @@ -376,24 +418,57 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { sftpSessionsRef.current.set(connectionId, sftpId); - // Try to get home directory, default to / + // Try to get home directory, default to "/" let startPath = "/"; - try { - const homeFiles = await window.netcatty?.listSftp( - sftpId, - `/home/${credentials.username}`, - ); - if (homeFiles) startPath = `/home/${credentials.username}`; - } catch { - try { - const rootFiles = await window.netcatty?.listSftp(sftpId, "/root"); - if (rootFiles) startPath = "/root"; - } catch { - // Fallback path not available, use default + const statSftp = window.netcatty?.statSftp; + if (statSftp) { + const candidates: string[] = []; + if (credentials.username) { + candidates.push(`/home/${credentials.username}`); + } + candidates.push("/root"); + for (const candidate of candidates) { + try { + const stat = await statSftp(sftpId, candidate); + if (stat?.type === "directory") { + startPath = candidate; + break; + } + } catch { + // Ignore missing/permission errors + } + } + } else { + if (credentials.username) { + try { + const homeFiles = await window.netcatty?.listSftp( + sftpId, + `/home/${credentials.username}`, + ); + if (homeFiles) startPath = `/home/${credentials.username}`; + } catch { + // Fall through to /root check + } + } + if (startPath === "/") { + try { + const rootFiles = await window.netcatty?.listSftp( + sftpId, + "/root", + ); + if (rootFiles) startPath = "/root"; + } catch { + // Fallback path not available, use default + } } } const files = await listRemoteFiles(sftpId, startPath); + if (navSeqRef.current[side] !== connectRequestId) return; + dirCacheRef.current.set(makeCacheKey(connectionId, startPath), { + files, + timestamp: Date.now(), + }); // Clear reconnecting flag on success reconnectingRef.current[side] = false; @@ -413,6 +488,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { reconnecting: false, })); } catch (err) { + if (navSeqRef.current[side] !== connectRequestId) return; reconnectingRef.current[side] = false; setPane((prev) => ({ ...prev, @@ -432,7 +508,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { } }, // eslint-disable-next-line react-hooks/exhaustive-deps -- listLocalFiles is intentionally omitted to prevent infinite loops - [getHostCredentials, leftPane, rightPane], + [getHostCredentials, leftPane, rightPane, clearCacheForConnection], ); // Auto-connect left pane to local filesystem on first mount @@ -473,6 +549,13 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { const pane = side === "left" ? leftPane : rightPane; const setPane = side === "left" ? setLeftPane : setRightPane; + // Invalidate any pending navigation for this side + navSeqRef.current[side] += 1; + + if (pane.connection) { + clearCacheForConnection(pane.connection.id); + } + // Clear reconnection state reconnectingRef.current[side] = false; lastConnectedHostRef.current[side] = null; @@ -499,7 +582,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { filter: "", }); }, - [leftPane, rightPane], + [leftPane, rightPane, clearCacheForConnection], ); // Mock local file data for development (when backend is not available) @@ -992,12 +1075,40 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { // Navigate to path const navigateTo = useCallback( - async (side: "left" | "right", path: string) => { + async ( + side: "left" | "right", + path: string, + options?: { force?: boolean }, + ) => { const pane = side === "left" ? leftPane : rightPane; const setPane = side === "left" ? setLeftPane : setRightPane; if (!pane.connection) return; + const requestId = ++navSeqRef.current[side]; + const cacheKey = makeCacheKey(pane.connection.id, path); + const cached = options?.force + ? undefined + : dirCacheRef.current.get(cacheKey); + + if ( + cached && + Date.now() - cached.timestamp < DIR_CACHE_TTL_MS && + cached.files + ) { + setPane((prev) => ({ + ...prev, + connection: prev.connection + ? { ...prev.connection, currentPath: path } + : null, + files: cached.files, + loading: false, + error: null, + selectedFiles: new Set(), + })); + return; + } + setPane((prev) => ({ ...prev, loading: true, error: null })); try { @@ -1009,6 +1120,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { const sftpId = sftpSessionsRef.current.get(pane.connection.id); if (!sftpId) { // Session lost - clear connection state + clearCacheForConnection(pane.connection.id); setPane({ connection: null, files: [], @@ -1024,16 +1136,10 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { try { files = await listRemoteFiles(sftpId, path); } catch (err) { - // Check if it's a session error - const errorMsg = - err instanceof Error ? err.message : "Unknown error"; - if ( - errorMsg.includes("session") || - errorMsg.includes("not found") || - errorMsg.includes("closed") - ) { + if (isSessionError(err)) { // Clean up stale session reference sftpSessionsRef.current.delete(pane.connection.id); + clearCacheForConnection(pane.connection.id); setPane({ connection: null, files: [], @@ -1045,10 +1151,17 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { }); return; } - throw err; + throw err as Error; } } + if (navSeqRef.current[side] !== requestId) return; + + dirCacheRef.current.set(cacheKey, { + files, + timestamp: Date.now(), + }); + setPane((prev) => ({ ...prev, connection: prev.connection @@ -1059,6 +1172,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { selectedFiles: new Set(), })); } catch (err) { + if (navSeqRef.current[side] !== requestId) return; setPane((prev) => ({ ...prev, error: @@ -1068,7 +1182,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { } }, // eslint-disable-next-line react-hooks/exhaustive-deps -- listLocalFiles is intentionally omitted to prevent infinite loops - [leftPane, rightPane], + [leftPane, rightPane, makeCacheKey, clearCacheForConnection], ); // Refresh current directory @@ -1076,7 +1190,7 @@ export const useSftpState = (hosts: Host[], keys: SSHKey[]) => { async (side: "left" | "right") => { const pane = side === "left" ? leftPane : rightPane; if (pane.connection) { - await navigateTo(side, pane.connection.currentPath); + await navigateTo(side, pane.connection.currentPath, { force: true }); } }, [leftPane, rightPane, navigateTo], diff --git a/components/SFTPModal.tsx b/components/SFTPModal.tsx index 23a277fb4..f93e53878 100644 --- a/components/SFTPModal.tsx +++ b/components/SFTPModal.tsx @@ -268,6 +268,13 @@ const SFTPModal: React.FC = ({ const navigatingRef = useRef(false); const lastSelectedIndexRef = useRef(null); + // Directory listing cache + load sequence to avoid stale updates + const DIR_CACHE_TTL_MS = 10_000; + const dirCacheRef = useRef< + Map + >(new Map()); + const loadSeqRef = useRef(0); + // Sorting state const [sortField, setSortField] = useState("name"); const [sortOrder, setSortOrder] = useState("asc"); @@ -290,7 +297,7 @@ const SFTPModal: React.FC = ({ const [editingPathValue, setEditingPathValue] = useState(""); const pathInputRef = useRef(null); - const ensureSftp = async () => { + const ensureSftp = useCallback(async () => { if (sftpIdRef.current) return sftpIdRef.current; if (!window.netcatty?.openSftp) throw new Error("SFTP bridge unavailable"); const sftpId = await window.netcatty.openSftp({ @@ -303,25 +310,60 @@ const SFTPModal: React.FC = ({ }); sftpIdRef.current = sftpId; return sftpId; - }; + }, [ + host.id, + credentials.hostname, + credentials.username, + credentials.port, + credentials.password, + credentials.privateKey, + ]); - const loadFiles = useCallback(async (path: string) => { - try { - setError(null); - const sftpId = await ensureSftp(); - setLoading(true); - const list = await window.netcatty.listSftp(sftpId, path); - setFiles(list); - setSelectedFiles(new Set()); - } catch (e) { - console.error("Failed to load files", e); - setError(e instanceof Error ? e.message : "Failed to load directory"); - setFiles([]); - } finally { - setLoading(false); - } - // eslint-disable-next-line react-hooks/exhaustive-deps -- ensureSftp is defined inline, not a dependency - }, []); + const loadFiles = useCallback( + async (path: string, options?: { force?: boolean }) => { + const requestId = ++loadSeqRef.current; + const cacheKey = `${host.id}::${path}`; + const cached = options?.force + ? undefined + : dirCacheRef.current.get(cacheKey); + + if ( + cached && + Date.now() - cached.timestamp < DIR_CACHE_TTL_MS && + cached.files + ) { + setFiles(cached.files); + setSelectedFiles(new Set()); + setError(null); + setLoading(false); + return; + } + + try { + setError(null); + setLoading(true); + const sftpId = await ensureSftp(); + const list = await window.netcatty.listSftp(sftpId, path); + if (loadSeqRef.current !== requestId) return; + dirCacheRef.current.set(cacheKey, { + files: list, + timestamp: Date.now(), + }); + setFiles(list); + setSelectedFiles(new Set()); + } catch (e) { + if (loadSeqRef.current !== requestId) return; + console.error("Failed to load files", e); + setError(e instanceof Error ? e.message : "Failed to load directory"); + setFiles([]); + } finally { + if (loadSeqRef.current === requestId) { + setLoading(false); + } + } + }, + [ensureSftp, host.id], + ); const closeSftp = async () => { if (sftpIdRef.current && window.netcatty?.closeSftp) { @@ -349,6 +391,8 @@ const SFTPModal: React.FC = ({ } loadFiles(currentPath); } else { + // Invalidate any in-flight directory load + loadSeqRef.current += 1; closeSftp(); initializedRef.current = false; } @@ -548,7 +592,7 @@ const SFTPModal: React.FC = ({ } setUploading(false); - await loadFiles(currentPath); + await loadFiles(currentPath, { force: true }); // Auto-clear completed tasks after 3 seconds setTimeout(() => { @@ -566,7 +610,7 @@ const SFTPModal: React.FC = ({ if (window.netcatty.deleteSftp) { await window.netcatty.deleteSftp(sftpId, fullPath); } - await loadFiles(currentPath); + await loadFiles(currentPath, { force: true }); } catch (e) { setError(e instanceof Error ? e.message : "Delete failed"); } @@ -580,7 +624,7 @@ const SFTPModal: React.FC = ({ const fullPath = currentPath === "/" ? `/${folderName}` : `${currentPath}/${folderName}`; await window.netcatty.mkdirSftp(sftpId, fullPath); - await loadFiles(currentPath); + await loadFiles(currentPath, { force: true }); } catch (e) { setError(e instanceof Error ? e.message : "Failed to create folder"); } @@ -812,7 +856,7 @@ const SFTPModal: React.FC = ({ await window.netcatty.deleteSftp(sftpId, fullPath); } } - await loadFiles(currentPath); + await loadFiles(currentPath, { force: true }); setSelectedFiles(new Set()); } catch (e) { setError(e instanceof Error ? e.message : "Delete failed"); @@ -875,7 +919,7 @@ const SFTPModal: React.FC = ({ variant="ghost" size="icon" className="h-7 w-7" - onClick={() => loadFiles(currentPath)} + onClick={() => loadFiles(currentPath, { force: true })} > @@ -1161,7 +1205,9 @@ const SFTPModal: React.FC = ({ inputRef.current?.click()}> Upload files - loadFiles(currentPath)}> + loadFiles(currentPath, { force: true })} + > Refresh {selectedFiles.size > 0 && ( diff --git a/electron/bridges/localFsBridge.cjs b/electron/bridges/localFsBridge.cjs index 9b02f0097..fa2dc6e11 100644 --- a/electron/bridges/localFsBridge.cjs +++ b/electron/bridges/localFsBridge.cjs @@ -13,23 +13,45 @@ const os = require("node:os"); async function listLocalDir(event, payload) { const dirPath = payload.path; const entries = await fs.promises.readdir(dirPath, { withFileTypes: true }); - const result = []; - - for (const entry of entries) { - try { - const fullPath = path.join(dirPath, entry.name); - const stat = await fs.promises.stat(fullPath); - result.push({ - name: entry.name, - type: entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "file", - size: `${stat.size} bytes`, - lastModified: stat.mtime.toISOString(), - }); - } catch (err) { - console.warn(`Could not stat ${entry.name}:`, err.message); + + // Stat entries in parallel with a small concurrency limit. + // Serial stats can be very slow on Windows for large dirs. + const CONCURRENCY = 32; + const result = new Array(entries.length); + let cursor = 0; + + const worker = async () => { + while (true) { + const i = cursor++; + if (i >= entries.length) return; + const entry = entries[i]; + try { + const fullPath = path.join(dirPath, entry.name); + const stat = await fs.promises.stat(fullPath); + result[i] = { + name: entry.name, + type: entry.isDirectory() + ? "directory" + : entry.isSymbolicLink() + ? "symlink" + : "file", + size: `${stat.size} bytes`, + lastModified: stat.mtime.toISOString(), + }; + } catch (err) { + console.warn(`Could not stat ${entry.name}:`, err.message); + result[i] = null; + } } - } - return result; + }; + + const workers = Array.from( + { length: Math.min(CONCURRENCY, entries.length) }, + () => worker(), + ); + await Promise.all(workers); + + return result.filter(Boolean); } /**