From ec2f0d0bce8d15c2a135ae62bc8c670563f92ba3 Mon Sep 17 00:00:00 2001 From: nervi0s <56052473+nervi0s@users.noreply.github.com> Date: Fri, 18 Sep 2026 08:10:26 +0200 Subject: [PATCH] fix: support native file dragging from local filesystem panes (#3377) * fix: support native file dragging from local filesystem panes * fix: preserve symlink-aware paths during native file drag --- application/state/sftp/localFileDrag.test.ts | 174 +++++++++++++++++ application/state/sftp/localFileDrag.ts | 177 ++++++++++++++++++ components/sftp/SftpPaneTreeView.tsx | 29 +-- .../sftp/hooks/useSftpPaneDragAndSelect.ts | 43 +++-- .../sftp/localFileDrag.interaction.test.ts | 87 +++++++++ docs/local-file-drag-validation.md | 121 ++++++++++++ electron/bridges/localFileDragBridge.cjs | 119 ++++++++++++ electron/bridges/localFileDragBridge.test.cjs | 149 +++++++++++++++ electron/main/registerBridges.cjs | 5 + electron/preload/api.cjs | 2 + electron/preload/api.localFileDrag.test.cjs | 15 ++ package.json | 1 + scripts/local-file-drag.live.test.cjs | 131 +++++++++++++ types/global/netcatty-bridge-files.d.ts | 2 + 14 files changed, 1027 insertions(+), 28 deletions(-) create mode 100644 application/state/sftp/localFileDrag.test.ts create mode 100644 application/state/sftp/localFileDrag.ts create mode 100644 components/sftp/localFileDrag.interaction.test.ts create mode 100644 docs/local-file-drag-validation.md create mode 100644 electron/bridges/localFileDragBridge.cjs create mode 100644 electron/bridges/localFileDragBridge.test.cjs create mode 100644 electron/preload/api.localFileDrag.test.cjs create mode 100644 scripts/local-file-drag.live.test.cjs diff --git a/application/state/sftp/localFileDrag.test.ts b/application/state/sftp/localFileDrag.test.ts new file mode 100644 index 000000000..497a14372 --- /dev/null +++ b/application/state/sftp/localFileDrag.test.ts @@ -0,0 +1,174 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge'; +import { JSDOM } from 'jsdom'; +import { + startSftpFileDrag, takeLocalFileDragSources, getLocalFileDragSources, + clearLocalFileDrag, clearLocalFileDragForPane, localDragPathKey, localFileDragMoveEffect, +} from './localFileDrag'; + +function setup(t: test.TestContext) { + const dom = new JSDOM(''); + const previous = Object.getOwnPropertyDescriptor(globalThis, 'window'); + Object.defineProperty(globalThis, 'window', { value: dom.window, configurable: true }); + const calls: { requestId: string; paths: string[] }[] = []; + const cancels: string[] = []; + const errors: string[] = []; + const remote: unknown[] = []; + const bridge = { + startLocalFileDrag: async (payload) => { calls.push(payload); return { started: true }; }, + cancelLocalFileDrag: (id) => cancels.push(id), + getPathForFile: (file) => (file as unknown as { path: string }).path, + } as unknown as NetcattyBridge; + Object.defineProperty(window, "netcatty", { value: bridge, configurable: true }); + t.after(() => { + clearLocalFileDrag(); + dom.window.close(); + if (previous) Object.defineProperty(globalThis, 'window', previous); + else Reflect.deleteProperty(globalThis, 'window'); + }); + const transfer = (paths: string[] = []) => ({ + types: ['Files'], files: paths.map((path) => ({ path })), + effectAllowed: '', setData: (...args: string[]) => remote.push(args), + }) as unknown as DataTransfer; + const sources = [ + { name: 'certificate.txt', sourcePath: '/local', sourceConnectionId: 'local', isDirectory: false }, + { name: 'folder', sourcePath: '/another path', sourceConnectionId: 'local', isDirectory: true }, + ]; + let prevented = 0; + const start = (isLocal: boolean | undefined = true, selection = sources) => startSftpFileDrag({ + event: { dataTransfer: transfer(), preventDefault: () => { prevented++; } }, + paneId: 'pane', connection: { id: 'local', isLocal }, sources: selection, side: 'left', + onRemoteDrag: (...args) => remote.push(args), onError: (error) => errors.push(error), + }); + return { calls, cancels, errors, remote, transfer, sources, start, prevented: () => prevented, dom }; +} + +test('local multi-selection retains individual tree paths and never exports plain text', async (t) => { + const h = setup(t); + h.start(); + assert.equal(h.prevented(), 1); + assert.equal(h.remote.length, 0); + assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt', '/another path/folder']); + const payload = h.transfer([...h.calls[0].paths].reverse()); + assert.equal(getLocalFileDragSources(payload)?.length, 2); + assert.deepEqual(takeLocalFileDragSources(payload), h.sources.map((source) => ({ ...source, side: 'left' }))); + assert.equal(takeLocalFileDragSources(payload), null, 'a native gesture is consumed exactly once'); + assert.equal(getLocalFileDragSources(payload), null); +}); + +test('native paths retain symlink-parent segments and match the returning internal drop', (t) => { + const h = setup(t); + const sources = [{ ...h.sources[0], sourcePath: '/local/link/.././folder' }]; + h.start(true, sources); + assert.deepEqual(h.calls[0].paths, ['/local/link/.././folder/certificate.txt']); + const payload = h.transfer(h.calls[0].paths); + assert.deepEqual(takeLocalFileDragSources(payload), sources.map(source => ({ ...source, side: 'left' }))); + assert.equal(takeLocalFileDragSources(payload), null); +}); + +test('remote origin preserves HTML payload and callbacks, including absent isLocal', (t) => { + const h = setup(t); + h.start(false); + assert.equal(h.prevented(), 0); + assert.equal(h.calls.length, 0); + assert.deepEqual(h.remote, [['text/plain', 'certificate.txt\nfolder'], [h.sources, 'left']]); + startSftpFileDrag({ event: { dataTransfer: h.transfer(), preventDefault: () => assert.fail('remote drag canceled') }, + paneId: 'remote', connection: { id: 'remote' }, sources: h.sources, side: 'right', + onRemoteDrag: () => {}, onError: assert.fail }); + assert.equal(h.calls.length, 0); +}); + +test('unrelated external files cannot reuse a previous local gesture', (t) => { + const h = setup(t); + h.start(); + assert.equal(takeLocalFileDragSources(h.transfer(['/different/certificate.txt'])), null); + assert.equal(getLocalFileDragSources(h.transfer()), null); + h.start(); + assert.equal(takeLocalFileDragSources(h.transfer(['/local/certificate.txt'])), null, 'partial selection is not an internal transfer'); +}); + +test('local failure cancels without text fallback and stale async errors cannot clear a newer gesture', async (t) => { + const h = setup(t); + let reject!: (error: Error) => void; + netcattyBridge.require().startLocalFileDrag = () => new Promise((_resolve, rejectPromise) => { reject = rejectPromise; }); + h.start(); + const oldReject = reject; + h.start(); + oldReject(new Error('obsolete')); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(h.errors.length, 0); + assert.ok(getLocalFileDragSources(h.transfer())); + reject(new Error('file disappeared')); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(h.errors, ['file disappeared']); + assert.equal(getLocalFileDragSources(h.transfer()), null); + assert.equal(h.remote.length, 0); +}); + +test('native state is cleared on physical cancellation, external completion, connection disposal and new gestures', async (t) => { + const h = setup(t); + for (const event of [new h.dom.window.KeyboardEvent('keydown', { key: 'Escape' }), + new h.dom.window.MouseEvent('mousemove', { buttons: 0 }), new h.dom.window.MouseEvent('mousedown'), + new h.dom.window.Event('blur'), new h.dom.window.Event('pagehide')]) { + h.start(); + await Promise.resolve(); + window.dispatchEvent(event); + assert.equal(getLocalFileDragSources(h.transfer()), null, event.type); + } + h.start(); + clearLocalFileDragForPane('another-pane'); + assert.ok(getLocalFileDragSources(h.transfer())); + clearLocalFileDragForPane('pane'); + assert.equal(getLocalFileDragSources(h.transfer()), null); + h.start(); + h.start(false); + assert.equal(getLocalFileDragSources(h.transfer()), null); +}); + +test('invalid local selections and missing bridge are rejected; parent entry is excluded', (t) => { + const h = setup(t); + h.start(true, [{ ...h.sources[0], name: '..' }]); + assert.equal(h.calls.length, 0); + h.start(true, [{ ...h.sources[0], sourceConnectionId: 'remote' }]); + assert.equal(h.calls.length, 0); + h.start(true, [h.sources[0], { ...h.sources[0], name: '..' }]); + assert.deepEqual(h.calls[0].paths, ['/local/certificate.txt']); + netcattyBridge.require().startLocalFileDrag = undefined; + h.start(); + assert.equal(h.errors.length, 3); + assert.equal(h.remote.length, 0); +}); + +test('path matching preserves POSIX whitespace, Unicode and backslashes, and accepts Windows separators', () => { + assert.equal(localDragPathKey('C:\\Users\\david\\certificate.pem'), 'C:/Users/david/certificate.pem'); + assert.equal(localDragPathKey('\\\\server\\share\\folder'), '//server/share/folder'); + assert.equal(localDragPathKey('/local/é \\name '), '/local/é \\name '); + assert.notEqual(localDragPathKey('/local/A'), localDragPathKey('/local/a')); +}); + + +test('local move accepts the copy-only native transport on Windows/Linux without changing the operation', () => { + assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyLink' }), 'copy'); + assert.equal(localFileDragMoveEffect({ effectAllowed: 'copy' }), 'copy'); + assert.equal(localFileDragMoveEffect({ effectAllowed: 'all' }), 'move'); + assert.equal(localFileDragMoveEffect({ effectAllowed: 'copyMove' }), 'move'); +}); + +test('native drop cleanup survives the browser microtask checkpoint before React receives the drop', async (t) => { + const h = setup(t); + h.start(); + window.dispatchEvent(new h.dom.window.Event('drop')); + // Unlike dispatchEvent in jsdom, native browser events can drain microtasks + // after the window capture callback, before the React root bubble callback. + await Promise.resolve(); + assert.ok(getLocalFileDragSources(h.transfer()), 'capture must not erase native identity before React handles drop'); + assert.deepEqual(takeLocalFileDragSources(h.transfer(h.calls[0].paths)), h.sources.map(source => ({ ...source, side: 'left' }))); + await new Promise(resolve => setTimeout(resolve, 5)); + assert.equal(getLocalFileDragSources(h.transfer()), null); + + h.start(); + window.dispatchEvent(new h.dom.window.Event('drop')); + await new Promise(resolve => setTimeout(resolve, 5)); + assert.equal(getLocalFileDragSources(h.transfer()), null, 'unhandled drops also release the gesture'); +}); diff --git a/application/state/sftp/localFileDrag.ts b/application/state/sftp/localFileDrag.ts new file mode 100644 index 000000000..b8abe285c --- /dev/null +++ b/application/state/sftp/localFileDrag.ts @@ -0,0 +1,177 @@ +import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; +import { joinPath } from "./utils"; + +export interface LocalDragSource { + name: string; + isDirectory: boolean; + sourcePath?: string; + sourceConnectionId?: string; + targetPath?: string; + side: "left" | "right"; +} + +interface DragSession { + requestId: string; + paneId: string; + connectionId: string; + paths: string[]; + sources: LocalDragSource[]; + started?: boolean; +} + +// Windows separators can differ between the SFTP UI and Electron webUtils. +// POSIX backslashes, whitespace, and case must remain significant. +export function localDragPathKey(value: string): string { + if (/^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value)) { + return value.replace(/\\/g, "/").replace(/\/$/, ""); + } + return value.length > 1 ? value.replace(/\/$/, "") : value; +} + +class LocalFileDragState { + session: DragSession | null = null; + + clear(requestId?: string) { + if (!requestId || this.session?.requestId === requestId) this.session = null; + } + + take(paths: string[]): LocalDragSource[] | null { + const session = this.session; + this.clear(); + if (!session || paths.length === 0 || paths.some((path) => !path)) return null; + const expected = new Set(session.paths.map(localDragPathKey)); + const actual = new Set(paths.map(localDragPathKey)); + if (expected.size !== actual.size || [...expected].some((path) => !actual.has(path))) return null; + return session.sources; + } +} + +const state = new LocalFileDragState(); +let detach: (() => void) | undefined; + +export function clearLocalFileDrag(requestId?: string) { + if (requestId && state.session?.requestId !== requestId) return; + const previous = state.session; + state.clear(); + detach?.(); + detach = undefined; + if (previous) netcattyBridge.get()?.cancelLocalFileDrag?.(previous.requestId); +} + +export function clearLocalFileDragForPane(paneId: string) { + if (state.session?.paneId === paneId) clearLocalFileDrag(); +} + +function observeGestureEnd() { + let dropCleanupTimer: ReturnType | undefined; + // Electron has no cross-platform native-drag completion callback. A canceled + // HTML drag's dragend is not a native completion signal. Clear on drop and + // on the next physical input/focus transition, including Escape and returning + // after a drop outside the window. Never retain state into a new gesture. + const clear = () => clearLocalFileDrag(); + const key = (event: KeyboardEvent) => { if (event.key === "Escape") clear(); }; + const move = (event: MouseEvent) => { if (state.session?.started && event.buttons === 0) clear(); }; + const drop = () => { + const requestId = state.session?.requestId; + // Native event dispatch can run microtasks BETWEEN capture and React's + // bubble listener. Use a macrotask so the row/pane can consume the gesture. + dropCleanupTimer = setTimeout(() => { if (requestId) clearLocalFileDrag(requestId); }, 0); + }; + // preventDefault() on dragstart produces a synthetic mouseup in Chromium. + // It must not cancel the native handoff. Observe later input instead. + window.addEventListener("mousedown", clear, true); + window.addEventListener("mousemove", move, true); + window.addEventListener("keydown", key, true); + window.addEventListener("blur", clear); + window.addEventListener("pagehide", clear); + window.addEventListener("drop", drop, true); + detach = () => { + if (dropCleanupTimer !== undefined) clearTimeout(dropCleanupTimer); + window.removeEventListener("mousedown", clear, true); + window.removeEventListener("mousemove", move, true); + window.removeEventListener("keydown", key, true); + window.removeEventListener("blur", clear); + window.removeEventListener("pagehide", clear); + window.removeEventListener("drop", drop, true); + }; +} + +type DragEventLike = Pick; + +export function startSftpFileDrag({ event, paneId, connection, sources, side, onRemoteDrag, onError }: { + event: DragEventLike; + paneId: string; + connection?: { id: string; isLocal?: boolean } | null; + sources: Omit[]; + side: "left" | "right"; + onRemoteDrag: (sources: Omit[], side: "left" | "right") => void; + onError: (message: string) => void; +}) { + clearLocalFileDrag(); + if (connection?.isLocal !== true) { + event.dataTransfer!.effectAllowed = "copyMove"; + event.dataTransfer!.setData("text/plain", sources.map((file) => file.name).join("\n")); + onRemoteDrag(sources, side); + return; + } + event.preventDefault(); + const bridge = netcattyBridge.get(); + if (!bridge?.startLocalFileDrag) { + onError("Native file drag is unavailable. Restart Netcatty after updating."); + return; + } + const files = sources.filter((source) => source.name !== ".."); + if (!files.length || files.some((file) => !file.sourcePath || file.sourceConnectionId !== connection.id)) { + onError("The local file selection is no longer available."); + return; + } + const requestId = crypto.randomUUID(); + const paths = [...new Set(files.map((file) => joinPath(file.sourcePath!, file.name)))]; + state.session = { requestId, paneId, connectionId: connection.id, paths, sources: files.map((file) => ({ ...file, side })) }; + observeGestureEnd(); + // Send during dragstart, without awaiting in the renderer. Do not interpret + // the reply as a completed transfer or use it to clear an active gesture. + try { + void bridge.startLocalFileDrag({ requestId, paths }).then((result) => { + if (result.started && state.session?.requestId === requestId) state.session.started = true; + if (!result.started && state.session?.requestId === requestId) { + clearLocalFileDrag(requestId); + if (result.error) onError(result.error); + } + }).catch((error: unknown) => { + if (state.session?.requestId !== requestId) return; + clearLocalFileDrag(requestId); + onError(error instanceof Error ? error.message : "Unable to drag local files"); + }); + } catch (error) { + clearLocalFileDrag(requestId); + onError(error instanceof Error ? error.message : "Unable to drag local files"); + } +} + +export function getLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null { + return dataTransfer.types.includes("Files") ? state.session?.sources ?? null : null; +} + +export function localFileDragMoveEffect(dataTransfer: Pick): "copy" | "move" { + // Electron's Windows/Linux native source advertises COPY | LINK, not MOVE. + // Negotiate an allowed transport effect; our existing same-pane callback is + // responsible for the actual local move (the OS must not delete originals). + return ["all", "copyMove", "linkMove", "move"].includes(dataTransfer.effectAllowed) ? "move" : "copy"; +} + +export function takeLocalFileDragSources(dataTransfer: DataTransfer): LocalDragSource[] | null { + if (!state.session) return null; + const bridge = netcattyBridge.get(); + const session = state.session; + try { + return state.take(Array.from(dataTransfer.files).map((file) => bridge?.getPathForFile?.(file) ?? "")); + } catch { + state.clear(); + return null; + } finally { + detach?.(); + detach = undefined; + bridge?.cancelLocalFileDrag?.(session.requestId); + } +} diff --git a/components/sftp/SftpPaneTreeView.tsx b/components/sftp/SftpPaneTreeView.tsx index 8c77ba037..195fdc3cd 100644 --- a/components/sftp/SftpPaneTreeView.tsx +++ b/components/sftp/SftpPaneTreeView.tsx @@ -14,6 +14,8 @@ import type { SftpTransferSource } from './SftpContext'; import type { SftpPaneTreeViewProps } from './SftpPaneTreeView.types'; import { sftpTreeSelectionStore, useSftpTreeSelectionState } from '../../application/state/sftp/sftpTreeSelectionStore'; import { sftpKeyboardSelectionStore, sftpTreeEnterStore } from './hooks/useSftpKeyboardShortcuts'; +import { startSftpFileDrag, localFileDragMoveEffect, getLocalFileDragSources, takeLocalFileDragSources, type LocalDragSource } from '../../application/state/sftp/localFileDrag'; +import { toast } from '../ui/toast'; import { useI18n } from '../../application/i18n/I18nProvider'; import { SftpColumnMenuItems } from './SftpColumnMenuItems'; import { @@ -686,10 +688,11 @@ export const SftpPaneTreeView = React.memo(({ sourcePath: getParentPath(entryPath), }); } - e.dataTransfer.effectAllowed = 'copyMove'; - e.dataTransfer.setData('text/plain', files.map((f) => f.name).join('\n')); - onDragStartRef.current(files, sideRef.current); - }, [getActionPaths, pane.connection?.id, toTransferSources]); + startSftpFileDrag({ event: e, paneId: pane.id, connection: pane.connection, + sources: files, side: sideRef.current, onRemoteDrag: onDragStartRef.current, + onError: (message) => toast.error(message, "SFTP"), + }); + }, [getActionPaths, pane.id, pane.connection, toTransferSources]); const stableOnDragEnd = useCallback(() => onDragEndRef.current(), []); const applyLocalMoveMutation = useCallback(( sourceParentPaths: string[], @@ -793,8 +796,7 @@ export const SftpPaneTreeView = React.memo(({ setIsMoving(false); } }, [moveToPath, isMoving, executeMoveAction, moveTargetPaths]); - const getSamePaneDragPaths = useCallback((): string[] | null => { - const dragged = draggedFilesRef.current; + const getSamePaneDragPaths = useCallback((dragged: LocalDragSource[] | null): string[] | null => { if (!dragged || dragged.length === 0) return null; if (dragged[0]?.side !== sideRef.current) return null; const currentConnectionId = pane.connection?.id; @@ -807,15 +809,16 @@ export const SftpPaneTreeView = React.memo(({ const entry = entryByPathRef.current.get(entryPath); if (!entry) return; const isDir = isNavigableDirectory(entry); - const samePaneDragPaths = getSamePaneDragPaths(); + const sources = draggedFilesRef.current ?? getLocalFileDragSources(e.dataTransfer); + const samePaneDragPaths = getSamePaneDragPaths(sources); if (samePaneDragPaths && isDir && entry.name !== '..') { e.preventDefault(); e.stopPropagation(); - e.dataTransfer.dropEffect = 'move'; + e.dataTransfer.dropEffect = draggedFilesRef.current ? 'move' : localFileDragMoveEffect(e.dataTransfer); setDragOverNodePath(entryPath); return; } - const isInternalDrag = draggedFilesRef.current && draggedFilesRef.current[0]?.side !== sideRef.current; + const isInternalDrag = sources && sources[0]?.side !== sideRef.current; if (isInternalDrag && isDir && entry.name !== '..') { e.preventDefault(); e.stopPropagation(); @@ -835,7 +838,9 @@ export const SftpPaneTreeView = React.memo(({ const entry = entryByPathRef.current.get(entryPath); if (!entry) return; const isDir = isNavigableDirectory(entry); - const samePaneDragPaths = getSamePaneDragPaths(); + const sources = draggedFilesRef.current ?? (isDir && entry.name !== '..' + ? takeLocalFileDragSources(e.dataTransfer) : null); + const samePaneDragPaths = getSamePaneDragPaths(sources); if (samePaneDragPaths && isDir && entry.name !== '..') { e.preventDefault(); e.stopPropagation(); @@ -863,13 +868,13 @@ export const SftpPaneTreeView = React.memo(({ return; } const hasFiles = e.dataTransfer.types.includes('Files'); - const isInternalDrag = draggedFilesRef.current && draggedFilesRef.current[0]?.side !== sideRef.current; + const isInternalDrag = sources && sources[0]?.side !== sideRef.current; if (isInternalDrag && isDir && entry.name !== '..') { e.preventDefault(); e.stopPropagation(); setDragOverNodePath(null); onReceiveFromOtherPaneRef.current( - draggedFilesRef.current.map((file) => ({ ...file, targetPath: entryPath })), + sources!.map((file) => ({ ...file, targetPath: entryPath })), ); return; } diff --git a/components/sftp/hooks/useSftpPaneDragAndSelect.ts b/components/sftp/hooks/useSftpPaneDragAndSelect.ts index 07b0cd950..fe212f8e6 100644 --- a/components/sftp/hooks/useSftpPaneDragAndSelect.ts +++ b/components/sftp/hooks/useSftpPaneDragAndSelect.ts @@ -2,13 +2,16 @@ import React, { useCallback, useEffect, useRef, useState } from "react"; import type { SftpFileEntry } from "../../../types"; import type { SftpPaneCallbacks, SftpDragCallbacks, SftpTransferSource } from "../SftpContext"; import { isNavigableDirectory } from "../utils"; +import { toast } from "../../ui/toast"; +import { startSftpFileDrag, localFileDragMoveEffect, getLocalFileDragSources, takeLocalFileDragSources, clearLocalFileDragForPane, type LocalDragSource } from "../../../application/state/sftp/localFileDrag"; import { joinPath } from "../../../application/state/sftp/utils"; interface UseSftpPaneDragAndSelectParams { side: "left" | "right"; pane: { + id: string; selectedFiles: Set; - connection?: { currentPath: string; id: string } | null; + connection?: { currentPath: string; id: string; isLocal?: boolean } | null; }; sortedDisplayFiles: SftpFileEntry[]; draggedFiles: (SftpTransferSource & { side: "left" | "right" })[] | null; @@ -73,8 +76,10 @@ export const useSftpPaneDragAndSelect = ({ } }, [pane.selectedFiles.size]); - const getSamePaneDragPaths = useCallback((): string[] | null => { - const dragged = draggedFilesRef.current; + useEffect(() => () => clearLocalFileDragForPane(pane.id), + [pane.id, pane.connection?.id, pane.connection?.isLocal, pane.connection?.currentPath]); + + const getSamePaneDragPaths = useCallback((dragged: LocalDragSource[] | null): string[] | null => { if (!dragged || dragged.length === 0) return null; if (dragged[0]?.side !== side) return null; @@ -115,9 +120,10 @@ export const useSftpPaneDragAndSelect = ({ setIsDragOverPane(false); setDragOverEntry(null); - if (draggedFilesRef.current && draggedFilesRef.current.length > 0) { - if (draggedFilesRef.current[0]?.side !== side) { - onReceiveRef.current(draggedFilesRef.current); + const sources = draggedFilesRef.current ?? takeLocalFileDragSources(e.dataTransfer); + if (sources && sources.length > 0) { + if (sources[0]?.side !== side) { + onReceiveRef.current(sources); } return; } @@ -153,26 +159,28 @@ export const useSftpPaneDragAndSelect = ({ side, }, ]; - e.dataTransfer.effectAllowed = "copyMove"; - e.dataTransfer.setData("text/plain", files.map((f) => f.name).join("\n")); - onDragStart(files, side); + startSftpFileDrag({ event: e, paneId: pane.id, connection: pane.connection, + sources: files, side, onRemoteDrag: onDragStart, + onError: (message) => toast.error(message, "SFTP"), + }); }, - [onDragStart, pane.connection?.currentPath, pane.connection?.id, side], + [onDragStart, pane.id, pane.connection, side], ); const handleEntryDragOver = useCallback( (entry: SftpFileEntry, e: React.DragEvent) => { - const samePaneDragPaths = getSamePaneDragPaths(); + const sources = draggedFilesRef.current ?? getLocalFileDragSources(e.dataTransfer); + const samePaneDragPaths = getSamePaneDragPaths(sources); if (samePaneDragPaths && isNavigableDirectory(entry) && entry.name !== "..") { e.preventDefault(); e.stopPropagation(); - e.dataTransfer.dropEffect = "move"; + e.dataTransfer.dropEffect = draggedFilesRef.current ? "move" : localFileDragMoveEffect(e.dataTransfer); setDragOverEntry(entry.name); return; } // Handle cross-pane internal drag - if (draggedFilesRef.current && draggedFilesRef.current[0]?.side !== side) { + if (sources && sources[0]?.side !== side) { if (isNavigableDirectory(entry) && entry.name !== "..") { e.preventDefault(); e.stopPropagation(); @@ -194,7 +202,10 @@ export const useSftpPaneDragAndSelect = ({ const handleEntryDrop = useCallback( async (entry: SftpFileEntry, e: React.DragEvent) => { - const samePaneDragPaths = getSamePaneDragPaths(); + // Let a non-directory drop bubble to the pane before consuming a native gesture. + const sources = draggedFilesRef.current ?? (isNavigableDirectory(entry) && entry.name !== ".." + ? takeLocalFileDragSources(e.dataTransfer) : null); + const samePaneDragPaths = getSamePaneDragPaths(sources); if (samePaneDragPaths && isNavigableDirectory(entry) && entry.name !== "..") { e.preventDefault(); e.stopPropagation(); @@ -210,7 +221,7 @@ export const useSftpPaneDragAndSelect = ({ } // Handle cross-pane internal drag - if (draggedFilesRef.current && draggedFilesRef.current[0]?.side !== side) { + if (sources && sources[0]?.side !== side) { if (isNavigableDirectory(entry) && entry.name !== "..") { e.preventDefault(); e.stopPropagation(); @@ -220,7 +231,7 @@ export const useSftpPaneDragAndSelect = ({ ? joinPath(pane.connection.currentPath, entry.name) : undefined; onReceiveRef.current( - draggedFilesRef.current.map((file) => ({ ...file, targetPath })), + sources.map((file) => ({ ...file, targetPath })), ); } return; diff --git a/components/sftp/localFileDrag.interaction.test.ts b/components/sftp/localFileDrag.interaction.test.ts new file mode 100644 index 000000000..b5256f7df --- /dev/null +++ b/components/sftp/localFileDrag.interaction.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { JSDOM } from 'jsdom'; +import { useSftpPaneDragAndSelect } from './hooks/useSftpPaneDragAndSelect'; +import { clearLocalFileDrag } from '../../application/state/sftp/localFileDrag'; +import type { SftpFileEntry } from '../../types'; + +test('list hook preserves local copy/move routing, remote HTML drag, selection and connection cleanup', async () => { + const dom = new JSDOM('
', { url: 'http://localhost' }); + const previous = new Map(); + for (const [name, value] of Object.entries({ window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true })) { + previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { configurable: true, value }); + } + const starts: { paths: string[] }[] = []; + Object.defineProperty(dom.window, 'netcatty', { value: { + startLocalFileDrag: async (payload: { paths: string[] }) => { starts.push(payload); return { started: true }; }, + cancelLocalFileDrag() {}, + getPathForFile: (file: { path: string }) => file.path, + }}); + const entries: SftpFileEntry[] = [ + { name: 'a.txt', type: 'file' }, { name: 'b.txt', type: 'file' }, { name: 'folder', type: 'directory' }, + ].map(entry => ({ ...entry, size: 0, sizeFormatted: '', lastModified: 0, lastModifiedFormatted: '' })) as SftpFileEntry[]; + const actions: { kind: string; args: unknown[] }[] = []; + const record = (kind: string) => (...args: unknown[]) => { actions.push({ kind, args }); }; + let left!: ReturnType; + let right!: ReturnType; + let remoteDrag: Parameters[0]['draggedFiles'] = null; + function Harness({ local = true, connectionId = 'left' }) { + const usePane = (side: 'left' | 'right') => useSftpPaneDragAndSelect({ + side, pane: { id: side, selectedFiles: new Set(['a.txt', 'folder']), + connection: { id: side === 'left' ? connectionId : 'right', currentPath: '/files', isLocal: side === 'right' || local } }, + sortedDisplayFiles: entries, draggedFiles: remoteDrag, + onDragStart: (files, origin) => { remoteDrag = files.map(file => ({ ...file, side: origin })); record('remote')(files); }, + onReceiveFromOtherPane: record('copy'), onMoveEntriesToPath: async (...args) => record('move')(...args), + onUploadExternalFiles: async () => record('external')(), onOpenEntry() {}, onRangeSelect() {}, onToggleSelection() {}, + }); + left = usePane('left'); right = usePane('right'); + return null; + } + const event = (paths: string[] = []) => ({ + preventDefault() {}, stopPropagation() {}, + dataTransfer: { types: paths.length ? ['Files'] : [], files: paths.map(path => ({ path })), items: paths.map(() => ({})), + effectAllowed: '', dropEffect: '', setData: record('text') }, + }) as unknown as React.DragEvent; + const root = createRoot(dom.window.document.getElementById('root')!); + try { + await act(async () => root.render(React.createElement(Harness))); + await act(async () => left.handleFileDragStart(entries[0], event())); + assert.deepEqual(starts.at(-1)?.paths, ['/files/a.txt', '/files/folder']); + await act(async () => right.handlePaneDrop(event(starts.at(-1)!.paths))); + assert.deepEqual(actions.map(a => a.kind), ['copy']); + assert.equal((actions[0].args[0] as unknown[]).length, 2); + + actions.length = 0; + await act(async () => left.handleFileDragStart(entries[1], event())); + assert.deepEqual(starts.at(-1)?.paths, ['/files/b.txt'], 'dragging an unselected row excludes the old selection'); + await act(async () => left.handleEntryDrop(entries[2], event(starts.at(-1)!.paths))); + assert.deepEqual(actions, [{ kind: 'move', args: [['/files/b.txt'], '/files/folder'] }]); + + actions.length = 0; + await act(async () => left.handleFileDragStart(entries[1], event())); + await act(async () => root.render(React.createElement(Harness, { connectionId: 'replacement' }))); + await act(async () => right.handlePaneDrop(event(['/files/b.txt']))); + assert.deepEqual(actions.map(a => a.kind), ['external'], 'connection replacement invalidates internal native identity'); + + actions.length = 0; + await act(async () => root.render(React.createElement(Harness, { local: false }))); + const before = starts.length; + await act(async () => left.handleFileDragStart(entries[1], event())); + assert.equal(starts.length, before, 'remote path never reaches native bridge'); + assert.deepEqual(actions.map(a => a.kind), ['text', 'remote']); + await act(async () => root.render(React.createElement(Harness, { local: false }))); + await act(async () => right.handlePaneDrop(event())); + assert.equal(actions.at(-1)?.kind, 'copy'); + } finally { + await act(async () => root.unmount()); + clearLocalFileDrag(); + dom.window.close(); + for (const [name, descriptor] of previous) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else Reflect.deleteProperty(globalThis, name); + } + } +}); diff --git a/docs/local-file-drag-validation.md b/docs/local-file-drag-validation.md new file mode 100644 index 000000000..fd8ba3ebd --- /dev/null +++ b/docs/local-file-drag-validation.md @@ -0,0 +1,121 @@ +# Local native file drag + +Local filesystem panes hand real files and folders to Electron's native drag API. +Remote SFTP panes retain their HTML drag payload and transfer callbacks. This +applies to both panes and the list and tree views; no SFTP download or temporary +copy is involved in the new drag path. + +## Boundaries + +- `isLocal === true` is required at the source. Native IPC accepts only the main + frame of a registered app-content window during an active left-button gesture. +- Metadata validation accepts existing files, directories, and valid symlinks, + preserving the link path. It rejects relative paths, Windows device paths, + broken links and special files. It does not read content or traverse folders. +- Absolute path spelling is passed unchanged to metadata validation and Electron. + Dot segments are not normalized: `link/../file` can identify a different file + from the lexically simplified path. Only identical path strings are deduplicated. +- Input tracking in the main process prevents asynchronous metadata validation + from starting a drag after mouse release, Escape, or a replacement gesture. +- Chromium can emit a synthetic `mouseup` when HTML `dragstart` is canceled. + Renderer cleanup must not treat this as completion of the native handoff. +- Drop cleanup runs in a timer, not a microtask: native event dispatch can drain + microtasks between window capture and React bubble handlers. +- Electron does not expose a portable native-drag completion callback. The + renderer consumes matching drops once and clears its identity on subsequent + physical input, Escape, focus loss, page exit, or source connection disposal. + A successful start reply is never treated as a completed transfer. +- Native drops returning to the source window must match every selected path + before using the existing internal copy/move callbacks. Other OS drops retain + the external-upload flow. Filesystem services and conflict handling are unchanged. +- Electron advertises COPY/LINK on Windows/Linux. The drop target negotiates an + allowed effect while the existing same-pane callback performs a local move; + Netcatty never requests an OS deletion of the source on external delivery. + +## Automated checks + +```sh +npm run lint +node --test --import tsx components/sftp/*.test.ts application/state/sftp/localFileDrag.test.ts electron/bridges/localFileDragBridge.test.cjs electron/preload/api.localFileDrag.test.cjs electron/bridges/registerBridgesTransferLimits.test.cjs +npm run build +``` + +The regression tests cover local selection, path matching, single delivery, +copy/move routing, remote HTML drag, connection replacement, cancellation, +invalid IPC senders, missing files, symlinks, Windows drives/UNC and native effects. + +## Interactive Electron check + +```sh +npm run test:local-file-drag:electron +``` + +The fixture uses the actual list hook, preload methods and main-process native +bridge. It creates disposable files and a destination directory under Netcatty's +own temp directory and uses a separate Electron profile. It never connects to an +SFTP server. Its copy/move callbacks **record intent**, rather than modifying files. + +Drag a file or folder to the blue native target: expect `NATIVE_DROP` with real +filesystem paths. Drag between panes: expect one `INTERNAL_COPY`. Drag a file onto +a folder in the same pane: expect one `INTERNAL_MOVE`. Toggle the source to remote: +its outgoing gesture must remain HTML text and its internal drop must still call +`INTERNAL_COPY`. Close the test window when finished. The fixture directory is +printed in the terminal and retained for inspecting copied files. + +## Manual acceptance matrix + +Run on macOS, Windows 11, and Linux using a desktop file manager and the full app: + +1. Drag single files, multiple files, folders and mixed selections from list and + tree views into the file manager. Compare names, content and folder structure; + verify no text clipping or lost originals. +2. Open a supported certificate/keystore by dropping it onto KeyStore Explorer, + comparing with the same file dragged from the desktop file manager. +3. Check local-to-local, local-to-SFTP and same-pane folder moves in the full app, + including nested tree entries, conflicts and cancellation. Check both sides. +4. Check unchanged remote-to-local and remote-to-remote drags against a test host. +5. Cancel with Escape, release over an invalid target, change/close the source + connection, then drag another file from the OS. No previous selection may be + transferred. Repeat quick gestures and files removed just before dragging. + +## Validation recorded during implementation (2026-09-12) + +- Lint and production build passed; 167 targeted/regression tests passed. +- Full `npm test` passed on macOS: 11,693 tests, 11,665 passed, 28 skipped, + zero failures (143 seconds), including the npm pretest checks, with the agent's + `LC_ALL=C.UTF-8` environment. The initial + sandboxed run hit `EPERM` when opening local test servers; the complete rerun + outside that sandbox passed. +- A subsequent user run reported ten failures. Eight server-stats failures were + reproduced with `LC_ALL=es_ES.UTF-8` in both the working tree and unmodified + HEAD `8be56264fc6a3b93aacdc91277a11d0753c822f4`: the 26 `getServerStats` + tests give 18 passes / 8 failures in Spanish and 26 passes / 0 failures with + `LC_ALL=C` in both copies. Locale-sensitive awk decimal commas conflict with + the stats record delimiter. This is a pre-existing locale bug, not a drag regression. +- The other two reported failures involve interactive zsh (`TTY read` I/O error + and missing wrapper output). Targeted reruns pass; their cause remains unconfirmed. + Neither these tests nor their shell implementation was changed by this work. +- Full TypeScript checking reports 731 diagnostics both before and after this + change (verified against a separate HEAD snapshot; no added diagnostics). +- Real Electron on macOS produced native file and folder receipts. Automated + pointer gestures were intermittent. Manual receipts exposed premature drop + cleanup, now corrected and regression-tested. A final native internal-copy/move + retest, the full macOS manual matrix, Finder copies and KeyStore Explorer + interoperability still require desktop verification. +- Windows 11 and Linux desktop runtime checks were completed successfully by + the contributor, as reported after implementation. These are manual validation + results supplied by the contributor; the agent did not run those desktop checks. + +## PR review follow-up: symlink-aware paths + +The review identified that lexical normalization could replace the selected +file when a local path contains a symlink followed by `..`. The regression was +reproduced with a real filesystem symlink and two distinct files, then corrected +by preserving the original absolute path for both `stat` and `startDrag`. +The tests also reject a missing selected file even when its normalized path +names an existing file, preserve POSIX/Windows/UNC path spelling, and check +renderer matching for a returning path with dot segments. + +The affected/regression suite passed 188 tests after this correction. These are +automated checks; the new symlink-parent case has not been retested through a +physical desktop drag. diff --git a/electron/bridges/localFileDragBridge.cjs b/electron/bridges/localFileDragBridge.cjs new file mode 100644 index 000000000..52d6db066 --- /dev/null +++ b/electron/bridges/localFileDragBridge.cjs @@ -0,0 +1,119 @@ +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); + +function validateDragPayload(payload, pathApi = path) { + if (!payload || typeof payload.requestId !== "string" || !payload.requestId + || payload.requestId.length > 128 || !Array.isArray(payload.paths) + || payload.paths.length === 0 || payload.paths.length > 4096) { + throw new Error("Invalid local file drag request"); + } + const paths = payload.paths.map((value) => { + if (typeof value !== "string" || value.includes("\0") || !pathApi.isAbsolute(value)) { + throw new Error("Drag paths must be absolute filesystem paths"); + } + if (pathApi.sep === "\\" && (!/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(value) + || /^[\\/]{2}[?.][\\/]/.test(value))) { + throw new Error("Drag paths must identify a drive or a network share"); + } + // Preserve the exact path for both stat and startDrag. Lexically collapsing + // link/.. can select a different file because the filesystem follows the + // symlink before traversing its parent. Deduplicate only identical strings. + return value; + }); + return [...new Set(paths)]; +} + +function createLocalFileDragHandlers({ getWindows, nativeImage, getGesture, stat = fs.promises.stat }) { + const pending = new Map(); + let icon; + const authorized = (event) => { + const sender = event?.sender; + return !!sender && !sender.isDestroyed() + && !!event.senderFrame && event.senderFrame === sender.mainFrame + && getWindows().some((win) => !win.isDestroyed() && win.webContents === sender); + }; + const cancel = (event, { requestId } = {}) => { + if (!authorized(event)) return; + if (pending.get(event.sender)?.requestId === requestId) pending.delete(event.sender); + }; + const start = async (event, payload) => { + let request; + try { + if (!authorized(event)) throw new Error("Unauthorized local file drag sender"); + const gesture = getGesture(event.sender); + if (!gesture) throw new Error("Start a new mouse drag to share local files"); + const paths = validateDragPayload(payload); + request = { requestId: payload.requestId }; + pending.set(event.sender, request); + // Only metadata is inspected, including the target of a symlink. No + // recursive traversal, content reads, temporary copies, or SFTP calls. + for (const filePath of paths) { + const info = await stat(filePath); + if (!info.isFile() && !info.isDirectory()) { + throw new Error("Only files and folders can be dragged"); + } + if (pending.get(event.sender) !== request) return { started: false }; + if (getGesture(event.sender) !== gesture) { + throw new Error("The drag ended before the files were ready. Please drag again."); + } + } + if (!authorized(event) || pending.get(event.sender) !== request) return { started: false }; + // Native input is tracked in the main process, not via the synthetic + // mouseup Chromium emits when the renderer cancels its HTML drag. + if (getGesture(event.sender) !== gesture) { + throw new Error("The drag ended before the files were ready. Please drag again."); + } + if (!icon) { + const pixels = Buffer.alloc(16 * 16 * 4); + for (let i = 0; i < pixels.length; i += 4) { + pixels[i] = 220; + pixels[i + 1] = 140; + pixels[i + 2] = 40; + pixels[i + 3] = 255; + } + icon = nativeImage.createFromBitmap(pixels, { width: 16, height: 16 }); + } + if (icon.isEmpty()) throw new Error("File drag icon is unavailable"); + event.sender.startDrag({ files: paths, icon }); + // startDrag returning does not mean the destination accepted the files. + return { started: true }; + } catch (error) { + return { started: false, error: error instanceof Error ? error.message : "Unable to drag files" }; + } finally { + if (request && pending.get(event.sender) === request) pending.delete(event.sender); + } + }; + return { start, cancel }; +} + +function createGestureTracker() { + const gestures = new WeakMap(); + const attached = new WeakSet(); + const attach = (sender) => { + if (!sender || attached.has(sender)) return; + attached.add(sender); + sender.on("before-mouse-event", (_event, input) => { + if (input.button !== "left") return; + if (input.type === "mouseDown") gestures.set(sender, {}); + else if (input.type === "mouseUp") gestures.delete(sender); + }); + sender.on("before-input-event", (_event, input) => { + if (input.key === "Escape") gestures.delete(sender); + }); + sender.on("destroyed", () => gestures.delete(sender)); + }; + return { attach, getGesture: (sender) => gestures.get(sender) }; +} + +function registerHandlers(ipcMain, dependencies) { + const tracker = createGestureTracker(); + for (const win of dependencies.getWindows()) tracker.attach(win.webContents); + dependencies.app?.on?.("web-contents-created", (_event, sender) => tracker.attach(sender)); + const handlers = createLocalFileDragHandlers({ ...dependencies, getGesture: tracker.getGesture }); + ipcMain.handle("netcatty:local:drag-start", handlers.start); + ipcMain.on("netcatty:local:drag-cancel", handlers.cancel); +} + +module.exports = { registerHandlers, createLocalFileDragHandlers, createGestureTracker, validateDragPayload }; diff --git a/electron/bridges/localFileDragBridge.test.cjs b/electron/bridges/localFileDragBridge.test.cjs new file mode 100644 index 000000000..80adf614e --- /dev/null +++ b/electron/bridges/localFileDragBridge.test.cjs @@ -0,0 +1,149 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const fs = require("node:fs"); +const path = require("node:path"); +const { validateDragPayload, createLocalFileDragHandlers, createGestureTracker } = require("./localFileDragBridge.cjs"); +const tempDirBridge = require("./tempDirBridge.cjs"); + +function harness(options = {}) { + const calls = []; + const sender = { mainFrame: {}, isDestroyed: () => false, startDrag: (item) => calls.push(item) }; + const win = { isDestroyed: () => false, webContents: sender }; + const event = { sender, senderFrame: sender.mainFrame }; + const icon = { isEmpty: () => false }; + const gesture = {}; + const handlers = createLocalFileDragHandlers({ + getWindows: () => [win], getGesture: () => gesture, nativeImage: { createFromBitmap: () => icon }, ...options, + }); + return { calls, event, handlers, icon }; +} + +test("drag paths reject malformed requests and handle Windows drives and UNC without trimming names", () => { + for (const payload of [null, {}, { requestId: "x", paths: [] }, { requestId: "x", paths: ["relative"] }, + { requestId: "x", paths: ["/bad\0file"] }, { requestId: "x", paths: [42] }]) { + assert.throws(() => validateDragPayload(payload)); + } + assert.deepEqual(validateDragPayload({ requestId: "x", paths: ["C:/a b/file ", "C:\\a b\\file ", "\\\\server\\share\\folder"] }, path.win32), + ["C:/a b/file ", "C:\\a b\\file ", "\\\\server\\share\\folder"]); + assert.throws(() => validateDragPayload({ requestId: "x", paths: ["C:relative"] }, path.win32)); + assert.deepEqual(validateDragPayload({ requestId: "x", paths: ["/a/../b", "/b", "/a/../b"] }, path.posix), ["/a/../b", "/b"]); + assert.throws(() => validateDragPayload({ requestId: "x", paths: ["/drive-relative"] }, path.win32)); + assert.throws(() => validateDragPayload({ requestId: "x", paths: ["//./pipe/device"] }, path.win32)); +}); + +test("absolute path spelling survives dot segments and repeated separators on POSIX, drives and UNC", () => { + for (const [pathApi, paths] of [ + [path.posix, ["/local/link/../file", "/local/./file", "/local//file"]], + [path.win32, ["C:\\local\\link\\..\\file", "C:/local/./file", "\\\\server\\share\\link\\..\\file"]], + ]) { + assert.deepEqual(validateDragPayload({ requestId: "paths", paths: [...paths, paths[0]] }, pathApi), paths); + } +}); + +test("native drag validates every item, supports directories and preserves symlinks", async (t) => { + tempDirBridge.ensureTempDir(); + const dir = fs.mkdtempSync(tempDirBridge.getTempFilePath("local-drag-test-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const file = path.join(dir, "certificate with spaces.txt"); + const folder = path.join(dir, "folder"); + fs.writeFileSync(file, "original"); + fs.mkdirSync(folder); + const h = harness(); + assert.deepEqual(await h.handlers.start(h.event, { requestId: "one", paths: [file, folder, file] }), { started: true }); + assert.deepEqual(h.calls[0].files, [file, folder]); + assert.equal(h.calls[0].icon, h.icon); + assert.equal(fs.readFileSync(file, "utf8"), "original"); + const result = await h.handlers.start(h.event, { requestId: "two", paths: [file, path.join(dir, "missing")] }); + assert.equal(result.started, false); + assert.ok(result.error); + assert.equal(h.calls.length, 1, "a partly valid selection must not start"); + if (process.platform !== "win32") { + const link = path.join(dir, "link"); + fs.symlinkSync(file, link); + assert.equal((await h.handlers.start(h.event, { requestId: "link", paths: [link] })).started, true); + assert.deepEqual(h.calls[1].files, [link]); + fs.unlinkSync(file); + assert.equal((await h.handlers.start(h.event, { requestId: "broken", paths: [link] })).started, false); + } +}); + +test("symlink followed by parent traversal keeps the selected file through validation and native handoff", { + skip: process.platform === "win32", +}, async (t) => { + tempDirBridge.ensureTempDir(); + const dir = fs.mkdtempSync(tempDirBridge.getTempFilePath("local-drag-symlink-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const target = path.join(dir, "target"); + fs.mkdirSync(path.join(target, "nested"), { recursive: true }); + const selected = path.join(target, "certificate.txt"); + const decoy = path.join(dir, "certificate.txt"); + fs.writeFileSync(selected, "selected certificate"); + fs.writeFileSync(decoy, "different certificate"); + const link = path.join(dir, "link"); + fs.symlinkSync(path.join(target, "nested"), link); + // Do not use path.join here: it would erase the filesystem-sensitive '..'. + const original = `${link}/../certificate.txt`; + assert.equal(fs.statSync(original).ino, fs.statSync(selected).ino); + assert.notEqual(fs.statSync(original).ino, fs.statSync(path.normalize(original)).ino); + const inspected = []; + const h = harness({ stat: (value) => { inspected.push(value); return fs.promises.stat(value); } }); + assert.deepEqual(await h.handlers.start(h.event, { requestId: "link-parent", paths: [original, original] }), { started: true }); + assert.deepEqual(inspected, [original]); + assert.deepEqual(h.calls[0].files, [original]); + fs.unlinkSync(selected); + const missing = await h.handlers.start(h.event, { requestId: "missing-target", paths: [original] }); + assert.equal(missing.started, false, "the existing decoy must not replace a missing selected file"); + assert.ok(missing.error); + assert.equal(h.calls.length, 1); +}); + +test("unregistered windows and subframes cannot initiate filesystem inspection or drag", async () => { + let inspected = 0; + const h = harness({ stat: () => { inspected++; } }); + const payload = { requestId: "id", paths: [path.resolve("file")] }; + assert.equal((await h.handlers.start({ ...h.event, senderFrame: {} }, payload)).started, false); + assert.equal((await h.handlers.start({ sender: { ...h.event.sender }, senderFrame: h.event.senderFrame }, payload)).started, false); + assert.equal(inspected, 0); + assert.equal(h.calls.length, 0); +}); + +test("mouse release, Escape and replacement gestures cannot start a delayed native drag", async () => { + const { EventEmitter } = require("node:events"); + const tracker = createGestureTracker(); + let finish; + const h = harness({ getGesture: tracker.getGesture, + stat: () => new Promise(resolve => { finish = resolve; }), + }); + Object.setPrototypeOf(h.event.sender, new EventEmitter()); + tracker.attach(h.event.sender); + const mouse = type => h.event.sender.emit("before-mouse-event", {}, { type, button: "left" }); + const payload = { requestId: "id", paths: [path.resolve("file")] }; + assert.equal((await h.handlers.start(h.event, payload)).started, false); + for (const end of [() => mouse("mouseUp"), + () => h.event.sender.emit("before-input-event", {}, { key: "Escape" }), + () => mouse("mouseDown"), + () => h.handlers.cancel(h.event, payload)]) { + mouse("mouseDown"); + const result = h.handlers.start(h.event, payload); + end(); + finish({ isFile: () => true }); + assert.equal((await result).started, false); + } + assert.equal(h.calls.length, 0); + mouse("mouseDown"); + const valid = h.handlers.start(h.event, payload); + finish({ isFile: () => true }); + assert.deepEqual(await valid, { started: true }); + assert.equal(h.calls.length, 1); +}); + +test("special files, destroyed senders and native errors fail without claiming a completed transfer", async () => { + const h = harness({ stat: () => ({ isFile: () => false, isDirectory: () => false }) }); + const payload = { requestId: "id", paths: [path.resolve("file")] }; + assert.equal((await h.handlers.start(h.event, payload)).started, false); + const native = harness({ stat: () => ({ isFile: () => true }) }); + native.event.sender.startDrag = () => { throw new Error("native error"); }; + assert.deepEqual(await native.handlers.start(native.event, payload), { started: false, error: "native error" }); + native.event.sender.isDestroyed = () => true; + assert.equal((await native.handlers.start(native.event, payload)).started, false); +}); diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index a87ee8558..5a5c648d1 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -459,6 +459,11 @@ function createBridgeRegistrar(context) { sshBridge.registerHandlers(ipcMain, { terminalWorkerManager }); sftpBridge.registerHandlers(ipcMain, { terminalWorkerManager }); localFsBridge.registerHandlers(ipcMain); + require("../bridges/localFileDragBridge.cjs").registerHandlers(ipcMain, { + getWindows: () => getWindowManager().getAppContentWindows?.() || [], + nativeImage: electronModule.nativeImage, + app, + }); transferBridge.registerHandlers(ipcMain, { terminalWorkerManager }); portForwardingBridge.registerHandlers(ipcMain, { terminalWorkerManager }); terminalBridge.registerHandlers(ipcMain, { terminalWorkerManager }); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index c79fd026e..ea3a60edd 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -1636,6 +1636,8 @@ function createPreloadApi(ctx) { }, // Get file path from File object (for drag-and-drop) + startLocalFileDrag: (payload) => ipcRenderer.invoke("netcatty:local:drag-start", payload), + cancelLocalFileDrag: (requestId) => ipcRenderer.send("netcatty:local:drag-cancel", { requestId }), getPathForFile: (file) => { try { return webUtils.getPathForFile(file); diff --git a/electron/preload/api.localFileDrag.test.cjs b/electron/preload/api.localFileDrag.test.cjs new file mode 100644 index 000000000..98351e8fb --- /dev/null +++ b/electron/preload/api.localFileDrag.test.cjs @@ -0,0 +1,15 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { createPreloadApi } = require("./api.cjs"); + +test("local file drag exposes only the dedicated start and cancellation channels", async () => { + const calls = []; + const api = createPreloadApi({ ipcRenderer: { + invoke: async (...args) => { calls.push(args); return { started: true }; }, + send: (...args) => calls.push(args), + }, webUtils: {} }); + const payload = { requestId: "one", paths: ["/file"] }; + assert.deepEqual(await api.startLocalFileDrag(payload), { started: true }); + api.cancelLocalFileDrag("one"); + assert.deepEqual(calls, [["netcatty:local:drag-start", payload], ["netcatty:local:drag-cancel", { requestId: "one" }]]); +}); diff --git a/package.json b/package.json index d43605ba5..ba51497f5 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "bench:sync-crdt": "tsx scripts/bench-sync-crdt.ts", "test:ssh-mfa-models": "node --test electron/bridges/sshMfaModels.live.test.cjs", "test:ssh-mfa-models:live": "SSH_MFA_LIVE=1 node --test electron/bridges/sshMfaModels.live.test.cjs", + "test:local-file-drag:electron": "electron scripts/local-file-drag.live.test.cjs", "test:tray-panel-layout": "electron scripts/tray-panel-layout.live.test.cjs", "test:xterm-foreground-intense": "electron scripts/xterm-foreground-intense.live.test.cjs", "test:terminal-background-rendering": "electron scripts/terminal-background-rendering.live.test.cjs", diff --git a/scripts/local-file-drag.live.test.cjs b/scripts/local-file-drag.live.test.cjs new file mode 100644 index 000000000..6e3e636ee --- /dev/null +++ b/scripts/local-file-drag.live.test.cjs @@ -0,0 +1,131 @@ +"use strict"; + +// Interactive test: native drags must be driven by the OS, not synthetic DOM +// DragEvents. All filesystem fixtures and userData live in Netcatty's temp dir. +if (!process.versions.electron) { + require("node:test")("native local file drag (interactive Electron)", { + skip: "run npm run test:local-file-drag:electron and follow the window instructions", + }, () => {}); +} else { + const fs = require("node:fs"); + const path = require("node:path"); + const { app, BrowserWindow, ipcMain, nativeImage } = require("electron"); + const { build } = require("esbuild"); + const tempDirBridge = require("../electron/bridges/tempDirBridge.cjs"); + const { registerHandlers } = require("../electron/bridges/localFileDragBridge.cjs"); + tempDirBridge.ensureTempDir(); + const fixture = fs.mkdtempSync(tempDirBridge.getTempFilePath("local-file-drag-live-")); + app.setPath("userData", path.join(fixture, "profile")); + const source = path.join(fixture, "source"); + const destination = path.join(fixture, "destination"); + fs.mkdirSync(source); + fs.mkdirSync(destination); + fs.mkdirSync(path.join(source, "folder")); + fs.writeFileSync(path.join(source, "certificate test.txt"), "Netcatty native drag fixture\n"); + fs.writeFileSync(path.join(source, "folder", "nested.txt"), "Nested fixture\n"); + const preload = path.join(fixture, "preload.cjs"); + fs.writeFileSync(preload, ` + const { contextBridge, ipcRenderer, webUtils } = require('electron'); + const { createPreloadApi } = require(${JSON.stringify(path.resolve(__dirname, '../electron/preload/api.cjs'))}); + const api = createPreloadApi({ ipcRenderer, webUtils }); + contextBridge.exposeInMainWorld('netcatty', { + startLocalFileDrag: async payload => { ipcRenderer.send('test:drag-report', {kind:'START_REQUEST', files:payload.paths}); const result = await api.startLocalFileDrag(payload); ipcRenderer.send('test:drag-report', {kind:'START_RESULT', result}); return result; }, + cancelLocalFileDrag: id => { ipcRenderer.send('test:drag-report', {kind:'CANCEL_REQUEST', id}); api.cancelLocalFileDrag(id); }, + getPathForFile: api.getPathForFile, + }); + contextBridge.exposeInMainWorld('dragTest', { + source: ${JSON.stringify(source)}, destination: ${JSON.stringify(destination)}, + report: payload => ipcRenderer.send('test:drag-report', payload), + }); + `); + const renderer = ` + import React, { useState } from 'react'; + import { createRoot } from 'react-dom/client'; + import { useSftpPaneDragAndSelect } from './components/sftp/hooks/useSftpPaneDragAndSelect'; + import { netcattyBridge } from './infrastructure/services/netcattyBridge'; + const report = (kind, files) => { + document.querySelector('#result').textContent = JSON.stringify({kind, files}, null, 2); + window.dragTest.report({kind, files}); + }; + for (const type of ['dragstart','dragenter','drop','dragend','mouseup','mousedown','blur','keydown']) window.addEventListener(type, e => window.dragTest.report({kind:'EVENT', type, buttons:e.buttons, key:e.key, types:e.dataTransfer ? [...e.dataTransfer.types] : []}), true); + const noop = () => {}; + const entries = [ + {name: 'certificate test.txt', type: 'file', size: 28}, + {name: 'folder', type: 'directory', size: 0} + ]; + function Pane({side, dragged, setDragged}) { + const [selectedFiles, setSelected] = useState(new Set()); + const [remote, setRemote] = useState(false); + const pane = {id: side, selectedFiles, connection: { + id: side, isLocal: !remote, currentPath: window.dragTest.source + }}; + const drag = useSftpPaneDragAndSelect({ side, pane, sortedDisplayFiles: entries, draggedFiles: dragged, + onDragStart: (files, origin) => setDragged(files.map(f => ({...f, side: origin}))), + onReceiveFromOtherPane: files => report('INTERNAL_COPY', files), + onMoveEntriesToPath: async (paths, target) => report('INTERNAL_MOVE', {paths, target}), + onUploadExternalFiles: async data => report('EXTERNAL_UPLOAD', Array.from(data.files).map(f => netcattyBridge.require().getPathForFile(f))), + onOpenEntry: noop, onRangeSelect: names => setSelected(new Set(names)), + onToggleSelection: (name, multi) => setSelected(old => { + const next = multi ? new Set(old) : new Set(); + if (next.has(name)) next.delete(name); else next.add(name); + return next; + }), + }); + return
+

{side} {remote ? 'REMOTE (regression)' : 'LOCAL'}

+ + {entries.map((entry, i) =>
drag.handleRowSelect(entry,i,e)} + onDragStart={e => drag.handleFileDragStart(entry,e)} onDragEnd={() => setDragged(null)} + onDragOver={e => drag.handleEntryDragOver(entry,e)} onDrop={e => drag.handleEntryDrop(entry,e)}> + {entry.name} +
)} +

Drop here to copy between panes.

+
; + } + function App() { + const [dragged,setDragged] = useState(null); + return <>

Netcatty native drag test

+

Drag a file to the blue target, another pane, or Finder/Explorer. Cmd/Ctrl-click for multi-selection. Escape cancels.

+
+
{e.preventDefault();e.dataTransfer.dropEffect='copy';}} + onDrop={e => {e.preventDefault();report('NATIVE_DROP', Array.from(e.dataTransfer.files).map(f => netcattyBridge.require().getPathForFile(f)));}}> + Native file destination (expects real Files, never text) +
+

Finder/Explorer destination: {window.dragTest.destination}

No drops yet
+ ; + } + createRoot(document.getElementById('root')).render(); + `; + let win; + ipcMain.on("test:drag-report", (event, payload) => { + if (event.sender !== win?.webContents) return; + if (payload.kind === "NATIVE_DROP") { + if (!payload.files?.length || payload.files.some(file => !fs.existsSync(file))) { + console.error("FAIL_NATIVE_FILES", JSON.stringify(payload)); + return; + } + } + console.log("DRAG_RECEIPT", JSON.stringify(payload)); + }); + app.whenReady().then(async () => { + await build({ stdin: { contents: renderer, loader: "tsx", resolveDir: path.resolve(__dirname, "..") }, + bundle: true, platform: "browser", format: "iife", outfile: path.join(fixture, "renderer.js"), + define: { "process.env.NODE_ENV": '"development"' }, logLevel: "warning", + }); + const html = path.join(fixture, "index.html"); + fs.writeFileSync(html, `
`); + win = new BrowserWindow({ width: 1000, height: 760, title: "Netcatty native drag test", webPreferences: { + preload, contextIsolation: true, nodeIntegration: false, sandbox: false, + }}); + registerHandlers(ipcMain, { getWindows: () => win && !win.isDestroyed() ? [win] : [], nativeImage }); + await win.loadFile(html); + console.log("DRAG_FIXTURE", fixture); + console.log("Close the test window when finished. Fixtures remain here for content verification."); + }).catch(error => { console.error(error); app.exit(1); }); + app.on("window-all-closed", () => app.quit()); +} diff --git a/types/global/netcatty-bridge-files.d.ts b/types/global/netcatty-bridge-files.d.ts index c0aa27484..3a2480686 100644 --- a/types/global/netcatty-bridge-files.d.ts +++ b/types/global/netcatty-bridge-files.d.ts @@ -133,6 +133,8 @@ declare global { // Get file path from File object (for drag-and-drop, uses Electron's webUtils) getPathForFile?(file: File): string | undefined; + startLocalFileDrag?(payload: { requestId: string; paths: string[] }): Promise<{ started: boolean; error?: string }>; + cancelLocalFileDrag?(requestId: string): void; showSystemNotification?(payload: { title: string; body: string;