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.

fix(lume): make native clipboard actions reliable

Francesco Bonacci7ba697f1d355
diff --git a/libs/lume/src/Clipboard/ClipboardWatcher.swift b/libs/lume/src/Clipboard/ClipboardWatcher.swift
index c3e767aeb2..440a5d09eb 100644
--- a/libs/lume/src/Clipboard/ClipboardWatcher.swift
+++ b/libs/lume/src/Clipboard/ClipboardWatcher.swift
@@ -6,17 +6,23 @@ enum ClipboardSyncError: LocalizedError {
case emptyClipboard
case contentTooLarge
case transferFailed
+ case guestCopyTimedOut
+ case transferInProgress
var errorDescription: String? {
switch self {
case .unavailable:
return "Clipboard sync is waiting for guest SSH access."
case .emptyClipboard:
- return "The clipboard does not contain text or an image."
+ return "The clipboard does not contain supported text or image data."
case .contentTooLarge:
return "The clipboard content is too large to transfer."
case .transferFailed:
return "The clipboard transfer failed."
+ case .guestCopyTimedOut:
+ return "The VM did not copy new content. Select something in the VM and try again."
+ case .transferInProgress:
+ return "Another clipboard transfer is already in progress."
}
}
}
@@ -47,6 +53,7 @@ private enum ClipboardPayload: Equatable, Sendable {
public actor ClipboardWatcher {
private let vmName: String
private let storage: String?
+ private let macAddress: String?
private var watchTask: Task<Void, Never>?
private var isRunning = false
@@ -59,6 +66,10 @@ public actor ClipboardWatcher {
// Cached SSH client to avoid reconnecting every poll cycle.
private var cachedSSHClient: SSHClient?
private var cachedIPAddress: String?
+ private var sshCommandInProgress = false
+ private var manualTransferInProgress = false
+ private var manualTransferRequested = false
+ private var automaticSyncInProgress = false
// Error suppression to avoid flooding logs with repeated failures.
private var consecutiveFailures = 0
@@ -70,9 +81,10 @@ public actor ClipboardWatcher {
private static let maxTextSize = 1_000_000
private static let maxImageSize = 10_000_000
- public init(vmName: String, storage: String?) {
+ public init(vmName: String, storage: String?, macAddress: String? = nil) {
self.vmName = vmName
self.storage = storage
+ self.macAddress = macAddress
}
public func start() {
@@ -103,6 +115,35 @@ public actor ClipboardWatcher {
pendingHostPayload = nil
}
+ /// Prevent the automatic watcher from changing either pasteboard between a
+ /// manual action's baseline read, injected shortcut, and payload transfer.
+ func beginManualTransfer() async throws {
+ manualTransferRequested = true
+ do {
+ // A command may spend five seconds connecting before its normal
+ // 30-second image timeout. Bound the wait without rejecting a
+ // healthy in-flight poll at its documented ceiling.
+ for _ in 0..<1_800 {
+ try Task.checkCancellation()
+ if !manualTransferInProgress && !automaticSyncInProgress {
+ manualTransferRequested = false
+ manualTransferInProgress = true
+ return
+ }
+ try await Task.sleep(for: .milliseconds(25))
+ }
+ } catch {
+ manualTransferRequested = false
+ throw error
+ }
+ manualTransferRequested = false
+ throw ClipboardSyncError.transferInProgress
+ }
+
+ func endManualTransfer() {
+ manualTransferInProgress = false
+ }
+
/// Immediately copies host text or image data into the guest clipboard.
func pushHostClipboardToVM() async throws {
let snapshot = await readHostClipboard()
@@ -125,16 +166,11 @@ public actor ClipboardWatcher {
}
/// Immediately reads guest text or image data into the host clipboard.
- /// When a baseline is supplied, waits briefly for the guest's Copy command.
+ /// When a baseline is supplied, requires the guest's Copy command to
+ /// advance the pasteboard generation before reading its payload.
func pullVMClipboardToHost(after baseline: Int? = nil) async throws {
if let baseline {
- for _ in 0..<15 {
- let current = try await readVMChangeCount()
- if current != baseline {
- break
- }
- try await Task.sleep(for: .milliseconds(100))
- }
+ try await waitForVMClipboardChange(after: baseline)
}
let payload = try await readPayloadFromVM()
@@ -162,7 +198,16 @@ public actor ClipboardWatcher {
}
private func syncBidirectional() async {
+ // Manual Copy/Paste is a multi-step transaction. Do not let polling
+ // overwrite a pasteboard or satisfy a change-count wait in the middle.
+ guard !manualTransferRequested, !manualTransferInProgress, !automaticSyncInProgress else {
+ return
+ }
+ automaticSyncInProgress = true
+ defer { automaticSyncInProgress = false }
+
let hostClipboard = await readHostClipboard()
+ guard !manualTransferRequested else { return }
if hostClipboard.changeCount != lastHostChangeCount {
lastHostChangeCount = hostClipboard.changeCount
if let payload = hostClipboard.payload,
@@ -179,9 +224,11 @@ public actor ClipboardWatcher {
if let pendingHostPayload {
do {
try await writePayloadToVM(pendingHostPayload)
+ guard !manualTransferRequested else { return }
lastVMPayload = pendingHostPayload
self.pendingHostPayload = nil
lastVMChangeCount = try? await readVMChangeCount()
+ guard !manualTransferRequested else { return }
resetFailureState()
} catch {
handleSyncError("Failed to sync clipboard to VM", error: error)
@@ -191,6 +238,7 @@ public actor ClipboardWatcher {
do {
let currentChangeCount = try await readVMChangeCount()
+ guard !manualTransferRequested else { return }
guard let previousChangeCount = lastVMChangeCount else {
lastVMChangeCount = currentChangeCount
return
@@ -199,6 +247,7 @@ public actor ClipboardWatcher {
lastVMChangeCount = currentChangeCount
let payload = try await readPayloadFromVM()
+ guard !manualTransferRequested else { return }
guard payload != lastVMPayload,
payload != lastHostPayload,
isValidSize(payload) else {
@@ -220,10 +269,6 @@ public actor ClipboardWatcher {
}
private func writePayloadToVM(_ payload: ClipboardPayload) async throws {
- guard let sshClient = await getSSHClient() else {
- throw ClipboardSyncError.unavailable
- }
-
let command: String
let timeout: TimeInterval
switch payload {
@@ -258,7 +303,7 @@ public actor ClipboardWatcher {
timeout = 30
}
- let result = try await sshClient.execute(command: command, timeout: timeout)
+ let result = try await executeSSHCommand(command: command, timeout: timeout)
guard result.exitCode == 0 else {
throw ClipboardSyncError.transferFailed
}
@@ -272,12 +317,9 @@ public actor ClipboardWatcher {
}
private func readVMChangeCount() async throws -> Int {
- guard let sshClient = await getSSHClient() else {
- throw ClipboardSyncError.unavailable
- }
let command =
"osascript -l JavaScript -e 'ObjC.import(\"AppKit\"); $.NSPasteboard.generalPasteboard.changeCount'"
- let result = try await sshClient.execute(command: command, timeout: 5)
+ let result = try await executeSSHCommand(command: command, timeout: 5)
guard result.exitCode == 0,
let value = Int(result.output.trimmingCharacters(in: .whitespacesAndNewlines)) else {
throw ClipboardSyncError.transferFailed
@@ -285,11 +327,53 @@ public actor ClipboardWatcher {
return value
}
- private func readPayloadFromVM() async throws -> ClipboardPayload {
- guard let sshClient = await getSSHClient() else {
- throw ClipboardSyncError.unavailable
+ /// Wait for the guest pasteboard generation to advance after Command-C.
+ /// This is internal so the timeout behavior can be regression-tested without
+ /// requiring a VM or live SSH server.
+ static func guestClipboardWaitCommand(
+ after baseline: Int,
+ attempts: Int = 25,
+ changeCountExpression: String = "Number(pasteboard.changeCount)"
+ ) -> String {
+ let boundedAttempts = max(1, attempts)
+ return """
+ /usr/bin/osascript -l JavaScript -e '\
+ ObjC.import("AppKit"); \
+ ObjC.import("stdlib"); \
+ const pasteboard = $.NSPasteboard.generalPasteboard; \
+ const baseline = \(baseline); \
+ const attempts = \(boundedAttempts); \
+ for (let attempt = 0; attempt < attempts; attempt += 1) { \
+ const current = \(changeCountExpression); \
+ if (current !== baseline) { console.log(String(current)); $.exit(0); } \
+ $.NSThread.sleepForTimeInterval(0.1); \
+ } \
+ $.exit(75);'
+ """
+ }
+
+ /// Wait in one guest-side command instead of opening a new SSH connection
+ /// for every poll. Besides being faster, this makes a missed guest shortcut
+ /// an explicit timeout rather than allowing stale clipboard content through.
+ private func waitForVMClipboardChange(after baseline: Int) async throws {
+ let result: SSHResult
+ do {
+ result = try await executeSSHCommand(
+ command: Self.guestClipboardWaitCommand(after: baseline),
+ timeout: 5
+ )
+ } catch SSHError.timeout {
+ throw ClipboardSyncError.guestCopyTimedOut
+ }
+ if result.exitCode == 75 {
+ throw ClipboardSyncError.guestCopyTimedOut
}
+ guard result.exitCode == 0 else {
+ throw ClipboardSyncError.transferFailed
+ }
+ }
+ private func readPayloadFromVM() async throws -> ClipboardPayload {
let path = "/tmp/lume-clipboard-\(UUID().uuidString).png"
let command = """
if /usr/bin/osascript \\
@@ -304,10 +388,12 @@ public actor ClipboardWatcher {
printf 'TEXT\\n'
pbpaste | base64
fi
+ lume_status=$?
rm -f '\(path)'
+ exit $lume_status
"""
- let result = try await sshClient.execute(command: command, timeout: 30)
+ let result = try await executeSSHCommand(command: command, timeout: 30)
guard result.exitCode == 0,
let separator = result.output.firstIndex(of: "\n") else {
throw ClipboardSyncError.transferFailed
@@ -385,6 +471,50 @@ public actor ClipboardWatcher {
}
}
+ private func executeSSHCommand(
+ command: String,
+ timeout: TimeInterval
+ ) async throws -> SSHResult {
+ try Task.checkCancellation()
+ guard !sshCommandInProgress else {
+ throw ClipboardSyncError.transferInProgress
+ }
+
+ sshCommandInProgress = true
+ defer { sshCommandInProgress = false }
+
+ for attempt in 0..<2 {
+ guard let sshClient = await getSSHClient() else {
+ throw ClipboardSyncError.unavailable
+ }
+ do {
+ let result = try await sshClient.execute(command: command, timeout: timeout)
+ try Task.checkCancellation()
+ return result
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch let error as SSHError {
+ guard case .connectionFailed = error, attempt == 0,
+ !manualTransferRequested else {
+ throw error
+ }
+ cachedSSHClient = nil
+ cachedIPAddress = nil
+ Logger.debug(
+ "Retrying clipboard SSH command after a connection failure",
+ metadata: [
+ "vm": vmName,
+ "error": error.localizedDescription,
+ ])
+ try await Task.sleep(for: .milliseconds(250))
+ } catch {
+ throw error
+ }
+ }
+
+ throw ClipboardSyncError.transferFailed
+ }
+
private func handleSyncError(_ message: String, error: Error) {
cachedSSHClient = nil
consecutiveFailures += 1
@@ -413,27 +543,41 @@ public actor ClipboardWatcher {
}
private func getSSHClient() async -> SSHClient? {
+ if let cachedSSHClient, cachedIPAddress != nil {
+ return cachedSSHClient
+ }
+
do {
- let vmDetails = try await MainActor.run {
- let controller = LumeController()
- return try controller.getDetails(name: vmName, storage: storage)
+ let ipAddress: String?
+ if let macAddress {
+ ipAddress = await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ continuation.resume(
+ returning: DHCPLeaseParser.getIPAddress(forMAC: macAddress)
+ )
+ }
+ }
+ } else {
+ let vmDetails = try await MainActor.run {
+ let controller = LumeController()
+ return try controller.getDetails(name: vmName, storage: storage)
+ }
+ guard vmDetails.status == "running", vmDetails.sshAvailable == true else {
+ return nil
+ }
+ ipAddress = vmDetails.ipAddress
}
- guard vmDetails.status == "running",
- let ipAddress = vmDetails.ipAddress, !ipAddress.isEmpty,
- vmDetails.sshAvailable == true else {
+ guard let ipAddress, !ipAddress.isEmpty else {
return nil
}
- if let cachedSSHClient, cachedIPAddress == ipAddress {
- return cachedSSHClient
- }
-
let client = SSHClient(
host: ipAddress,
port: 22,
user: "lume",
- password: "lume"
+ password: "lume",
+ connectTimeout: 5
)
cachedSSHClient = client
cachedIPAddress = ipAddress
diff --git a/libs/lume/src/Commands/DetachedRun.swift b/libs/lume/src/Commands/DetachedRun.swift
index 695f3e6207..043fe1826e 100644
--- a/libs/lume/src/Commands/DetachedRun.swift
+++ b/libs/lume/src/Commands/DetachedRun.swift
@@ -51,7 +51,9 @@ enum DetachedVMRunner {
fileURLWithPath: FileManager.default.currentDirectoryPath,
isDirectory: true
)
- process.environment = ProcessInfo.processInfo.environment
+ var environment = ProcessInfo.processInfo.environment
+ environment["NSUnbufferedIO"] = "YES"
+ process.environment = environment
process.standardInput = FileHandle.nullDevice
process.standardOutput = logHandle
process.standardError = logHandle
diff --git a/libs/lume/src/SSH/SSHClient.swift b/libs/lume/src/SSH/SSHClient.swift
index ec9c6f6cc3..8b08accbd1 100644
--- a/libs/lume/src/SSH/SSHClient.swift
+++ b/libs/lume/src/SSH/SSHClient.swift
@@ -21,18 +21,21 @@ public actor SSHClient {
private let port: Int
private let user: String
private let password: String
+ private let connectTimeout: TimeInterval
private let eventLoopGroup: MultiThreadedEventLoopGroup
public init(
host: String,
port: UInt16 = 22,
user: String = "lume",
- password: String = "lume"
+ password: String = "lume",
+ connectTimeout: TimeInterval = 30
) {
self.host = host
self.port = Int(port)
self.user = user
self.password = password
+ self.connectTimeout = connectTimeout
self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
@@ -155,7 +158,7 @@ public actor SSHClient {
static func makeChildChannelFuture(
handlerFuture: EventLoopFuture<NIOSSHHandler>,
eventLoop: EventLoop,
- initialize: @escaping (NIOSSHHandler, EventLoopPromise<Channel>) -> Void
+ initialize: @escaping @Sendable (NIOSSHHandler, EventLoopPromise<Channel>) -> Void
) -> EventLoopFuture<Channel> {
handlerFuture.flatMap { sshHandler in
let childChannelPromise = eventLoop.makePromise(of: Channel.self)
@@ -188,7 +191,7 @@ public actor SSHClient {
}
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelOption(ChannelOptions.socket(SocketOptionLevel(IPPROTO_TCP), TCP_NODELAY), value: 1)
- .connectTimeout(.seconds(30))
+ .connectTimeout(.seconds(max(1, Int64(connectTimeout.rounded(.up)))))
do {
return try await bootstrap.connect(host: host, port: port).get()
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index a42457fcf2..57606e7731 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -56,6 +56,7 @@ class VM {
private var nativeAttachRegistered = false
private var activeSharedDirectories: [SharedDirectory] = []
private var scopedSharedDirectoryURLs: [URL] = []
+ private var clipboardTransferInProgress = false
private var sessionCleanedUp = true
internal let virtualizationServiceFactory:
(VMVirtualizationServiceContext) throws -> VMVirtualizationService
@@ -493,29 +494,72 @@ class VM {
guard clipboardWatcher == nil else { return }
let watcher = ClipboardWatcher(
vmName: vmDirContext.name,
- storage: vmDirContext.storage
+ storage: vmDirContext.storage,
+ macAddress: vmDirContext.config.macAddress
)
clipboardWatcher = watcher
await watcher.start()
}
+ private func withManualClipboardTransfer<T: Sendable>(
+ _ watcher: ClipboardWatcher,
+ operation: () async throws -> T
+ ) async throws -> T {
+ guard !clipboardTransferInProgress else {
+ throw ClipboardSyncError.transferInProgress
+ }
+
+ clipboardTransferInProgress = true
+ defer { clipboardTransferInProgress = false }
+
+ try await watcher.beginManualTransfer()
+ do {
+ let result = try await operation()
+ await watcher.endManualTransfer()
+ return result
+ } catch {
+ await watcher.endManualTransfer()
+ throw error
+ }
+ }
+
private func copyClipboardFromGuest() async throws {
guard let clipboardWatcher else {
throw ClipboardSyncError.unavailable
}
-
- let baseline = try? await clipboardWatcher.vmClipboardChangeCount()
- try await sendGuestClipboardShortcut("c")
- try await clipboardWatcher.pullVMClipboardToHost(after: baseline)
+ try await withManualClipboardTransfer(clipboardWatcher) {
+ let baseline = try await clipboardWatcher.vmClipboardChangeCount()
+ try Task.checkCancellation()
+ for attempt in 0..<2 {
+ try await sendGuestClipboardShortcut("c")
+ try Task.checkCancellation()
+ do {
+ try await clipboardWatcher.pullVMClipboardToHost(after: baseline)
+ try Task.checkCancellation()
+ return
+ } catch ClipboardSyncError.guestCopyTimedOut where attempt == 0 {
+ Logger.debug(
+ "Guest copy did not update the pasteboard; retrying shortcut",
+ metadata: ["vm": vmDirContext.name]
+ )
+ try await Task.sleep(for: .milliseconds(150))
+ }
+ }
+ }
}
private func pasteClipboardIntoGuest() async throws {
guard let clipboardWatcher else {
throw ClipboardSyncError.unavailable
}
-
- try await clipboardWatcher.pushHostClipboardToVM()
- try await sendGuestClipboardShortcut("v")
+ try await withManualClipboardTransfer(clipboardWatcher) {
+ try await clipboardWatcher.pushHostClipboardToVM()
+ try Task.checkCancellation()
+ // Give the guest pasteboard server a moment to publish the new value
+ // before delivering Command-V to the foreground application.
+ try await Task.sleep(for: .milliseconds(100))
+ try await sendGuestClipboardShortcut("v")
+ }
}
private func sendGuestClipboardShortcut(_ character: Character) async throws {
diff --git a/libs/lume/src/VM/VMDisplayPresenter.swift b/libs/lume/src/VM/VMDisplayPresenter.swift
index 00c85d9609..a337941540 100644
--- a/libs/lume/src/VM/VMDisplayPresenter.swift
+++ b/libs/lume/src/VM/VMDisplayPresenter.swift
@@ -214,6 +214,9 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
private var copyFilesToGuestDesktopAction: (@MainActor ([URL]) async throws -> Void)?
private var fileDropTask: Task<Void, Never>?
private var fileDropInProgress = false
+ private var clipboardActionTask: Task<Void, Never>?
+ private var clipboardActionInProgress = false
+ private var clipboardToolbarItems: [NSToolbarItem] = []
private var captureSystemKeysItem: NSMenuItem?
private var captureSystemKeysToolbarItem: NSToolbarItem?
private var showWindowItem: NSMenuItem?
@@ -268,6 +271,7 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
overlayTask?.cancel()
overlayTask = nil
fileDropTask?.cancel()
+ clipboardActionTask?.cancel()
machineView?.onClipboardShortcut = nil
machineView?.onFileDragEntered = nil
machineView?.canAcceptFileDrop = nil
@@ -288,6 +292,10 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
if fileDropTask == nil {
fileDropInProgress = false
}
+ if clipboardActionTask == nil {
+ clipboardActionInProgress = false
+ }
+ clipboardToolbarItems.removeAll()
captureSystemKeysItem = nil
captureSystemKeysToolbarItem = nil
showWindowItem = nil
@@ -335,10 +343,16 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
switch shortcut {
case .copy:
guard copyFromGuestAction != nil else { return false }
- requestCopyFromGuest()
+ // Consume repeated shortcuts while an action is running instead
+ // of forwarding a second Command-C directly to the guest.
+ if !clipboardActionInProgress {
+ requestCopyFromGuest()
+ }
case .paste:
guard pasteIntoGuestAction != nil else { return false }
- requestPasteIntoGuest()
+ if !clipboardActionInProgress {
+ requestPasteIntoGuest()
+ }
}
return true
}
@@ -464,18 +478,20 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
mainMenu.addItem(editItem)
let copyItem = NSMenuItem(
- title: "Copy from VM",
+ title: "Copy VM → Mac",
action: #selector(copyFromGuest(_:)),
keyEquivalent: "c"
)
+ copyItem.toolTip = "Send Command-C to the VM, then copy the VM clipboard to this Mac"
copyItem.target = self
editMenu.addItem(copyItem)
let pasteItem = NSMenuItem(
- title: "Paste into VM",
+ title: "Paste Mac → VM",
action: #selector(pasteIntoGuest(_:)),
keyEquivalent: "v"
)
+ pasteItem.toolTip = "Copy this Mac's clipboard into the VM, then send Command-V"
pasteItem.target = self
editMenu.addItem(pasteItem)
@@ -555,6 +571,12 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
try await addSharedFolderAction(url, readOnly)
self?.showOverlay("Shared in /Volumes/My Shared Files")
} catch {
+ Logger.error(
+ "Native shared-folder action failed",
+ metadata: [
+ "vm": self?.vmName ?? "unknown",
+ "error": error.localizedDescription,
+ ])
self?.showOverlay("Share failed — \(error.localizedDescription)")
}
}
@@ -607,36 +629,80 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
private func requestCopyFromGuest() {
guard let copyFromGuestAction else {
- showOverlay("Copy unavailable")
+ showOverlay("Copy VM → Mac unavailable")
return
}
- showOverlay("Sending ⌘C to VM…")
- Task { @MainActor [weak self] in
+ guard beginClipboardAction() else { return }
+ showOverlay("Copy VM → Mac: sending ⌘C…", automaticallyHides: false)
+ clipboardActionTask = Task { @MainActor [weak self] in
+ guard let self else { return }
+ defer {
+ self.endClipboardAction()
+ self.clipboardActionTask = nil
+ }
do {
try await copyFromGuestAction()
- self?.showOverlay("Copied from VM")
+ self.showOverlay("Copied VM clipboard to Mac")
+ } catch is CancellationError {
+ Logger.info("Native clipboard copy cancelled", metadata: ["vm": self.vmName])
} catch {
- self?.showOverlay("Copy failed — \(error.localizedDescription)")
+ Logger.error(
+ "Native clipboard copy failed",
+ metadata: [
+ "vm": self.vmName,
+ "error": error.localizedDescription,
+ ])
+ self.showOverlay("Copy VM → Mac failed — \(error.localizedDescription)")
}
}
}
private func requestPasteIntoGuest() {
guard let pasteIntoGuestAction else {
- showOverlay("Paste unavailable")
+ showOverlay("Paste Mac → VM unavailable")
return
}
- showOverlay("Syncing clipboard to VM…")
- Task { @MainActor [weak self] in
+ guard beginClipboardAction() else { return }
+ showOverlay("Paste Mac → VM: syncing clipboard…", automaticallyHides: false)
+ clipboardActionTask = Task { @MainActor [weak self] in
+ guard let self else { return }
+ defer {
+ self.endClipboardAction()
+ self.clipboardActionTask = nil
+ }
do {
try await pasteIntoGuestAction()
- self?.showOverlay("Pasted into VM")
+ self.showOverlay("Pasted Mac clipboard into VM")
+ } catch is CancellationError {
+ Logger.info("Native clipboard paste cancelled", metadata: ["vm": self.vmName])
} catch {
- self?.showOverlay("Paste failed — \(error.localizedDescription)")
+ Logger.error(
+ "Native clipboard paste failed",
+ metadata: [
+ "vm": self.vmName,
+ "error": error.localizedDescription,
+ ])
+ self.showOverlay("Paste Mac → VM failed — \(error.localizedDescription)")
}
}
}
+ private func beginClipboardAction() -> Bool {
+ guard !clipboardActionInProgress else {
+ showOverlay("Clipboard transfer already in progress")
+ return false
+ }
+ clipboardActionInProgress = true
+ clipboardToolbarItems.forEach { $0.isEnabled = false }
+ return true
+ }
+
+ private func endClipboardAction() {
+ clipboardActionInProgress = false
+ clipboardToolbarItems.forEach { $0.isEnabled = true }
+ window?.makeFirstResponder(machineView)
+ }
+
private func showOverlay(_ message: String, automaticallyHides: Bool = true) {
guard let overlayView, let overlayLabel else { return }
overlayTask?.cancel()
@@ -692,19 +758,27 @@ final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDele
let item = NSToolbarItem(itemIdentifier: itemIdentifier)
switch itemIdentifier {
case .lumeCopy:
- item.label = "Copy"
- item.paletteLabel = "Copy from VM"
- item.toolTip = "Send ⌘C to the VM and copy its text to the host"
- item.image = NSImage(systemSymbolName: "doc.on.doc", accessibilityDescription: "Copy")
+ item.label = "Copy VM → Mac"
+ item.paletteLabel = "Copy VM to Mac"
+ item.toolTip = "Send Command-C to the VM, then copy the VM clipboard to this Mac"
+ item.image = NSImage(
+ systemSymbolName: "arrow.left.doc.on.clipboard",
+ accessibilityDescription: "Copy VM clipboard to Mac"
+ ) ?? NSImage(systemSymbolName: "arrow.left", accessibilityDescription: "VM to Mac")
item.target = self
item.action = #selector(copyFromGuest(_:))
+ clipboardToolbarItems.append(item)
case .lumePaste:
- item.label = "Paste"
- item.paletteLabel = "Paste into VM"
- item.toolTip = "Sync host text and send ⌘V to the VM"
- item.image = NSImage(systemSymbolName: "doc.on.clipboard", accessibilityDescription: "Paste")
+ item.label = "Paste Mac → VM"
+ item.paletteLabel = "Paste Mac into VM"
+ item.toolTip = "Copy this Mac's clipboard into the VM, then send Command-V"
+ item.image = NSImage(
+ systemSymbolName: "arrow.right.doc.on.clipboard",
+ accessibilityDescription: "Paste Mac clipboard into VM"
+ ) ?? NSImage(systemSymbolName: "arrow.right", accessibilityDescription: "Mac to VM")
item.target = self
item.action = #selector(pasteIntoGuest(_:))
+ clipboardToolbarItems.append(item)
case .lumeShareFolder:
item.label = "Share Folder"
item.paletteLabel = "Share Folder"
diff --git a/libs/lume/tests/ClipboardWatcherTests.swift b/libs/lume/tests/ClipboardWatcherTests.swift
new file mode 100644
index 0000000000..da891c34a7
--- /dev/null
+++ b/libs/lume/tests/ClipboardWatcherTests.swift
@@ -0,0 +1,38 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+@Test("Guest copy wait command succeeds only after the pasteboard changes")
+func guestClipboardWaitCommandDetectsChange() throws {
+ let command = ClipboardWatcher.guestClipboardWaitCommand(
+ after: 41,
+ attempts: 3,
+ changeCountExpression: "42"
+ )
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/sh")
+ process.arguments = ["-c", command]
+ process.standardOutput = Pipe()
+ process.standardError = Pipe()
+ try process.run()
+ process.waitUntilExit()
+
+ #expect(process.terminationStatus == 0)
+}
+
+@Test("Guest copy wait command reports a distinct timeout")
+func guestClipboardWaitCommandTimesOut() throws {
+ let command = ClipboardWatcher.guestClipboardWaitCommand(
+ after: 41,
+ attempts: 1,
+ changeCountExpression: "41"
+ )
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/sh")
+ process.arguments = ["-c", command]
+ try process.run()
+ process.waitUntilExit()
+
+ #expect(process.terminationStatus == 75)
+}
diff --git a/libs/lume/tests/SSHClientTests.swift b/libs/lume/tests/SSHClientTests.swift
index bbd9c0cdff..e0685d635a 100644
--- a/libs/lume/tests/SSHClientTests.swift
+++ b/libs/lume/tests/SSHClientTests.swift
@@ -1,4 +1,5 @@
@preconcurrency import NIOCore
+@preconcurrency import NIOConcurrencyHelpers
@preconcurrency import NIOEmbedded
@preconcurrency import NIOSSH
import Testing
@@ -15,18 +16,18 @@ func childPromiseIsCreatedAfterHandlerLookup() throws {
let handlerFuture = eventLoop.makeFailedFuture(
SSHClientFutureTestError.handlerLookupFailed
) as EventLoopFuture<NIOSSHHandler>
- var initializerCalled = false
+ let initializerCalled = NIOLockedValueBox(false)
let childFuture = SSHClient.makeChildChannelFuture(
handlerFuture: handlerFuture,
eventLoop: eventLoop
) { _, promise in
- initializerCalled = true
+ initializerCalled.withLockedValue { $0 = true }
promise.fail(SSHClientFutureTestError.handlerLookupFailed)
}
#expect(throws: SSHClientFutureTestError.self) {
try childFuture.wait()
}
- #expect(!initializerCalled)
+ #expect(!initializerCalled.withLockedValue { $0 })
}