Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(lume): add native file drag and drop

Francesco Bonaccifaa0e1e1d4e5
diff --git a/docs/content/docs/how-to-guides/lume/manage-vms.mdx b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
index 7025dee4af..29c1059023 100644
--- a/docs/content/docs/how-to-guides/lume/manage-vms.mdx
+++ b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
@@ -66,6 +66,17 @@ Closing the native window only hides it; it does not stop the guest. Reopen it
from Lume's Dock icon, **Window → Show VM Window**, or another `lume attach`
command. The older `--no-display` flag remains an alias for `--display none`.
+### Copy files into a native guest
+
+Drop one or more files or folders from Finder onto the native VM screen. Lume
+shows the transfer status while recursively copying the items over SSH to
+`/Users/lume/Desktop`.
+
+File drop is available only in the native viewer and transfers from host to
+guest. SSH for the default `lume` guest account must be available. Lume rejects
+the entire drop rather than overwriting an existing Desktop item; items in the
+same drop must also have distinct names.
+
Gracefully restart or shut down a guest over SSH:
```bash
@@ -92,9 +103,11 @@ lume run macos-tahoe --shared-dir ~/Projects
```
The directory appears in the guest at `/Volumes/My Shared Files`. In the native
-viewer, **Share Folder** can also add a directory while the guest is running;
-folders added from the toolbar last for that run only. Use a read-only mount
-when the guest only needs to read the files:
+viewer, **Share Folder** can also add a directory while the guest is running,
+including the first folder added to a VM that started without shared folders;
+no guest restart or remount is needed. Folders added from the toolbar last for
+that run only. Use a read-only mount when the guest only needs to read the
+files:
```bash
lume run macos-tahoe --shared-dir ~/Projects:ro
diff --git a/libs/lume/src/SSH/SystemSSHClient.swift b/libs/lume/src/SSH/SystemSSHClient.swift
index b033c64d61..793f712bca 100644
--- a/libs/lume/src/SSH/SystemSSHClient.swift
+++ b/libs/lume/src/SSH/SystemSSHClient.swift
@@ -1,5 +1,145 @@
import Foundation
+enum RemoteDesktopCopyError: Error, LocalizedError {
+ case noFilesSelected
+ case unavailableItem
+ case duplicateNames
+ case destinationExists
+ case preparationFailed(String?)
+ case transferFailed(String?)
+ case commitFailed(String?)
+ case timedOut
+
+ var errorDescription: String? {
+ switch self {
+ case .noFilesSelected:
+ return "No files were selected"
+ case .unavailableItem:
+ return "A dropped item is no longer available"
+ case .duplicateNames:
+ return "Dropped items must have unique names"
+ case .destinationExists:
+ return "An item with the same name already exists on the VM Desktop"
+ case .preparationFailed(let detail):
+ return detail.map { "Could not prepare the VM Desktop — \($0)" }
+ ?? "Could not prepare the VM Desktop"
+ case .transferFailed(let detail):
+ return detail.map { "Could not copy the dropped items — \($0)" }
+ ?? "Could not copy the dropped items"
+ case .commitFailed(let detail):
+ return detail.map { "Could not place the dropped items on the VM Desktop — \($0)" }
+ ?? "Could not place the dropped items on the VM Desktop"
+ case .timedOut:
+ return "File copy timed out"
+ }
+ }
+}
+
+final class CopyProcessController: @unchecked Sendable {
+ private enum StopReason {
+ case cancelled
+ case timedOut
+ }
+
+ private let lock = NSLock()
+ private var process: Process?
+ private var stopReason: StopReason?
+ private var timeoutWorkItem: DispatchWorkItem?
+
+ func register(_ process: Process) throws {
+ lock.lock()
+ defer { lock.unlock() }
+ if stopReason == .cancelled {
+ throw CancellationError()
+ }
+ if stopReason == .timedOut {
+ throw RemoteDesktopCopyError.timedOut
+ }
+ self.process = process
+ }
+
+ func processDidStart(_ process: Process) {
+ lock.lock()
+ let shouldTerminate = self.process === process && stopReason != nil
+ lock.unlock()
+ if shouldTerminate, process.isRunning {
+ process.terminate()
+ }
+ }
+
+ func cancel() {
+ requestStop(.cancelled, process: nil)
+ }
+
+ func timeOut(_ process: Process) {
+ requestStop(.timedOut, process: process)
+ }
+
+ func scheduleTimeout(for process: Process, deadline: Date) {
+ let remaining = deadline.timeIntervalSinceNow
+ guard remaining > 0 else {
+ timeOut(process)
+ return
+ }
+ let workItem = DispatchWorkItem { [weak self, weak process] in
+ guard let self, let process else { return }
+ self.timeOut(process)
+ }
+ lock.lock()
+ timeoutWorkItem?.cancel()
+ timeoutWorkItem = workItem
+ lock.unlock()
+ DispatchQueue.global().asyncAfter(deadline: .now() + remaining, execute: workItem)
+ }
+
+ func finish(_ process: Process) throws {
+ lock.lock()
+ let reason = self.process === process ? stopReason : nil
+ if self.process === process {
+ self.process = nil
+ }
+ timeoutWorkItem?.cancel()
+ timeoutWorkItem = nil
+ lock.unlock()
+
+ switch reason {
+ case .cancelled:
+ throw CancellationError()
+ case .timedOut:
+ throw RemoteDesktopCopyError.timedOut
+ case nil:
+ return
+ }
+ }
+
+ private func requestStop(_ reason: StopReason, process expectedProcess: Process?) {
+ lock.lock()
+ guard expectedProcess == nil || process === expectedProcess else {
+ lock.unlock()
+ return
+ }
+ if expectedProcess != nil, process?.isRunning != true {
+ lock.unlock()
+ return
+ }
+ if stopReason == nil {
+ stopReason = reason
+ }
+ let activeProcess = process
+ lock.unlock()
+
+ if let activeProcess, activeProcess.isRunning {
+ activeProcess.terminate()
+ let processIdentifier = activeProcess.processIdentifier
+ DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
+ if activeProcess.isRunning {
+ kill(processIdentifier, SIGKILL)
+ }
+ }
+ }
+ }
+}
+
/// SSH client that delegates to the system's /usr/bin/ssh binary.
/// Used as a fallback when NIO SSH cannot establish a direct TCP connection
/// (e.g., in sandboxed environments where only system-signed binaries can
@@ -81,6 +221,139 @@ public final class SystemSSHClient: Sendable {
)
}
+ /// Copy host files or directories to the guest user's Desktop using system scp.
+ public func copyToRemoteDesktop(
+ _ urls: [URL],
+ timeout: TimeInterval = 600
+ ) async throws {
+ let controller = CopyProcessController()
+ try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ do {
+ try self.copyToRemoteDesktopBlocking(
+ urls,
+ timeout: timeout,
+ controller: controller
+ )
+ continuation.resume()
+ } catch {
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ } onCancel: {
+ controller.cancel()
+ }
+ }
+
+ private func copyToRemoteDesktopBlocking(
+ _ urls: [URL],
+ timeout: TimeInterval,
+ controller: CopyProcessController
+ ) throws {
+ guard !urls.isEmpty else {
+ throw RemoteDesktopCopyError.noFilesSelected
+ }
+
+ let fileManager = FileManager.default
+ for url in urls {
+ guard url.isFileURL, fileManager.fileExists(atPath: url.path) else {
+ throw RemoteDesktopCopyError.unavailableItem
+ }
+ }
+
+ let itemNames = urls.map(\.lastPathComponent)
+ guard Swift.Set(itemNames.map { $0.lowercased() }).count == itemNames.count else {
+ throw RemoteDesktopCopyError.duplicateNames
+ }
+
+ let deadline = Date().addingTimeInterval(timeout)
+ let stagingDirectory = ".lume-drop-\(UUID().uuidString)"
+ var stagingNeedsCleanup = true
+ defer {
+ if stagingNeedsCleanup {
+ cleanupStagingDirectory(stagingDirectory)
+ }
+ }
+ let preparation = try executeCopyCommand(
+ desktopPreparationCommand(
+ itemNames: itemNames,
+ stagingDirectory: stagingDirectory
+ ),
+ deadline: deadline,
+ controller: controller
+ )
+ guard preparation.exitCode == 0 else {
+ if preparation.exitCode == 73 {
+ stagingNeedsCleanup = false
+ throw RemoteDesktopCopyError.destinationExists
+ }
+ throw RemoteDesktopCopyError.preparationFailed(
+ preparation.output.isEmpty ? nil : preparation.output
+ )
+ }
+ let askpassPath = try createAskpassScript()
+ defer { try? fileManager.removeItem(atPath: askpassPath) }
+
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/scp")
+ process.arguments = scpArguments(
+ sourcePaths: urls.map(\.path),
+ destinationDirectory: stagingDirectory
+ )
+
+ var environment = ProcessInfo.processInfo.environment
+ environment["SSH_ASKPASS"] = askpassPath
+ environment["SSH_ASKPASS_REQUIRE"] = "force"
+ environment["DISPLAY"] = ":0"
+ process.environment = environment
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = FileHandle.nullDevice
+
+ let stderrPipe = Pipe()
+ process.standardError = stderrPipe
+
+ try controller.register(process)
+ do {
+ try process.run()
+ } catch {
+ try? controller.finish(process)
+ throw error
+ }
+ controller.processDidStart(process)
+ controller.scheduleTimeout(for: process, deadline: deadline)
+ let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ try controller.finish(process)
+
+ guard process.terminationStatus == 0 else {
+ let stderr = String(data: stderrData, encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let message = stderr.flatMap { $0.isEmpty ? nil : $0 }
+ ?? "SCP exited with code \(process.terminationStatus)"
+ throw RemoteDesktopCopyError.transferFailed(message)
+ }
+
+ let commit = try executeCopyCommand(
+ desktopCommitCommand(
+ itemNames: itemNames,
+ stagingDirectory: stagingDirectory
+ ),
+ deadline: deadline,
+ controller: controller
+ )
+ guard commit.exitCode == 0 else {
+ if commit.exitCode == 73 {
+ throw RemoteDesktopCopyError.destinationExists
+ }
+ throw RemoteDesktopCopyError.commitFailed(
+ commit.output.isEmpty ? nil : commit.output
+ )
+ }
+ stagingNeedsCleanup = false
+ }
+
/// Start an interactive SSH session using system ssh
public func interactive() throws {
let askpassPath = try createAskpassScript()
@@ -129,6 +402,132 @@ public final class SystemSSHClient: Sendable {
return args
}
+ func desktopPreparationCommand(
+ itemNames: [String],
+ stagingDirectory: String
+ ) -> String {
+ let checks = itemNames.map {
+ "if [ -e \"$HOME/Desktop/\"\(Self.shellQuote($0)) ]; then exit 73; fi"
+ }
+ return (
+ ["set -e", "mkdir -p \"$HOME/Desktop\""] + checks
+ + ["mkdir \"$HOME/\(stagingDirectory)\""]
+ ).joined(separator: "; ")
+ }
+
+ func desktopCommitCommand(itemNames: [String], stagingDirectory: String) -> String {
+ let rollback = itemNames.map {
+ let source = "\"$HOME/\(stagingDirectory)/\"\(Self.shellQuote($0))"
+ let destination = "\"$HOME/Desktop/\"\(Self.shellQuote($0))"
+ return "if [ ! -e \(source) ] && [ -e \(destination) ]; then "
+ + "mv -n \(destination) \"$HOME/\(stagingDirectory)/\"; fi"
+ }.joined(separator: "; ")
+ let moves = itemNames.flatMap {
+ let source = "\"$HOME/\(stagingDirectory)/\"\(Self.shellQuote($0))"
+ let destination = "\"$HOME/Desktop/\"\(Self.shellQuote($0))"
+ return [
+ "if [ -e \(destination) ]; then exit 73; fi",
+ "mv -n \(source) \"$HOME/Desktop/\"",
+ "if [ -e \(source) ]; then exit 73; fi",
+ ]
+ }
+ return (
+ ["set -e", "rollback() { \(rollback); }", "trap rollback EXIT"] + moves
+ + ["rmdir \"$HOME/\(stagingDirectory)\"", "trap - EXIT"]
+ )
+ .joined(separator: "; ")
+ }
+
+ func scpArguments(
+ sourcePaths: [String],
+ destinationDirectory: String
+ ) -> [String] {
+ var args = [
+ "-q", "-r",
+ "-o", "StrictHostKeyChecking=no",
+ "-o", "UserKnownHostsFile=/dev/null",
+ "-o", "LogLevel=ERROR",
+ "-o", "ConnectTimeout=10",
+ "-o", "ServerAliveInterval=15",
+ "-o", "ServerAliveCountMax=4",
+ ]
+
+ if port != 22 {
+ args += ["-P", "\(port)"]
+ }
+
+ args.append("--")
+ args.append(contentsOf: sourcePaths)
+ args.append("\(user)@\(host):\(destinationDirectory)/")
+ return args
+ }
+
+ private func executeCopyCommand(
+ _ command: String,
+ deadline: Date,
+ controller: CopyProcessController
+ ) throws -> SSHResult {
+ let askpassPath = try createAskpassScript()
+ defer { try? FileManager.default.removeItem(atPath: askpassPath) }
+
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/ssh")
+ process.arguments = sshArguments(extraArgs: ["\(user)@\(host)", command])
+
+ var environment = ProcessInfo.processInfo.environment
+ environment["SSH_ASKPASS"] = askpassPath
+ environment["SSH_ASKPASS_REQUIRE"] = "force"
+ environment["DISPLAY"] = ":0"
+ process.environment = environment
+
+ let outputPipe = Pipe()
+ process.standardOutput = outputPipe
+ process.standardError = outputPipe
+ process.standardInput = FileHandle.nullDevice
+
+ try controller.register(process)
+ do {
+ try process.run()
+ } catch {
+ try? controller.finish(process)
+ throw error
+ }
+ controller.processDidStart(process)
+ controller.scheduleTimeout(for: process, deadline: deadline)
+ let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ try controller.finish(process)
+
+ return SSHResult(
+ exitCode: process.terminationStatus,
+ output: Self.filteredSSHOutput(outputData)
+ )
+ }
+
+ private func cleanupStagingDirectory(_ stagingDirectory: String) {
+ let command = """
+ if [ -d "$HOME/\(stagingDirectory)" ]; then \
+ find "$HOME/\(stagingDirectory)" -depth -delete; \
+ fi
+ """
+ _ = try? execute(command: command, timeout: 15)
+ }
+
+ private static func shellQuote(_ value: String) -> String {
+ "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'"
+ }
+
+ private static func filteredSSHOutput(_ data: Data) -> String {
+ let output = String(data: data, encoding: .utf8) ?? ""
+ return output.components(separatedBy: "\n")
+ .filter { line in
+ !line.contains("Warning: Permanently added")
+ && !line.contains("known_hosts")
+ && !line.trimmingCharacters(in: .whitespaces).isEmpty
+ }
+ .joined(separator: "\n")
+ }
+
/// Creates a temporary script that outputs the password for SSH_ASKPASS
private func createAskpassScript() throws -> String {
let tempDir = FileManager.default.temporaryDirectory
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index db1e4549c5..a42457fcf2 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -390,6 +390,12 @@ class VM {
throw VMError.internalError("The VM session is no longer available")
}
try await self.addSharedFolder(url, readOnly: readOnly)
+ },
+ copyFilesToGuestDesktop: { [weak self] urls in
+ guard let self else {
+ throw VMError.internalError("The VM session is no longer available")
+ }
+ try await self.copyFilesToGuestDesktop(urls)
}
)
displayContext = context
@@ -558,6 +564,49 @@ class VM {
}
}
+ private func copyFilesToGuestDesktop(_ urls: [URL]) async throws {
+ guard !urls.isEmpty else {
+ throw VMError.internalError("Drop at least one file or folder")
+ }
+ for url in urls {
+ guard url.isFileURL, FileManager.default.fileExists(atPath: url.path) else {
+ throw VMError.internalError("A dropped item is no longer available")
+ }
+ }
+
+ guard virtualizationService?.state == .running else {
+ throw SSHError.vmNotRunning(vmDirContext.name)
+ }
+ guard let macAddress = vmDirContext.config.macAddress else {
+ throw SSHError.noIPAddress(vmDirContext.name)
+ }
+ let ipAddress = await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ continuation.resume(
+ returning: DHCPLeaseParser.getIPAddress(forMAC: macAddress)
+ )
+ }
+ }
+ guard let ipAddress, !ipAddress.isEmpty else {
+ throw SSHError.noIPAddress(vmDirContext.name)
+ }
+
+ let client = SystemSSHClient(
+ host: ipAddress,
+ port: 22,
+ user: "lume",
+ password: "lume"
+ )
+ try await client.copyToRemoteDesktop(urls)
+
+ Logger.info(
+ "Copied dropped items to VM Desktop",
+ metadata: [
+ "name": vmDirContext.name,
+ "count": "\(urls.count)",
+ ])
+ }
+
private func cleanupSession() async {
guard !sessionCleanedUp else { return }
sessionCleanedUp = true
diff --git a/libs/lume/src/VM/VMDisplayPresenter.swift b/libs/lume/src/VM/VMDisplayPresenter.swift
index 1f1cc3ddb3..00c85d9609 100644
--- a/libs/lume/src/VM/VMDisplayPresenter.swift
+++ b/libs/lume/src/VM/VMDisplayPresenter.swift
@@ -10,6 +10,7 @@ struct VMDisplayContext {
let copyFromGuest: (@MainActor () async throws -> Void)?
let pasteIntoGuest: (@MainActor () async throws -> Void)?
let addSharedFolder: (@MainActor (URL, Bool) async throws -> Void)?
+ let copyFilesToGuestDesktop: (@MainActor ([URL]) async throws -> Void)?
init(
virtualMachine: VZVirtualMachine?,
@@ -18,7 +19,8 @@ struct VMDisplayContext {
vmName: String = "Lume VM",
copyFromGuest: (@MainActor () async throws -> Void)? = nil,
pasteIntoGuest: (@MainActor () async throws -> Void)? = nil,
- addSharedFolder: (@MainActor (URL, Bool) async throws -> Void)? = nil
+ addSharedFolder: (@MainActor (URL, Bool) async throws -> Void)? = nil,
+ copyFilesToGuestDesktop: (@MainActor ([URL]) async throws -> Void)? = nil
) {
self.virtualMachine = virtualMachine
self.vncURL = vncURL
@@ -27,6 +29,7 @@ struct VMDisplayContext {
self.copyFromGuest = copyFromGuest
self.pasteIntoGuest = pasteIntoGuest
self.addSharedFolder = addSharedFolder
+ self.copyFilesToGuestDesktop = copyFilesToGuestDesktop
}
}
@@ -82,9 +85,38 @@ private enum NativeClipboardShortcut {
case paste
}
+@MainActor
+enum NativeFileDrop {
+ static func fileURLs(from pasteboard: NSPasteboard) -> [URL] {
+ let options: [NSPasteboard.ReadingOptionKey: Any] = [
+ .urlReadingFileURLsOnly: true
+ ]
+ let objects = pasteboard.readObjects(
+ forClasses: [NSURL.self],
+ options: options
+ ) as? [NSURL]
+ return (objects ?? []).map { $0 as URL }.filter(\.isFileURL)
+ }
+}
+
@MainActor
private final class NativeVirtualMachineView: VZVirtualMachineView {
var onClipboardShortcut: ((NativeClipboardShortcut) -> Bool)?
+ var onFileDragEntered: (() -> Void)?
+ var canAcceptFileDrop: (() -> Bool)?
+ var onFileDrop: (([URL]) -> Bool)?
+ private var cachedDragSequenceNumber: Int?
+ private var cachedDragURLs: [URL] = []
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ registerForDraggedTypes([.fileURL])
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ registerForDraggedTypes([.fileURL])
+ }
override func keyDown(with event: NSEvent) {
let modifiers = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
@@ -104,6 +136,55 @@ private final class NativeVirtualMachineView: VZVirtualMachineView {
}
super.keyDown(with: event)
}
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard onFileDrop != nil, canAcceptFileDrop?() != false,
+ !fileURLs(from: sender).isEmpty
+ else {
+ return []
+ }
+ onFileDragEntered?()
+ return .copy
+ }
+
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard onFileDrop != nil, canAcceptFileDrop?() != false,
+ !fileURLs(from: sender).isEmpty
+ else {
+ return []
+ }
+ return .copy
+ }
+
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ let urls = fileURLs(from: sender)
+ defer { resetCachedDrag() }
+ guard !urls.isEmpty, let onFileDrop else { return false }
+ return onFileDrop(urls)
+ }
+
+ override func draggingExited(_ sender: NSDraggingInfo?) {
+ resetCachedDrag()
+ }
+
+ override func concludeDragOperation(_ sender: NSDraggingInfo?) {
+ resetCachedDrag()
+ }
+
+ private func fileURLs(from sender: NSDraggingInfo) -> [URL] {
+ let sequenceNumber = sender.draggingSequenceNumber
+ if cachedDragSequenceNumber == sequenceNumber {
+ return cachedDragURLs
+ }
+ cachedDragSequenceNumber = sequenceNumber
+ cachedDragURLs = NativeFileDrop.fileURLs(from: sender.draggingPasteboard)
+ return cachedDragURLs
+ }
+
+ private func resetCachedDrag() {
+ cachedDragSequenceNumber = nil
+ cachedDragURLs = []
+ }
}
private extension NSToolbarItem.Identifier {
@@ -130,6 +211,9 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
private var copyFromGuestAction: (@MainActor () async throws -> Void)?
private var pasteIntoGuestAction: (@MainActor () async throws -> Void)?
private var addSharedFolderAction: (@MainActor (URL, Bool) async throws -> Void)?
+ private var copyFilesToGuestDesktopAction: (@MainActor ([URL]) async throws -> Void)?
+ private var fileDropTask: Task<Void, Never>?
+ private var fileDropInProgress = false
private var captureSystemKeysItem: NSMenuItem?
private var captureSystemKeysToolbarItem: NSToolbarItem?
private var showWindowItem: NSMenuItem?
@@ -146,6 +230,7 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
copyFromGuestAction = context.copyFromGuest
pasteIntoGuestAction = context.pasteIntoGuest
addSharedFolderAction = context.addSharedFolder
+ copyFilesToGuestDesktopAction = context.copyFilesToGuestDesktop
let application = NSApplication.shared
if application.activationPolicy() != .regular {
@@ -182,7 +267,11 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
func hide() {
overlayTask?.cancel()
overlayTask = nil
+ fileDropTask?.cancel()
machineView?.onClipboardShortcut = nil
+ machineView?.onFileDragEntered = nil
+ machineView?.canAcceptFileDrop = nil
+ machineView?.onFileDrop = nil
machineView?.virtualMachine = nil
window?.delegate = nil
window?.orderOut(nil)
@@ -195,6 +284,10 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
copyFromGuestAction = nil
pasteIntoGuestAction = nil
addSharedFolderAction = nil
+ copyFilesToGuestDesktopAction = nil
+ if fileDropTask == nil {
+ fileDropInProgress = false
+ }
captureSystemKeysItem = nil
captureSystemKeysToolbarItem = nil
showWindowItem = nil
@@ -249,6 +342,20 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
}
return true
}
+ view.onFileDragEntered = { [weak self] in
+ self?.showOverlay("Drop to copy to the VM Desktop")
+ }
+ view.canAcceptFileDrop = { [weak self] in
+ guard let self else { return false }
+ return copyFilesToGuestDesktopAction != nil && !fileDropInProgress
+ }
+ view.onFileDrop = { [weak self] urls in
+ guard let self, copyFilesToGuestDesktopAction != nil, !fileDropInProgress else {
+ return false
+ }
+ requestFileDrop(urls)
+ return true
+ }
container.addSubview(view)
let overlayView = NSVisualEffectView()
@@ -454,6 +561,50 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
}
}
+ private func requestFileDrop(_ urls: [URL]) {
+ guard let copyFilesToGuestDesktopAction, !fileDropInProgress else {
+ showOverlay("File transfer unavailable")
+ return
+ }
+
+ fileDropInProgress = true
+ let itemDescription = urls.count == 1 ? urls[0].lastPathComponent : "\(urls.count) items"
+ showOverlay("Copying \(itemDescription) to Desktop…", automaticallyHides: false)
+ let scopedURLs = urls.filter { $0.startAccessingSecurityScopedResource() }
+
+ fileDropTask = Task { @MainActor [weak self] in
+ defer {
+ for url in scopedURLs {
+ url.stopAccessingSecurityScopedResource()
+ }
+ }
+ guard let self else { return }
+ defer {
+ self.fileDropInProgress = false
+ self.fileDropTask = nil
+ }
+
+ do {
+ try await copyFilesToGuestDesktopAction(urls)
+ self.showOverlay("Copied to VM Desktop")
+ } catch is CancellationError {
+ Logger.info(
+ "Native file drop cancelled",
+ metadata: ["vm": self.vmName, "count": "\(urls.count)"]
+ )
+ } catch {
+ Logger.error(
+ "Native file drop failed",
+ metadata: [
+ "vm": self.vmName,
+ "count": "\(urls.count)",
+ "error": error.localizedDescription,
+ ])
+ self.showOverlay("File copy failed — \(error.localizedDescription)")
+ }
+ }
+ }
+
private func requestCopyFromGuest() {
guard let copyFromGuestAction else {
showOverlay("Copy unavailable")
@@ -486,13 +637,15 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
}
}
- private func showOverlay(_ message: String) {
+ private func showOverlay(_ message: String, automaticallyHides: Bool = true) {
guard let overlayView, let overlayLabel else { return }
overlayTask?.cancel()
+ overlayTask = nil
overlayLabel.stringValue = message
overlayView.alphaValue = 1
overlayView.isHidden = false
+ guard automaticallyHides else { return }
overlayTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .seconds(1.2))
guard !Task.isCancelled, let self, let overlayView = self.overlayView else { return }
diff --git a/libs/lume/tests/NativeFileDropTests.swift b/libs/lume/tests/NativeFileDropTests.swift
new file mode 100644
index 0000000000..566aa0bb77
--- /dev/null
+++ b/libs/lume/tests/NativeFileDropTests.swift
@@ -0,0 +1,220 @@
+import AppKit
+import Foundation
+import Testing
+
+@testable import lume
+
+@MainActor
+@Test("Native file drops accept local file and directory URLs only")
+func nativeFileDropExtractsLocalURLs() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let file = root.appendingPathComponent("File with spaces.txt")
+ let directory = root.appendingPathComponent("Folder")
+ try Data("drop test".utf8).write(to: file)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
+
+ let pasteboard = NSPasteboard(name: .init("ai.cua.lume.tests.file-drop.\(UUID().uuidString)"))
+ pasteboard.clearContents()
+ #expect(
+ pasteboard.writeObjects([
+ file as NSURL,
+ directory as NSURL,
+ URL(string: "https://example.com/not-a-file")! as NSURL,
+ ]))
+
+ let urls = NativeFileDrop.fileURLs(from: pasteboard)
+
+ #expect(urls == [file, directory])
+}
+
+@Test("SCP safely checks guest Desktop names before transfer")
+func scpDesktopPreparationCommand() {
+ let client = SystemSSHClient(host: "192.168.64.24")
+ let command = client.desktopPreparationCommand(
+ itemNames: ["Report's.txt"],
+ stagingDirectory: ".lume-drop-test"
+ )
+
+ #expect(command.hasPrefix("set -e; mkdir -p \"$HOME/Desktop\""))
+ #expect(command.contains(#""$HOME/Desktop/"'Report'\''s.txt'"#))
+ #expect(command.contains("exit 73"))
+ #expect(command.hasSuffix("mkdir \"$HOME/.lume-drop-test\""))
+}
+
+@Test("SCP keeps dropped paths as distinct arguments and targets the guest Desktop")
+func scpFileDropArguments() throws {
+ let client = SystemSSHClient(
+ host: "192.168.64.24",
+ port: 2222,
+ user: "lume",
+ password: "secret"
+ )
+ let sourcePaths = [
+ "/tmp/File with spaces.txt",
+ "/tmp/--looks-like-an-option",
+ ]
+
+ let arguments = client.scpArguments(
+ sourcePaths: sourcePaths,
+ destinationDirectory: "Desktop"
+ )
+ let separator = try #require(arguments.firstIndex(of: "--"))
+
+ #expect(arguments.contains("-r"))
+ #expect(arguments.contains("-P"))
+ #expect(arguments.contains("2222"))
+ #expect(arguments.contains("ServerAliveInterval=15"))
+ #expect(arguments.contains("ServerAliveCountMax=4"))
+ #expect(Array(arguments[(separator + 1)..<(arguments.count - 1)]) == sourcePaths)
+ #expect(arguments.last == "[email protected]:Desktop/")
+}
+
+@Test("SCP omits a port override for standard SSH")
+func scpFileDropDefaultPortArguments() {
+ let client = SystemSSHClient(host: "192.168.64.24")
+ let arguments = client.scpArguments(
+ sourcePaths: ["/tmp/example.txt"],
+ destinationDirectory: "Desktop"
+ )
+
+ #expect(!arguments.contains("-P"))
+}
+
+@Test("SCP rejects an empty file drop before launching a process")
+func scpRejectsEmptyFileDrop() async {
+ let client = SystemSSHClient(host: "192.168.64.24")
+
+ await #expect(throws: RemoteDesktopCopyError.self) {
+ try await client.copyToRemoteDesktop([])
+ }
+}
+
+@Test("SCP rejects duplicate destination names before connecting")
+func scpRejectsDuplicateDestinationNames() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ let first = root.appendingPathComponent("first/Same.txt")
+ let second = root.appendingPathComponent("second/Same.txt")
+ try FileManager.default.createDirectory(
+ at: first.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try FileManager.default.createDirectory(
+ at: second.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try Data().write(to: first)
+ try Data().write(to: second)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let client = SystemSSHClient(host: "invalid.invalid")
+ do {
+ try await client.copyToRemoteDesktop([first, second])
+ Issue.record("Expected duplicate destination names to be rejected")
+ } catch let error as RemoteDesktopCopyError {
+ #expect(error.localizedDescription == "Dropped items must have unique names")
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+}
+
+@Test("A pre-cancelled file copy cannot launch a process")
+func scpCancellationIsObservable() {
+ let controller = CopyProcessController()
+ controller.cancel()
+
+ #expect(throws: CancellationError.self) {
+ try controller.register(Process())
+ }
+}
+
+@Test("File-copy errors are ready for user-facing overlays")
+func scpFileCopyErrorDescriptions() {
+ #expect(
+ RemoteDesktopCopyError.destinationExists.localizedDescription
+ == "An item with the same name already exists on the VM Desktop"
+ )
+ #expect(RemoteDesktopCopyError.timedOut.localizedDescription == "File copy timed out")
+}
+
+@Test("SCP commits staged items to the Desktop with fail-fast shell semantics")
+func scpDesktopCommitCommand() {
+ let client = SystemSSHClient(host: "192.168.64.24")
+ let command = client.desktopCommitCommand(
+ itemNames: ["Report's.txt"],
+ stagingDirectory: ".lume-drop-1234"
+ )
+
+ #expect(command.hasPrefix("set -e; "))
+ #expect(command.contains(#""$HOME/.lume-drop-1234/"'Report'\''s.txt'"#))
+ #expect(command.contains("mv -n"))
+ #expect(command.contains("exit 73"))
+ #expect(command.contains("trap rollback EXIT"))
+ #expect(command.hasSuffix("trap - EXIT"))
+}
+
+@Test("One staging directory is threaded through prepare, transfer, and commit")
+func scpStagingDirectoryConsistency() {
+ let client = SystemSSHClient(host: "192.168.64.24")
+ let stagingDirectory = ".lume-drop-fixed"
+ let preparation = client.desktopPreparationCommand(
+ itemNames: ["example.txt"],
+ stagingDirectory: stagingDirectory
+ )
+ let transfer = client.scpArguments(
+ sourcePaths: ["/tmp/example.txt"],
+ destinationDirectory: stagingDirectory
+ )
+ let commit = client.desktopCommitCommand(
+ itemNames: ["example.txt"],
+ stagingDirectory: stagingDirectory
+ )
+
+ #expect(preparation.contains(stagingDirectory))
+ #expect(transfer.last == "[email protected]:\(stagingDirectory)/")
+ #expect(commit.contains(stagingDirectory))
+}
+
+@Test("A late Desktop collision rolls every staged item back")
+func scpDesktopCommitRollsBackOnCollision() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ let desktop = root.appendingPathComponent("Desktop")
+ let stagingDirectory = ".lume-drop-rollback"
+ let staging = root.appendingPathComponent(stagingDirectory)
+ try FileManager.default.createDirectory(at: desktop, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try Data("first".utf8).write(to: staging.appendingPathComponent("first.txt"))
+ try Data("second".utf8).write(to: staging.appendingPathComponent("second.txt"))
+ try Data("existing".utf8).write(to: desktop.appendingPathComponent("second.txt"))
+
+ let client = SystemSSHClient(host: "192.168.64.24")
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/sh")
+ process.arguments = [
+ "-c",
+ client.desktopCommitCommand(
+ itemNames: ["first.txt", "second.txt"],
+ stagingDirectory: stagingDirectory
+ ),
+ ]
+ var environment = ProcessInfo.processInfo.environment
+ environment["HOME"] = root.path
+ process.environment = environment
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+
+ #expect(process.terminationStatus == 73)
+ #expect(FileManager.default.fileExists(atPath: staging.appendingPathComponent("first.txt").path))
+ #expect(FileManager.default.fileExists(atPath: staging.appendingPathComponent("second.txt").path))
+ #expect(!FileManager.default.fileExists(atPath: desktop.appendingPathComponent("first.txt").path))
+ #expect(
+ try String(contentsOf: desktop.appendingPathComponent("second.txt"), encoding: .utf8)
+ == "existing"
+ )
+}
diff --git a/libs/lume/tests/VMDisplayLifecycleTests.swift b/libs/lume/tests/VMDisplayLifecycleTests.swift
index c587fe6622..04be4f4691 100644
--- a/libs/lume/tests/VMDisplayLifecycleTests.swift
+++ b/libs/lume/tests/VMDisplayLifecycleTests.swift
@@ -11,10 +11,12 @@ private enum PresenterTestError: Error {
private final class MockDisplayPresenter: VMDisplayPresenter {
private(set) var showCount = 0
private(set) var hideCount = 0
+ private(set) var lastContext: VMDisplayContext?
var showError: Error?
func show(context: VMDisplayContext) async throws {
showCount += 1
+ lastContext = context
if let showError { throw showError }
}
@@ -100,6 +102,7 @@ func presenterSelectionAndGuestShutdownCleanup() async throws {
#expect(selectedMode == mode)
#expect(presenter.showCount == 1)
#expect(presenter.hideCount == 1)
+ #expect(presenter.lastContext?.copyFilesToGuestDesktop != nil)
#expect(vnc.startCallCount == 1)
#expect(vnc.stopCallCount == 1)
#expect(service.stopCallCount == 0)