[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;