Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(ui): enable macOS saved-file drag-out

Ruben Lütke956ccade274a
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 5e57af20fa..641ea95bae 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -20,6 +20,10 @@ mascot now use a main-thread companion-process host on macOS; rendered images
and bubble fonts are explicitly bound to the overlay's Tcl interpreter so the
host's Tk bootstrap root cannot steal them.
+**Desktop download follow-up 2026-07-19:** saved-file drag-out now has native
+Windows (OLE/WebView2) and macOS (AppKit/WKWebView) sources. P-15 records the
+remaining GTK source gap; reveal/open actions remain available on Linux.
+
## Audit verdict summary
**No hard breakers found.** No feature crashes on macOS or headless Linux;
@@ -53,6 +57,7 @@ experiences today.
| P-12 | Info | CU legacy | Frozen legacy CU loops are Windows-only, but NOT on the live path (harness force-routes to v2); imports are lazy | `jarvis/cu/loops/screenshot_only_loop.py` et al. | None at runtime |
| P-13 | Info | Wiki | Wiki DB/vault anchor at `repo_root()` — read-only *wheel* installs would fail writes (not OS-specific; `JARVIS_DATA_DIR` override exists) | `jarvis/memory/wiki/db_path.py:9`, `vault_root.py:59` | None on the advertised install paths |
| P-14 | Info | CU extras | macOS/Linux actuation and UI trees depend on optional extras (pynput, pyobjc, pyatspi); without them everything degrades honestly to screenshot + pixel-click | `jarvis/cu/actuate/posix.py`, `jarvis/vision/tree_factory.py` | By design (§3); bare install keeps the CU loop functional |
+| P-15 | Low | Desktop downloads | Native drag-out has Windows OLE and macOS AppKit sources but no GTK/WebKitGTK source yet | `jarvis/ui/native_drag.py` | Linux desktop: the saved-file toast keeps reliable **Show in folder** and **Open** actions but is not itself a drag handle; headless: the normal browser download path remains available |
## Maintenance
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 7cedf0eda2..00ecc5363b 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3354,9 +3354,10 @@ class DesktopApp:
# Native file drag-out: dragging a saved-download toast drops the REAL
# file into any app (Explorer, a browser upload zone, a chat). Must be
- # installed BEFORE webview.start() — it patches the WebView2 UI-thread
- # message handler so DoDragDrop runs where the mouse press lives. Windows
- # only for now; a logged no-op elsewhere. Never blocks the window.
+ # installed BEFORE webview.start() — it patches the WebView host's
+ # UI-thread message handler so the OS drag runs where the mouse press
+ # lives. Windows and macOS are native; Linux is a logged no-op until its
+ # GTK source lands. Never blocks the window.
try:
from pathlib import Path as _Path
diff --git a/jarvis/ui/native_drag.py b/jarvis/ui/native_drag.py
index e151a98b92..71c2058829 100644
--- a/jarvis/ui/native_drag.py
+++ b/jarvis/ui/native_drag.py
@@ -6,21 +6,19 @@ window via HTML5 drag-and-drop, and pywebview ships no drag-out API
(r0x0r/pywebview#877, #1192). So we start the native OS drag ourselves.
**The one thing that makes this work (and the reason a naive attempt fails):**
-``DoDragDrop`` runs a modal OLE loop that grabs the mouse and reads mouse
-messages from the *calling thread's* queue — so it must run on the WebView2 host
-**UI thread** while the physical mouse button is still down. pywebview's
-``js_api`` bridge runs exposed methods on a *worker* thread, so starting the drag
-there never takes over the in-progress press. Instead the frontend posts a raw
-``window.chrome.webview.postMessage([TAG, {files}])`` on ``mousedown``; WebView2
-delivers that to ``EdgeChrome.on_script_notify`` **on the UI thread**, and we run
-``DoDragDrop`` there. This is the technique shipped by Tiefsee4 (hbl917070) and
-ported to pywebview by FeralFox — verified against WebView2Feedback#2313.
+the native drag must begin on the WebView host's UI thread while the physical
+mouse button is still down. pywebview's ``js_api`` bridge runs exposed methods
+on a worker thread, so it cannot take over the in-progress press. The frontend
+therefore uses each engine's raw script-message bridge on ``mousedown``:
+WebView2's ``window.chrome.webview`` on Windows and WKWebView's
+``window.webkit.messageHandlers.jarvisFileDrag`` on macOS.
Cross-platform, capability-gated, fail-closed to a logged no-op:
* Windows: monkeypatch ``EdgeChrome.on_script_notify`` → WinForms ``DataObject``
(which packs CF_HDROP for us) → ``webview.DoDragDrop(..., Copy)``.
-* macOS / Linux: Phase-2 seams (NSFilePromiseProvider / GTK drag-source) — honest
- no-op until wired.
+* macOS: register a dedicated WKScriptMessage handler → ``NSDraggingItem``
+ carrying a real file URL → ``beginDraggingSessionWithItems``.
+* Linux: GTK drag-source seam — honest no-op until wired.
Path safety (AP-2 spirit): a path posted by the renderer is dragged only if it
resolves to an existing regular file inside an explicit allow-list of base dirs
@@ -32,8 +30,10 @@ from __future__ import annotations
import json
import logging
import sys
-from collections.abc import Sequence
+import time
+from collections.abc import Mapping, Sequence
from pathlib import Path
+from typing import Any
log = logging.getLogger(__name__)
@@ -44,6 +44,16 @@ MESSAGE_TAG = "jarvis-file-drag"
# Windows DROPEFFECT: COPY (never MOVE — the source download must stay put).
_DROPEFFECT_COPY = 1
+# A dedicated WKWebView handler appears in JavaScript only when the AppKit bridge
+# registered successfully. That keeps frontend capability detection truthful;
+# the normal pywebview js_api bridge deliberately hops to a worker thread.
+MACOS_MESSAGE_HANDLER = "jarvisFileDrag"
+
+# A WK script message normally arrives synchronously from the DOM mousedown.
+# Keep a small allowance for WebKit dispatch without ever reusing an old click.
+_MACOS_MOUSE_EVENT_MAX_AGE_S = 1.0
+_MACOS_DRAG_ICON_SIZE = 32.0
+
def _resolve_bases(allowed_base_dirs: Sequence[Path] | None) -> list[Path] | None:
if allowed_base_dirs is None:
@@ -82,17 +92,45 @@ def _validate_paths(paths: Sequence[str], bases: list[Path] | None) -> list[str]
return out
+def _drag_files_from_message(message: object) -> list[str] | None:
+ """Extract our file list, or return ``None`` when a message is not ours."""
+ data = message
+ if isinstance(data, str):
+ try:
+ data = json.loads(data)
+ except (TypeError, ValueError):
+ return None
+
+ if (
+ not isinstance(data, Sequence)
+ or isinstance(data, (str, bytes, bytearray))
+ or len(data) < 2
+ or data[0] != MESSAGE_TAG
+ or not isinstance(data[1], Mapping)
+ ):
+ return None
+
+ raw_files = data[1].get("files", [])
+ if not isinstance(raw_files, Sequence) or isinstance(
+ raw_files, (str, bytes, bytearray)
+ ):
+ return []
+ return [str(path) for path in raw_files]
+
+
def install_native_drag(allowed_base_dirs: Sequence[Path] | None = None) -> bool:
"""Wire native file drag-out into the desktop WebView. Call once before
``webview.start()``. Returns True if a drag source was installed for this OS.
- Windows-only for now; macOS/Linux return False (honest no-op) until their
- seams land. Never raises — a missing dependency / unexpected pywebview
- internal just disables the feature and logs.
+ Windows and macOS have native sources. Linux returns False (honest no-op)
+ until its GTK seam lands. Never raises — a missing dependency or unexpected
+ pywebview internal just disables the feature and logs.
"""
if sys.platform == "win32":
return _install_windows_drag(allowed_base_dirs)
- # Phase 2: _install_macos_drag / _install_linux_drag.
+ if sys.platform == "darwin":
+ return _install_macos_drag(allowed_base_dirs)
+ # Phase 2: _install_linux_drag.
log.info("native_drag: no drag source for platform %s yet", sys.platform)
return False
@@ -102,13 +140,13 @@ def _install_windows_drag(allowed_base_dirs: Sequence[Path] | None) -> bool:
on the UI thread when the frontend posts a ``[MESSAGE_TAG, {files}]`` message.
"""
try:
- import clr
+ import clr # type: ignore[import-not-found]
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Collections")
- import System.Windows.Forms as WinForms # noqa: N813
+ import System.Windows.Forms as WinForms # type: ignore[import-not-found] # noqa: N813
import webview.platforms.edgechromium as ec
- from System import Array
+ from System import Array # type: ignore[import-not-found]
except Exception as exc: # noqa: BLE001 — .NET/pywebview internals absent
log.warning("native_drag: WebView2 drag bridge unavailable (%s)", exc)
return False
@@ -125,23 +163,17 @@ def _install_windows_drag(allowed_base_dirs: Sequence[Path] | None) -> bool:
# the js_api bridge / drop-in feature keep working.
try:
data = json.loads(args.get_WebMessageAsJson())
- is_drag = (
- isinstance(data, list)
- and len(data) >= 2
- and data[0] == MESSAGE_TAG
- and isinstance(data[1], dict)
- )
+ raw_files = _drag_files_from_message(data)
except Exception: # noqa: BLE001 — not JSON / not ours
- is_drag = False
+ raw_files = None
- if not is_drag:
+ if raw_files is None:
return original(self, sender, args)
# Our drag message — handled on the UI thread (this callback). Any failure
# is contained here; we never re-dispatch to the original for a drag msg.
try:
- raw_files = data[1].get("files", [])
- paths = _validate_paths([str(p) for p in raw_files], bases)
+ paths = _validate_paths(raw_files, bases)
if paths:
obj = WinForms.DataObject(
WinForms.DataFormats.FileDrop, Array[str](paths)
@@ -152,7 +184,162 @@ def _install_windows_drag(allowed_base_dirs: Sequence[Path] | None) -> bool:
log.exception("native_drag: DoDragDrop failed")
return None
- ec.EdgeChrome.on_script_notify = _patched_on_script_notify
- ec.EdgeChrome._jarvis_drag_installed = True
+ ec.EdgeChrome.on_script_notify = _patched_on_script_notify # type: ignore[method-assign]
+ ec.EdgeChrome._jarvis_drag_installed = True # type: ignore[attr-defined]
log.info("native_drag: WebView2 file drag-out installed")
return True
+
+
+def _begin_macos_drag(
+ webview: Any,
+ paths: Sequence[str],
+ event: Any,
+ source: Any,
+ *,
+ appkit: Any,
+ foundation: Any,
+) -> bool:
+ """Start one AppKit copy drag containing existing file URLs."""
+ try:
+ location = webview.convertPoint_fromView_(event.locationInWindow(), None)
+ workspace = appkit.NSWorkspace.sharedWorkspace()
+ items = []
+ for index, path in enumerate(paths):
+ url = foundation.NSURL.fileURLWithPath_(path)
+ item = appkit.NSDraggingItem.alloc().initWithPasteboardWriter_(url)
+ icon = workspace.iconForFile_(path)
+ offset = min(index, 4) * 3.0
+ frame = appkit.NSMakeRect(
+ float(location.x) - (_MACOS_DRAG_ICON_SIZE / 2.0) + offset,
+ float(location.y) - (_MACOS_DRAG_ICON_SIZE / 2.0) - offset,
+ _MACOS_DRAG_ICON_SIZE,
+ _MACOS_DRAG_ICON_SIZE,
+ )
+ item.setDraggingFrame_contents_(frame, icon)
+ items.append(item)
+
+ if not items:
+ return False
+ session = webview.beginDraggingSessionWithItems_event_source_(
+ items,
+ event,
+ source,
+ )
+ if session is not None:
+ session.setAnimatesToStartingPositionsOnCancelOrFail_(True)
+ return session is not None
+ except Exception: # noqa: BLE001 — a drag must never crash AppKit's main thread
+ log.exception("native_drag: AppKit dragging session failed")
+ return False
+
+
+def _install_macos_drag(allowed_base_dirs: Sequence[Path] | None) -> bool:
+ """Patch pywebview's WKWebView bridge to start a native AppKit file drag."""
+ try:
+ import AppKit # type: ignore[import-not-found, import-untyped] # noqa: N813, PLC0415
+ import Foundation # type: ignore[import-not-found, import-untyped] # noqa: N813, PLC0415
+ import objc # type: ignore[import-not-found, import-untyped] # noqa: PLC0415
+ import webview.platforms.cocoa as cocoa # type: ignore[import-untyped] # noqa: PLC0415
+ except Exception as exc: # noqa: BLE001 — optional desktop internals absent
+ log.warning("native_drag: WKWebView drag bridge unavailable (%s)", exc)
+ return False
+
+ browser_class = cocoa.BrowserView
+ host_class = browser_class.WebKitHost
+ if getattr(host_class, "_jarvis_drag_installed", False):
+ return True
+
+ try:
+ dragging_source_protocol = objc.protocolNamed("NSDraggingSource")
+
+ class JarvisFileDragSource( # type: ignore[call-arg] # noqa: D101
+ AppKit.NSObject,
+ protocols=[dragging_source_protocol],
+ ):
+ def draggingSession_sourceOperationMaskForDraggingContext_(
+ self,
+ _session: Any,
+ _context: int,
+ ) -> int:
+ return int(AppKit.NSDragOperationCopy)
+
+ bases = _resolve_bases(allowed_base_dirs)
+ source = JarvisFileDragSource.alloc().init()
+ original_mouse_down = host_class.mouseDown_
+ original_browser_init = browser_class.__init__
+
+ def _patched_mouse_down(self: Any, event: Any) -> Any:
+ self._jarvis_drag_mouse_down = (event, time.monotonic())
+ return original_mouse_down(self, event)
+
+ script_message_protocol = objc.protocolNamed("WKScriptMessageHandler")
+
+ class JarvisFileDragMessageHandler( # type: ignore[call-arg] # noqa: D101
+ AppKit.NSObject,
+ protocols=[script_message_protocol],
+ ):
+ def userContentController_didReceiveScriptMessage_(
+ self,
+ _controller: Any,
+ message: Any,
+ ) -> None:
+ raw_files = _drag_files_from_message(message.body())
+ if raw_files is None:
+ return
+
+ try:
+ webview = message.webView()
+ mouse_state = getattr(webview, "_jarvis_drag_mouse_down", None)
+ webview._jarvis_drag_mouse_down = None
+ if not mouse_state:
+ return
+ event, started_at = mouse_state
+ if (
+ time.monotonic() - float(started_at)
+ > _MACOS_MOUSE_EVENT_MAX_AGE_S
+ ):
+ return
+ if not (int(AppKit.NSEvent.pressedMouseButtons()) & 1):
+ return
+
+ paths = _validate_paths(raw_files, bases)
+ if paths:
+ _begin_macos_drag(
+ webview,
+ paths,
+ event,
+ source,
+ appkit=AppKit,
+ foundation=Foundation,
+ )
+ except Exception: # noqa: BLE001 — contain failures on AppKit's UI thread
+ log.exception("native_drag: WKWebView drag message failed")
+
+ def _patched_browser_init(self: Any, window: Any) -> None:
+ original_browser_init(self, window)
+ try:
+ handler = JarvisFileDragMessageHandler.alloc().init()
+ self.webview.configuration().userContentController().addScriptMessageHandler_name_(
+ handler,
+ MACOS_MESSAGE_HANDLER,
+ )
+ # WKUserContentController retains the handler; this explicit
+ # reference also keeps its lifetime obvious across pywebview versions.
+ self._jarvis_drag_message_handler = handler
+ except Exception: # noqa: BLE001 — window creation must still succeed
+ log.exception("native_drag: WKWebView handler registration failed")
+
+ host_class.mouseDown_ = _patched_mouse_down # type: ignore[method-assign]
+ browser_class.__init__ = _patched_browser_init # type: ignore[method-assign]
+ # Retain both the source and original methods for the full process and
+ # make duplicate installer calls idempotent.
+ host_class._jarvis_drag_source = source
+ host_class._jarvis_drag_original_mouse_down = original_mouse_down
+ browser_class._jarvis_drag_original_init = original_browser_init # type: ignore[attr-defined]
+ host_class._jarvis_drag_installed = True
+ except Exception as exc: # noqa: BLE001 — pywebview/AppKit internals changed
+ log.warning("native_drag: WKWebView drag bridge unavailable (%s)", exc)
+ return False
+
+ log.info("native_drag: WKWebView file drag-out installed")
+ return True
diff --git a/jarvis/ui/web/frontend/src/lib/fileActions.ts b/jarvis/ui/web/frontend/src/lib/fileActions.ts
index 844ff640fc..7f6bc9263a 100644
--- a/jarvis/ui/web/frontend/src/lib/fileActions.ts
+++ b/jarvis/ui/web/frontend/src/lib/fileActions.ts
@@ -1,13 +1,11 @@
/**
* Native file actions for a file already saved to the user's Downloads folder.
*
- * Why this exists: dragging a file OUT of the embedded desktop WebView is not
- * reliably possible on any OS (WebView2's HTML5 drag-and-drop is broken;
- * WKWebView/WebKitGTK don't support the Chromium `DownloadURL` drag format). So
- * instead of a broken drag, the UI lets the user reveal the real file in the OS
- * file manager (and drag it natively from there) or open it directly. Both are
- * desktop-only backend calls; on a headless VPS the routes 404 and these return
- * false.
+ * Why this exists: HTML5 cannot reliably drag a real local file out of an
+ * embedded WebView. Windows and macOS use a native drag bridge, while these
+ * actions remain the universal fallback: reveal the saved file in the OS file
+ * manager or open it directly. Both are desktop-only backend calls; on a
+ * headless VPS the routes 404 and these return false.
*/
/** Open the OS file manager with `path` selected. Returns true on success. */
diff --git a/jarvis/ui/web/frontend/src/lib/nativeDrag.test.ts b/jarvis/ui/web/frontend/src/lib/nativeDrag.test.ts
new file mode 100644
index 0000000000..24817b1c14
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/nativeDrag.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { canNativeDrag, startNativeFileDrag } from "./nativeDrag";
+
+interface MessageBridge {
+ postMessage: (message: unknown) => void;
+}
+
+type NativeHostWindow = Window & {
+ chrome?: { webview?: MessageBridge };
+ webkit?: { messageHandlers?: Record<string, MessageBridge | undefined> };
+};
+
+const host = window as NativeHostWindow;
+
+describe("native file drag bridge", () => {
+ beforeEach(() => {
+ delete host.chrome;
+ delete host.webkit;
+ });
+
+ it("stays disabled in a plain browser", () => {
+ expect(canNativeDrag()).toBe(false);
+ expect(startNativeFileDrag("/tmp/session.txt")).toBe(false);
+ });
+
+ it("posts a real-file request through WebView2 on Windows", () => {
+ const postMessage = vi.fn();
+ host.chrome = { webview: { postMessage } };
+
+ expect(canNativeDrag()).toBe(true);
+ expect(startNativeFileDrag("C:\\Users\\Nova\\Downloads\\session.txt")).toBe(
+ true,
+ );
+ expect(postMessage).toHaveBeenCalledWith([
+ "jarvis-file-drag",
+ { files: ["C:\\Users\\Nova\\Downloads\\session.txt"] },
+ ]);
+ });
+
+ it("posts the same request through WKWebView on macOS", () => {
+ const postMessage = vi.fn();
+ host.webkit = {
+ messageHandlers: { jarvisFileDrag: { postMessage } },
+ };
+
+ expect(canNativeDrag()).toBe(true);
+ expect(
+ startNativeFileDrag("/Users/nova/Downloads/voice-session.txt"),
+ ).toBe(true);
+ expect(postMessage).toHaveBeenCalledWith([
+ "jarvis-file-drag",
+ { files: ["/Users/nova/Downloads/voice-session.txt"] },
+ ]);
+ });
+
+ it("does not treat an unrelated WebKit host as the desktop bridge", () => {
+ host.webkit = { messageHandlers: {} };
+
+ expect(canNativeDrag()).toBe(false);
+ expect(startNativeFileDrag("/tmp/session.txt")).toBe(false);
+ });
+
+ it("rejects an empty file path without posting", () => {
+ const postMessage = vi.fn();
+ host.webkit = {
+ messageHandlers: { jarvisFileDrag: { postMessage } },
+ };
+
+ expect(startNativeFileDrag("")).toBe(false);
+ expect(postMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/nativeDrag.ts b/jarvis/ui/web/frontend/src/lib/nativeDrag.ts
index 42a1bdabe6..1b674c1ee1 100644
--- a/jarvis/ui/web/frontend/src/lib/nativeDrag.ts
+++ b/jarvis/ui/web/frontend/src/lib/nativeDrag.ts
@@ -1,32 +1,44 @@
/**
- * Native OS file drag-out from the desktop WebView2 shell.
+ * Native OS file drag-out from the desktop shell.
*
* A WebView cannot drag a real file out via HTML5 drag-and-drop, so we hand the
- * drag to the native side: on `mousedown` (button still down) we post a raw
- * WebView2 message. pywebview delivers it to `EdgeChrome.on_script_notify` ON THE
- * UI THREAD, where `jarvis/ui/native_drag.py` starts an OLE `DoDragDrop` that
- * takes over the in-progress mouse press. From there the OS carries a real file
- * to any target — Explorer, a browser upload zone, a chat. See native_drag.py.
+ * drag to the native side: on `mousedown` (button still down) we post through
+ * WebView2 on Windows or WKWebView on macOS. pywebview delivers either message
+ * on the UI thread, where `jarvis/ui/native_drag.py` starts the platform drag
+ * session and hands a real file URL to Explorer, Finder, browser upload zones,
+ * chats, and other native targets.
*
- * Only available inside the desktop WebView2 shell; `canNativeDrag()` is false in
- * a plain browser / on the VPS, where the UI falls back to the "Show in folder"
- * action instead.
+ * Only available inside a supported desktop shell; `canNativeDrag()` is false
+ * in a plain browser, on Linux until its GTK seam lands, and on a headless VPS,
+ * where the UI falls back to the "Show in folder" action instead.
*/
/** Discriminator — MUST match `MESSAGE_TAG` in jarvis/ui/native_drag.py. */
const DRAG_MESSAGE_TAG = "jarvis-file-drag";
+/** Handler name — MUST match `MACOS_MESSAGE_HANDLER` in native_drag.py. */
+const MACOS_MESSAGE_HANDLER = "jarvisFileDrag";
-interface WebView2Bridge {
+interface NativeMessageBridge {
postMessage: (message: unknown) => void;
}
-function bridge(): WebView2Bridge | undefined {
- const chrome = (window as { chrome?: { webview?: WebView2Bridge } }).chrome;
- const wv = chrome?.webview;
- return wv && typeof wv.postMessage === "function" ? wv : undefined;
+function bridge(): NativeMessageBridge | undefined {
+ const host = window as unknown as {
+ chrome?: { webview?: NativeMessageBridge };
+ webkit?: {
+ messageHandlers?: Record<string, NativeMessageBridge | undefined>;
+ };
+ };
+ const webView2 = host.chrome?.webview;
+ if (webView2 && typeof webView2.postMessage === "function") return webView2;
+
+ const wkWebView = host.webkit?.messageHandlers?.[MACOS_MESSAGE_HANDLER];
+ return wkWebView && typeof wkWebView.postMessage === "function"
+ ? wkWebView
+ : undefined;
}
-/** True in the desktop WebView2 shell, where a native file drag is possible. */
+/** True in a desktop shell that exposes a native file-drag message bridge. */
export function canNativeDrag(): boolean {
return bridge() !== undefined;
}
@@ -36,8 +48,8 @@ export function canNativeDrag(): boolean {
* the button is held. No-op (returns false) outside the desktop shell.
*/
export function startNativeFileDrag(path: string): boolean {
- const wv = bridge();
- if (!wv || !path) return false;
- wv.postMessage([DRAG_MESSAGE_TAG, { files: [path] }]);
+ const nativeBridge = bridge();
+ if (!nativeBridge || !path) return false;
+ nativeBridge.postMessage([DRAG_MESSAGE_TAG, { files: [path] }]);
return true;
}
diff --git a/tests/unit/ui/test_native_drag.py b/tests/unit/ui/test_native_drag.py
new file mode 100644
index 0000000000..e5815fb1cc
--- /dev/null
+++ b/tests/unit/ui/test_native_drag.py
@@ -0,0 +1,262 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.ui import native_drag
+
+
+ ("message", "expected"),
+ [
+ (
+ [
+ "jarvis-file-drag",
+ {"files": ["/Downloads/one.txt", "/Downloads/two.txt"]},
+ ],
+ ["/Downloads/one.txt", "/Downloads/two.txt"],
+ ),
+ (
+ '["jarvis-file-drag", {"files": ["/Downloads/one.txt"]}]',
+ ["/Downloads/one.txt"],
+ ),
+ (["jarvis-file-drag", {"files": "not-a-list"}], []),
+ (["another-message", {"files": ["/Downloads/one.txt"]}], None),
+ ("not-json", None),
+ ],
+)
+def test_drag_files_from_message(
+ message: object,
+ expected: list[str] | None,
+) -> None:
+ assert native_drag._drag_files_from_message(message) == expected # noqa: SLF001
+
+
+def test_validate_paths_keeps_only_regular_files_inside_allowed_bases(
+ tmp_path: Path,
+) -> None:
+ downloads = tmp_path / "Downloads"
+ downloads.mkdir()
+ allowed = downloads / "session.txt"
+ allowed.write_text("transcript", encoding="utf-8")
+ outside = tmp_path / "private.txt"
+ outside.write_text("private", encoding="utf-8")
+
+ paths = native_drag._validate_paths( # noqa: SLF001
+ [str(allowed), str(outside), str(downloads / "missing.txt")],
+ native_drag._resolve_bases([downloads]), # noqa: SLF001
+ )
+
+ assert paths == [str(allowed.resolve())]
+
+
+def test_install_routes_macos_to_the_appkit_backend(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ seen: list[list[Path] | None] = []
+ monkeypatch.setattr(native_drag.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ native_drag,
+ "_install_macos_drag",
+ lambda bases: seen.append(list(bases) if bases is not None else None) or True,
+ )
+
+ assert native_drag.install_native_drag([tmp_path]) is True
+ assert seen == [[tmp_path]]
+
+
+def test_install_is_an_honest_noop_without_a_desktop_drag_backend(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(native_drag.sys, "platform", "linux")
+
+ assert native_drag.install_native_drag() is False
+
+
+def test_begin_macos_drag_publishes_file_urls_with_copy_session() -> None:
+ created_items: list[Any] = []
+
+ class FakeDraggingItem:
+ @classmethod
+ def alloc(cls) -> FakeDraggingItem:
+ item = cls()
+ created_items.append(item)
+ return item
+
+ def initWithPasteboardWriter_(self, writer: object) -> FakeDraggingItem:
+ self.writer = writer
+ return self
+
+ def setDraggingFrame_contents_(self, frame: object, contents: object) -> None:
+ self.frame = frame
+ self.contents = contents
+
+ class FakeSession:
+ def __init__(self) -> None:
+ self.animates_back = False
+
+ def setAnimatesToStartingPositionsOnCancelOrFail_(self, value: bool) -> None:
+ self.animates_back = value
+
+ class FakeWebView:
+ def __init__(self) -> None:
+ self.session = FakeSession()
+ self.started: tuple[list[Any], object, object] | None = None
+
+ def convertPoint_fromView_(self, point: object, source_view: object) -> Any:
+ assert point == "window-point"
+ assert source_view is None
+ return SimpleNamespace(x=100.0, y=80.0)
+
+ def beginDraggingSessionWithItems_event_source_(
+ self,
+ items: list[Any],
+ event: object,
+ source: object,
+ ) -> FakeSession:
+ self.started = (items, event, source)
+ return self.session
+
+ event = SimpleNamespace(locationInWindow=lambda: "window-point")
+ source = object()
+ webview = FakeWebView()
+ appkit = SimpleNamespace(
+ NSDraggingItem=FakeDraggingItem,
+ NSWorkspace=SimpleNamespace(
+ sharedWorkspace=lambda: SimpleNamespace(
+ iconForFile_=lambda path: f"icon:{path}"
+ )
+ ),
+ NSMakeRect=lambda x, y, width, height: (x, y, width, height),
+ )
+ foundation = SimpleNamespace(
+ NSURL=SimpleNamespace(fileURLWithPath_=lambda path: f"file-url:{path}")
+ )
+
+ started = native_drag._begin_macos_drag( # noqa: SLF001
+ webview,
+ ["/Downloads/one.txt", "/Downloads/two.txt"],
+ event,
+ source,
+ appkit=appkit,
+ foundation=foundation,
+ )
+
+ assert started is True
+ assert [item.writer for item in created_items] == [
+ "file-url:/Downloads/one.txt",
+ "file-url:/Downloads/two.txt",
+ ]
+ assert created_items[0].frame == (84.0, 64.0, 32.0, 32.0)
+ assert created_items[1].frame == (87.0, 61.0, 32.0, 32.0)
+ assert webview.started == (created_items, event, source)
+ assert webview.session.animates_back is True
+
+
+def test_macos_bridge_intercepts_only_fresh_physical_drag_messages(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ class FakeNSObject:
+ def __init_subclass__(cls, **_kwargs: object) -> None:
+ super().__init_subclass__()
+
+ @classmethod
+ def alloc(cls) -> FakeNSObject:
+ return cls()
+
+ def init(self) -> FakeNSObject:
+ return self
+
+ class FakeHost:
+ def __init__(self) -> None:
+ self.handlers: dict[str, object] = {}
+
+ def mouseDown_(self, event: object) -> str:
+ self.original_mouse_event = event
+ return "mouse-down"
+
+ def configuration(self) -> Any:
+ return SimpleNamespace(
+ userContentController=lambda: SimpleNamespace(
+ addScriptMessageHandler_name_=lambda handler, name: self.handlers.__setitem__(
+ name,
+ handler,
+ )
+ )
+ )
+
+ class FakeBrowserView:
+ WebKitHost = FakeHost
+
+ def __init__(self, webview: FakeHost) -> None:
+ self.webview = webview
+
+ cocoa = ModuleType("webview.platforms.cocoa")
+ cocoa.BrowserView = FakeBrowserView # type: ignore[attr-defined]
+ platforms = ModuleType("webview.platforms")
+ platforms.__path__ = [] # type: ignore[attr-defined]
+ platforms.cocoa = cocoa # type: ignore[attr-defined]
+ webview_module = ModuleType("webview")
+ webview_module.__path__ = [] # type: ignore[attr-defined]
+ webview_module.platforms = platforms # type: ignore[attr-defined]
+ appkit = ModuleType("AppKit")
+ appkit.NSObject = FakeNSObject # type: ignore[attr-defined]
+ appkit.NSDragOperationCopy = 1 # type: ignore[attr-defined]
+ appkit.NSEvent = SimpleNamespace(pressedMouseButtons=lambda: 1) # type: ignore[attr-defined]
+ foundation = ModuleType("Foundation")
+ objc = ModuleType("objc")
+ objc.protocolNamed = lambda _name: object() # type: ignore[attr-defined]
+
+ monkeypatch.setitem(sys.modules, "AppKit", appkit)
+ monkeypatch.setitem(sys.modules, "Foundation", foundation)
+ monkeypatch.setitem(sys.modules, "objc", objc)
+ monkeypatch.setitem(sys.modules, "webview", webview_module)
+ monkeypatch.setitem(sys.modules, "webview.platforms", platforms)
+ monkeypatch.setitem(sys.modules, "webview.platforms.cocoa", cocoa)
+ monkeypatch.setattr(native_drag.time, "monotonic", lambda: 10.0)
+
+ saved_file = tmp_path / "session.txt"
+ saved_file.write_text("transcript", encoding="utf-8")
+ started: list[tuple[object, list[str], object, object]] = []
+ monkeypatch.setattr(
+ native_drag,
+ "_begin_macos_drag",
+ lambda webview, paths, event, source, **_kwargs: started.append(
+ (webview, list(paths), event, source)
+ )
+ or True,
+ )
+
+ assert native_drag._install_macos_drag([tmp_path]) is True # noqa: SLF001
+ host = FakeHost()
+ browser = FakeBrowserView(host)
+ handler = host.handlers[native_drag.MACOS_MESSAGE_HANDLER]
+ assert browser._jarvis_drag_message_handler is handler # type: ignore[attr-defined]
+ mouse_event = object()
+ assert host.mouseDown_(mouse_event) == "mouse-down"
+
+ class DragMessage:
+ @staticmethod
+ def body() -> list[object]:
+ return [native_drag.MESSAGE_TAG, {"files": [str(saved_file)]}]
+
+ @staticmethod
+ def webView() -> FakeHost: # noqa: N802 - WKScriptMessage-compatible fake
+ return host
+
+ assert (
+ handler.userContentController_didReceiveScriptMessage_(None, DragMessage())
+ is None
+ )
+ assert len(started) == 1
+ assert started[0][:3] == (host, [str(saved_file.resolve())], mouse_event)
+
+ unrelated = SimpleNamespace(body=lambda: "print")
+ assert handler.userContentController_didReceiveScriptMessage_(None, unrelated) is None
+ assert len(started) == 1