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 macOS VM display (#2641)

Francesco Bonacci7a5bc829cd8b
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 31360921e1..3ca7483377 100644
--- a/docs/content/docs/how-to-guides/lume/manage-vms.mdx
+++ b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
@@ -25,18 +25,39 @@ SSH availability when the VM is running.
## Run and stop a VM
-Run Tahoe with a display:
+Run Tahoe with the default Screen Sharing viewer:
```bash
lume run macos-tahoe
+# Equivalent to: lume run macos-tahoe --display vnc
```
-Run it headlessly:
+Use Lume's lower-latency native macOS viewer instead:
```bash
-lume run --no-display macos-tahoe
+lume run macos-tahoe --display native
```
+Closing the native window only hides it; it does not stop the guest. Reopen it
+from Lume's Dock icon or **Window → Show VM Window**. Run headlessly with
+`--display none` (the older `--no-display` flag remains an alias):
+
+```bash
+lume run macos-tahoe --display none
+```
+
+VNC remains available in all three modes. To open Screen Sharing for an
+already-running VM without restarting it:
+
+```bash
+open "$(lume get macos-tahoe --format json | \
+ plutil -extract 0.vncUrl raw -o - -)"
+```
+
+A native view can only be created by the process that started the VM, so a VM
+started with `--display vnc` or `--display none` cannot be switched to native
+from a second command yet.
+
Stop it when you are finished:
```bash
@@ -55,8 +76,10 @@ Pass a host directory when you run the VM:
lume run macos-tahoe --shared-dir ~/Projects
```
-The directory appears in the guest at `/Volumes/My Shared Files`. Use a
-read-only mount when the guest only needs to read the files:
+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:
```bash
lume run macos-tahoe --shared-dir ~/Projects:ro
diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdx
index c2268c2eda..4797c20d6e 100644
--- a/docs/content/docs/reference/lume/cli-reference.mdx
+++ b/docs/content/docs/reference/lume/cli-reference.mdx
@@ -70,6 +70,7 @@ Run a virtual machine
| `--disk` | [String] | - | Disk image to attach as a read-write virtio-blk device |
| `--registry` | String | ghcr.io | Container registry URL |
| `--organization` | String | trycua | Organization to pull from |
+| `--display` | DisplayMode | vnc | Local viewer to open: vnc, native, or none. The VNC server remains available in every mode |
| `--vnc-port` | Int | 0 | Port for VNC server (0 for auto-assign) |
| `--recovery-mode` | Bool | false | For macOS VMs only, boot in recovery mode |
| `--storage` | String | - | VM storage location to use |
@@ -78,7 +79,8 @@ Run a virtual machine
| Name | Default | Description |
| ---- | ------- | ----------- |
-| `-d, --no-display` | false | Do not start the VNC client |
+| `-d, --no-display` | false | Compatibility alias for --display none |
+| `--clipboard` | false | Enable bidirectional clipboard sync via SSH. Automatic for native macOS display |
### lume stop
diff --git a/libs/lume/resources/AppIcon.icns b/libs/lume/resources/AppIcon.icns
new file mode 100644
index 0000000000..833a224c90
Binary files /dev/null and b/libs/lume/resources/AppIcon.icns differ
diff --git a/libs/lume/resources/Info.plist b/libs/lume/resources/Info.plist
index e67e7d36a6..ef30c2309f 100644
--- a/libs/lume/resources/Info.plist
+++ b/libs/lume/resources/Info.plist
@@ -9,6 +9,10 @@
<string>lume</string>
<key>CFBundleName</key>
<string>Lume</string>
+ <key>CFBundleDisplayName</key>
+ <string>Lume</string>
+ <key>CFBundleIconFile</key>
+ <string>AppIcon</string>
<key>CFBundleVersion</key>
<string>__VERSION__</string>
<key>CFBundleShortVersionString</key>
@@ -19,6 +23,8 @@
<string>6.0</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
<key>LSUIElement</key>
<true/>
</dict>
diff --git a/libs/lume/scripts/build/build-release-notarized.sh b/libs/lume/scripts/build/build-release-notarized.sh
index ab056d7611..5506347e67 100755
--- a/libs/lume/scripts/build/build-release-notarized.sh
+++ b/libs/lume/scripts/build/build-release-notarized.sh
@@ -83,6 +83,7 @@ BUILD_BUNDLE=".build/release/lume_lume.bundle"
if [ -d "$BUILD_BUNDLE" ]; then
cp -rf "$BUILD_BUNDLE" "$APP_BUNDLE/Contents/Resources/"
fi
+cp -f ./resources/AppIcon.icns "$APP_BUNDLE/Contents/Resources/AppIcon.icns"
# Stamp and copy Info.plist
sed "s/__VERSION__/$VERSION/g" "./resources/Info.plist" > "$APP_BUNDLE/Contents/Info.plist"
diff --git a/libs/lume/scripts/build/build-release.sh b/libs/lume/scripts/build/build-release.sh
index 8a5e7b5b1d..1cb5a8bcaf 100755
--- a/libs/lume/scripts/build/build-release.sh
+++ b/libs/lume/scripts/build/build-release.sh
@@ -24,6 +24,7 @@ mkdir -p "$APP_BUNDLE/Contents/Resources"
if [ -d ".build/release/lume_lume.bundle" ]; then
cp -rf .build/release/lume_lume.bundle "$APP_BUNDLE/Contents/Resources/"
fi
+cp -f ./resources/AppIcon.icns "$APP_BUNDLE/Contents/Resources/AppIcon.icns"
# Stamp Info.plist with version from VERSION file
VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
diff --git a/libs/lume/scripts/install-local.sh b/libs/lume/scripts/install-local.sh
index 34e8e91fe6..f54303ded9 100755
--- a/libs/lume/scripts/install-local.sh
+++ b/libs/lume/scripts/install-local.sh
@@ -156,6 +156,7 @@ build_lume() {
if [ -d "$BUILD_PATH/lume_lume.bundle" ]; then
cp -rf "$BUILD_PATH/lume_lume.bundle" "$APP_BUNDLE/Contents/Resources/"
fi
+ cp -f "$LUME_DIR/resources/AppIcon.icns" "$APP_BUNDLE/Contents/Resources/AppIcon.icns"
# Stamp Info.plist with version
CURRENT_VERSION=$("$BUILD_PATH/lume" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "0.0.0")
diff --git a/libs/lume/src/Clipboard/ClipboardWatcher.swift b/libs/lume/src/Clipboard/ClipboardWatcher.swift
index f159eecf24..c3e767aeb2 100644
--- a/libs/lume/src/Clipboard/ClipboardWatcher.swift
+++ b/libs/lume/src/Clipboard/ClipboardWatcher.swift
@@ -1,7 +1,48 @@
import AppKit
import Foundation
-/// Watches clipboard and syncs bidirectionally between host and VM via SSH.
+enum ClipboardSyncError: LocalizedError {
+ case unavailable
+ case emptyClipboard
+ case contentTooLarge
+ case transferFailed
+
+ 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."
+ case .contentTooLarge:
+ return "The clipboard content is too large to transfer."
+ case .transferFailed:
+ return "The clipboard transfer failed."
+ }
+ }
+}
+
+private enum ClipboardPayload: Equatable, Sendable {
+ case text(String)
+ case png(Data)
+
+ var byteCount: Int {
+ switch self {
+ case .text(let value):
+ return value.utf8.count
+ case .png(let data):
+ return data.count
+ }
+ }
+
+ var kind: String {
+ switch self {
+ case .text: return "text"
+ case .png: return "image"
+ }
+ }
+}
+
+/// Watches text and image clipboards and syncs bidirectionally over SSH.
/// Requires SSH/Remote Login to be enabled on the VM.
public actor ClipboardWatcher {
private let vmName: String
@@ -9,75 +50,101 @@ public actor ClipboardWatcher {
private var watchTask: Task<Void, Never>?
private var isRunning = false
- // Track last synced content to avoid sync loops
- private var lastHostContent: String = ""
- private var lastVMContent: String = ""
- private var lastHostChangeCount: Int = 0
+ private var lastHostPayload: ClipboardPayload?
+ private var lastVMPayload: ClipboardPayload?
+ private var pendingHostPayload: ClipboardPayload?
+ private var lastHostChangeCount = 0
+ private var lastVMChangeCount: Int?
- // Cached SSH client to avoid reconnecting every poll cycle
+ // Cached SSH client to avoid reconnecting every poll cycle.
private var cachedSSHClient: SSHClient?
private var cachedIPAddress: String?
- // Error suppression to avoid flooding logs with repeated failures
- private var consecutiveFailures: Int = 0
+ // Error suppression to avoid flooding logs with repeated failures.
+ private var consecutiveFailures = 0
private var lastLoggedError: String?
- /// Polling interval for clipboard changes
private static let pollInterval: TimeInterval = 1.0
-
- /// Backoff interval when SSH is unavailable
private static let backoffInterval: TimeInterval = 5.0
-
- /// Number of consecutive failures before suppressing logs
- private static let errorLogThreshold: Int = 3
-
- /// Delay before starting to watch (allows VM to boot and get IP)
- /// Set to 0 since we gracefully handle SSH not being available yet
- private static let startupDelay: TimeInterval = 0
-
- /// Max content size (1MB)
- private static let maxContentSize = 1_000_000
+ private static let errorLogThreshold = 3
+ private static let maxTextSize = 1_000_000
+ private static let maxImageSize = 10_000_000
public init(vmName: String, storage: String?) {
self.vmName = vmName
self.storage = storage
}
- /// Start watching clipboard for bidirectional sync
public func start() {
guard !isRunning else { return }
isRunning = true
watchTask = Task { [weak self] in
- guard let self = self else { return }
-
- // Optional startup delay (set to 0 since we gracefully handle SSH not ready)
- if Self.startupDelay > 0 {
- try? await Task.sleep(nanoseconds: UInt64(Self.startupDelay * 1_000_000_000))
- }
-
- // Initialize with current clipboard state to avoid syncing on start
+ guard let self else { return }
await self.initializeState()
-
Logger.info("Clipboard sync started", metadata: ["vm": self.vmName])
while !Task.isCancelled {
await self.syncBidirectional()
let interval = await self.currentPollInterval()
- try? await Task.sleep(nanoseconds: UInt64(interval * 1_000_000_000))
+ try? await Task.sleep(for: .seconds(interval))
}
Logger.info("Clipboard sync stopped", metadata: ["vm": self.vmName])
}
}
- /// Stop watching the clipboard
public func stop() {
watchTask?.cancel()
watchTask = nil
isRunning = false
cachedSSHClient = nil
cachedIPAddress = nil
+ pendingHostPayload = nil
+ }
+
+ /// Immediately copies host text or image data into the guest clipboard.
+ func pushHostClipboardToVM() async throws {
+ let snapshot = await readHostClipboard()
+ guard let payload = snapshot.payload else {
+ throw ClipboardSyncError.emptyClipboard
+ }
+ try validateSize(of: payload)
+ try await writePayloadToVM(payload)
+
+ lastHostChangeCount = snapshot.changeCount
+ lastHostPayload = payload
+ lastVMPayload = payload
+ pendingHostPayload = nil
+ lastVMChangeCount = try? await readVMChangeCount()
+ }
+
+ /// Returns the current guest pasteboard generation for reliable Copy handling.
+ func vmClipboardChangeCount() async throws -> Int {
+ try await readVMChangeCount()
+ }
+
+ /// Immediately reads guest text or image data into the host clipboard.
+ /// When a baseline is supplied, waits briefly for the guest's Copy command.
+ 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))
+ }
+ }
+
+ let payload = try await readPayloadFromVM()
+ try validateSize(of: payload)
+ lastVMPayload = payload
+ pendingHostPayload = nil
+ lastVMChangeCount = try? await readVMChangeCount()
+ lastHostChangeCount = await writeHostClipboard(payload)
+ lastHostPayload = payload
+ resetFailureState()
}
private func currentPollInterval() -> TimeInterval {
@@ -86,142 +153,255 @@ public actor ClipboardWatcher {
: Self.pollInterval
}
- private func initializeState() {
- lastHostChangeCount = NSPasteboard.general.changeCount
- if let content = NSPasteboard.general.string(forType: .string) {
- lastHostContent = content
- lastVMContent = content // Assume VM starts with same content
- }
+ private func initializeState() async {
+ let snapshot = await readHostClipboard()
+ lastHostChangeCount = snapshot.changeCount
+ lastHostPayload = snapshot.payload
+ // Do not overwrite either side merely because the VM has just started.
+ lastVMPayload = snapshot.payload
}
private func syncBidirectional() async {
- // Check host clipboard for changes
- let hostChangeCount = NSPasteboard.general.changeCount
- var didSyncToVM = false
-
- if hostChangeCount != lastHostChangeCount {
- lastHostChangeCount = hostChangeCount
- if let content = NSPasteboard.general.string(forType: .string),
- !content.isEmpty,
- content != lastHostContent,
- content != lastVMContent, // Avoid sync loop
- content.utf8.count <= Self.maxContentSize {
- lastHostContent = content
- lastVMContent = content // Assume VM will have this content after sync
- didSyncToVM = await syncToVM(content: content)
+ let hostClipboard = await readHostClipboard()
+ if hostClipboard.changeCount != lastHostChangeCount {
+ lastHostChangeCount = hostClipboard.changeCount
+ if let payload = hostClipboard.payload,
+ payload != lastHostPayload,
+ payload != lastVMPayload,
+ isValidSize(payload) {
+ lastHostPayload = payload
+ pendingHostPayload = payload
}
}
- // Check VM clipboard for changes, but skip if we just synced to VM
- // (VM clipboard won't be updated yet, would cause race condition)
- if !didSyncToVM {
- await syncFromVM()
+ // Retry host changes until SSH accepts them. Do not pull stale guest content
+ // while a host-to-guest transfer is pending.
+ if let pendingHostPayload {
+ do {
+ try await writePayloadToVM(pendingHostPayload)
+ lastVMPayload = pendingHostPayload
+ self.pendingHostPayload = nil
+ lastVMChangeCount = try? await readVMChangeCount()
+ resetFailureState()
+ } catch {
+ handleSyncError("Failed to sync clipboard to VM", error: error)
+ }
+ return
+ }
+
+ do {
+ let currentChangeCount = try await readVMChangeCount()
+ guard let previousChangeCount = lastVMChangeCount else {
+ lastVMChangeCount = currentChangeCount
+ return
+ }
+ guard currentChangeCount != previousChangeCount else { return }
+ lastVMChangeCount = currentChangeCount
+
+ let payload = try await readPayloadFromVM()
+ guard payload != lastVMPayload,
+ payload != lastHostPayload,
+ isValidSize(payload) else {
+ return
+ }
+
+ lastVMPayload = payload
+ lastHostChangeCount = await writeHostClipboard(payload)
+ lastHostPayload = payload
+ resetFailureState()
+ Logger.debug("Clipboard synced from VM", metadata: [
+ "vm": vmName,
+ "kind": payload.kind,
+ "size": "\(payload.byteCount)",
+ ])
+ } catch {
+ handleSyncError("Failed to sync clipboard from VM", error: error)
}
}
- private func syncToVM(content: String) async -> Bool {
- guard let sshClient = await getSSHClient() else { return false }
+ private func writePayloadToVM(_ payload: ClipboardPayload) async throws {
+ guard let sshClient = await getSSHClient() else {
+ throw ClipboardSyncError.unavailable
+ }
- do {
- guard let data = content.data(using: .utf8) else { return false }
- let base64Content = data.base64EncodedString()
-
- // For short content, use inline command
- // For long content, use heredoc to avoid shell argument limits
- let command: String
- if base64Content.count < 65536 {
- // Short content: inline is fine
- command = "printf '%s' '\(base64Content)' | base64 -D | pbcopy"
+ let command: String
+ let timeout: TimeInterval
+ switch payload {
+ case .text(let content):
+ guard let data = content.data(using: .utf8) else {
+ throw ClipboardSyncError.transferFailed
+ }
+ let encoded = data.base64EncodedString()
+ if encoded.count < 65_536 {
+ command = "printf '%s' '\(encoded)' | base64 -D | pbcopy"
} else {
- // Long content: use heredoc to avoid ARG_MAX limits
command = """
- base64 -D <<'CLIPBOARD_EOF' | pbcopy
- \(base64Content)
- CLIPBOARD_EOF
- """
+ base64 -D <<'LUME_CLIPBOARD_EOF' | pbcopy
+ \(encoded)
+ LUME_CLIPBOARD_EOF
+ """
}
+ timeout = 10
+
+ case .png(let data):
+ let encoded = data.base64EncodedString()
+ let path = "/tmp/lume-clipboard-\(UUID().uuidString).png"
+ command = """
+ base64 -D <<'LUME_CLIPBOARD_EOF' > '\(path)'
+ \(encoded)
+ LUME_CLIPBOARD_EOF
+ /usr/bin/osascript -e 'set the clipboard to (read (POSIX file "\(path)") as «class PNGf»)'
+ lume_status=$?
+ rm -f '\(path)'
+ exit $lume_status
+ """
+ timeout = 30
+ }
- let result = try await sshClient.execute(command: command, timeout: 10)
+ let result = try await sshClient.execute(command: command, timeout: timeout)
+ guard result.exitCode == 0 else {
+ throw ClipboardSyncError.transferFailed
+ }
- if result.exitCode == 0 {
- resetFailureState()
- Logger.debug("Clipboard synced to VM", metadata: [
- "vm": vmName,
- "size": "\(content.utf8.count)"
- ])
- return true
- }
- return false
- } catch {
- handleSyncError("Failed to sync clipboard to VM", error: error)
- return false
+ resetFailureState()
+ Logger.debug("Clipboard synced to VM", metadata: [
+ "vm": vmName,
+ "kind": payload.kind,
+ "size": "\(payload.byteCount)",
+ ])
+ }
+
+ 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)
+ guard result.exitCode == 0,
+ let value = Int(result.output.trimmingCharacters(in: .whitespacesAndNewlines)) else {
+ throw ClipboardSyncError.transferFailed
+ }
+ return value
}
- private func syncFromVM() async {
- guard let sshClient = await getSSHClient() else { return }
+ private func readPayloadFromVM() async throws -> ClipboardPayload {
+ guard let sshClient = await getSSHClient() else {
+ throw ClipboardSyncError.unavailable
+ }
- do {
- // Get VM clipboard content
- let result = try await sshClient.execute(command: "pbpaste | base64", timeout: 5)
+ let path = "/tmp/lume-clipboard-\(UUID().uuidString).png"
+ let command = """
+ if /usr/bin/osascript \\
+ -e 'set imageData to the clipboard as «class PNGf»' \\
+ -e 'set fileRef to open for access POSIX file "\(path)" with write permission' \\
+ -e 'set eof fileRef to 0' \\
+ -e 'write imageData to fileRef' \\
+ -e 'close access fileRef' >/dev/null 2>&1; then
+ printf 'IMAGE\\n'
+ base64 < '\(path)'
+ else
+ printf 'TEXT\\n'
+ pbpaste | base64
+ fi
+ rm -f '\(path)'
+ """
+
+ let result = try await sshClient.execute(command: command, timeout: 30)
+ guard result.exitCode == 0,
+ let separator = result.output.firstIndex(of: "\n") else {
+ throw ClipboardSyncError.transferFailed
+ }
- guard result.exitCode == 0 else { return }
+ let kind = result.output[..<separator].trimmingCharacters(in: .whitespacesAndNewlines)
+ let encoded = String(result.output[result.output.index(after: separator)...])
+ guard let data = Data(base64Encoded: encoded, options: .ignoreUnknownCharacters),
+ !data.isEmpty else {
+ throw ClipboardSyncError.emptyClipboard
+ }
- let trimmedOutput = result.output.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmedOutput.isEmpty else { return }
+ switch kind {
+ case "IMAGE":
+ return .png(data)
+ case "TEXT":
+ guard let content = String(data: data, encoding: .utf8), !content.isEmpty else {
+ throw ClipboardSyncError.emptyClipboard
+ }
+ return .text(content)
+ default:
+ throw ClipboardSyncError.transferFailed
+ }
+ }
- guard let data = Data(base64Encoded: trimmedOutput),
- let content = String(data: data, encoding: .utf8),
- !content.isEmpty,
- content != lastVMContent,
- content != lastHostContent, // Avoid sync loop
- content.utf8.count <= Self.maxContentSize else {
- return
+ private func readHostClipboard() async -> (changeCount: Int, payload: ClipboardPayload?) {
+ await MainActor.run {
+ let pasteboard = NSPasteboard.general
+ let payload: ClipboardPayload?
+
+ if let png = pasteboard.data(forType: .png), !png.isEmpty {
+ payload = .png(png)
+ } else if let tiff = pasteboard.data(forType: .tiff),
+ let representation = NSBitmapImageRep(data: tiff),
+ let png = representation.representation(using: .png, properties: [:]) {
+ payload = .png(png)
+ } else if let content = pasteboard.string(forType: .string), !content.isEmpty {
+ payload = .text(content)
+ } else {
+ payload = nil
}
+ return (pasteboard.changeCount, payload)
+ }
+ }
- // Update tracking
- lastVMContent = content
+ private func writeHostClipboard(_ payload: ClipboardPayload) async -> Int {
+ await MainActor.run {
+ let pasteboard = NSPasteboard.general
+ pasteboard.clearContents()
+ switch payload {
+ case .text(let content):
+ pasteboard.setString(content, forType: .string)
+ case .png(let data):
+ pasteboard.setData(data, forType: .png)
+ if let image = NSImage(data: data), let tiff = image.tiffRepresentation {
+ pasteboard.setData(tiff, forType: .tiff)
+ }
+ }
+ return pasteboard.changeCount
+ }
+ }
- // Write to host clipboard
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(content, forType: .string)
- lastHostChangeCount = NSPasteboard.general.changeCount
- lastHostContent = content
+ private func validateSize(of payload: ClipboardPayload) throws {
+ guard isValidSize(payload) else {
+ throw ClipboardSyncError.contentTooLarge
+ }
+ }
- resetFailureState()
- Logger.debug("Clipboard synced from VM", metadata: [
- "vm": vmName,
- "size": "\(content.utf8.count)"
- ])
- } catch {
- handleSyncError("Failed to sync clipboard from VM", error: error)
+ private func isValidSize(_ payload: ClipboardPayload) -> Bool {
+ switch payload {
+ case .text:
+ return payload.byteCount <= Self.maxTextSize
+ case .png:
+ return payload.byteCount <= Self.maxImageSize
}
}
- /// Log sync errors with suppression to avoid flooding output.
- /// Logs the first occurrence and when the error changes, then suppresses
- /// repeated identical errors.
private func handleSyncError(_ message: String, error: Error) {
- // Invalidate cached client on error so we reconnect next cycle
cachedSSHClient = nil
-
consecutiveFailures += 1
- let errorDesc = error.localizedDescription
+ let errorDescription = error.localizedDescription
- if errorDesc != lastLoggedError {
- // New error type — always log it
+ if errorDescription != lastLoggedError {
Logger.debug(message, metadata: [
"vm": vmName,
- "error": errorDesc
+ "error": errorDescription,
])
- lastLoggedError = errorDesc
+ lastLoggedError = errorDescription
} else if consecutiveFailures == Self.errorLogThreshold {
- // Threshold reached — log once that we're suppressing
- Logger.debug("Clipboard sync errors repeating, suppressing further logs until resolved", metadata: [
- "vm": vmName
- ])
+ Logger.debug(
+ "Clipboard sync errors repeating, suppressing further logs until resolved",
+ metadata: ["vm": vmName]
+ )
}
- // Otherwise: same error, already suppressed — don't log
}
private func resetFailureState() {
@@ -245,9 +425,8 @@ public actor ClipboardWatcher {
return nil
}
- // Reuse cached client if IP hasn't changed
- if let cached = cachedSSHClient, cachedIPAddress == ipAddress {
- return cached
+ if let cachedSSHClient, cachedIPAddress == ipAddress {
+ return cachedSSHClient
}
let client = SSHClient(
diff --git a/libs/lume/src/Commands/Run.swift b/libs/lume/src/Commands/Run.swift
index f89845ad1c..6a98c98c91 100644
--- a/libs/lume/src/Commands/Run.swift
+++ b/libs/lume/src/Commands/Run.swift
@@ -12,7 +12,15 @@ struct Run: AsyncParsableCommand {
completion: .custom(completeVMName))
var name: String
- @Flag(name: [.short, .long], help: "Do not start the VNC client")
+ @Option(
+ help: "Local viewer to open: 'vnc', 'native', or 'none'. The VNC server remains available in every mode."
+ )
+ var display: DisplayMode = .vnc
+
+ @Flag(
+ name: [.customShort("d"), .customLong("no-display")],
+ help: "Compatibility alias for --display none"
+ )
var noDisplay: Bool = false
@Option(
@@ -79,7 +87,10 @@ struct Run: AsyncParsableCommand {
help: "Optional network override: 'nat', 'bridged', or 'bridged:<interface>' (e.g. 'bridged:en0'). Defaults to the VM's configured mode.")
var network: String?
- @Flag(name: .customLong("clipboard"), help: "Enable bidirectional clipboard sync with the VM via SSH (experimental)")
+ @Flag(
+ name: .customLong("clipboard"),
+ help: "Enable bidirectional clipboard sync via SSH. This is automatic for native macOS display."
+ )
var clipboard: Bool = false
private var parsedNetworkMode: NetworkMode? {
@@ -148,13 +159,20 @@ struct Run: AsyncParsableCommand {
@MainActor
func run() async throws {
// Record telemetry
+ let displayMode = DisplayMode.resolve(requested: display, noDisplay: noDisplay)
TelemetryClient.shared.record(event: TelemetryEvent.run, properties: [
- "headless": noDisplay
+ "headless": displayMode == .none
])
+ try await runVM(displayMode: displayMode)
+ }
+
+ @MainActor
+ private func runVM(displayMode: DisplayMode) async throws {
try await LumeController().runVM(
name: name,
noDisplay: noDisplay,
+ displayMode: displayMode,
sharedDirectories: parsedSharedDirectories,
mount: mount.map { Path($0) },
registry: registry,
diff --git a/libs/lume/src/FileSystem/VMConfig.swift b/libs/lume/src/FileSystem/VMConfig.swift
index 8fa21238f6..3c1fdcb9bc 100644
--- a/libs/lume/src/FileSystem/VMConfig.swift
+++ b/libs/lume/src/FileSystem/VMConfig.swift
@@ -3,7 +3,7 @@ import Foundation
import Virtualization
/// Represents a shared directory configuration
-struct SharedDirectory: Codable {
+struct SharedDirectory: Codable, Sendable {
let hostPath: String
let tag: String
let readOnly: Bool
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index f5989f6ece..cdba97a70d 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -1036,6 +1036,7 @@ final class LumeController {
public func runVM(
name: String,
noDisplay: Bool = false,
+ displayMode: DisplayMode? = nil,
sharedDirectories: [SharedDirectory] = [],
mount: Path? = nil,
registry: String = "ghcr.io",
@@ -1053,11 +1054,12 @@ final class LumeController {
telemetryTransport: TelemetryTransport = .cli
) async throws {
let normalizedName = normalizeVMName(name: name)
+ let effectiveDisplayMode = displayMode ?? (noDisplay ? .none : .vnc)
Logger.info(
"Running VM",
metadata: [
"name": normalizedName,
- "no_display": "\(noDisplay)",
+ "display_mode": effectiveDisplayMode.rawValue,
"shared_directories":
"\(sharedDirectories.map( { $0.string } ).joined(separator: ", "))",
"mount": mount?.path ?? "none",
@@ -1168,7 +1170,7 @@ final class LumeController {
SharedVM.shared.setVM(name: normalizedName, vm: vm)
try await vm.run(
- noDisplay: noDisplay,
+ displayMode: effectiveDisplayMode,
sharedDirectories: sharedDirectories,
mount: mount,
vncPort: vncPort,
diff --git a/libs/lume/src/Main.swift b/libs/lume/src/Main.swift
index 0ce8640af7..1f2a9d6040 100644
--- a/libs/lume/src/Main.swift
+++ b/libs/lume/src/Main.swift
@@ -1,4 +1,6 @@
+import AppKit
import ArgumentParser
+import Dispatch
import Foundation
@main
@@ -56,7 +58,27 @@ extension Lume {
// MARK: - Command Execution
extension Lume {
- public static func main() async {
+ public static func main() {
+ if let vmName = nativeDisplayVMName() {
+ ProcessInfo.processInfo.processName = "Lume — \(vmName)"
+ do {
+ try NativeApplicationLoop.run {
+ await executeInvocation()
+ }
+ } catch {
+ exit(withError: error)
+ }
+ return
+ }
+
+ Task {
+ await executeInvocation()
+ Foundation.exit(EXIT_SUCCESS)
+ }
+ dispatchMain()
+ }
+
+ private static func executeInvocation() async {
// Telemetry management must be able to be the first invocation without
// creating an ID or making a request. Every other entry point performs
// consent-aware registration and per-version release recording before
@@ -84,6 +106,26 @@ extension Lume {
}
}
+ private static func nativeDisplayVMName() -> String? {
+ let args = Array(CommandLine.arguments.dropFirst())
+ guard args.first == "run", !args.contains("--no-display") else {
+ return nil
+ }
+ let usesNativeDisplay = args.contains("--display=native")
+ || args.indices.contains { index in
+ args[index] == "--display"
+ && args.index(after: index) < args.endIndex
+ && args[args.index(after: index)] == "native"
+ }
+ guard usesNativeDisplay else { return nil }
+
+ // The Run command's first positional argument is the VM name.
+ guard args.count > 1, !args[1].hasPrefix("-") else {
+ return "VM"
+ }
+ return args[1]
+ }
+
private static func isTelemetryManagementInvocation() -> Bool {
let args = Array(CommandLine.arguments.dropFirst())
return args.count >= 2 && args[0] == "config" && args[1] == "telemetry"
diff --git a/libs/lume/src/Unattended/UnattendedInstaller.swift b/libs/lume/src/Unattended/UnattendedInstaller.swift
index e7ec015496..b83ac3d3a9 100644
--- a/libs/lume/src/Unattended/UnattendedInstaller.swift
+++ b/libs/lume/src/Unattended/UnattendedInstaller.swift
@@ -63,7 +63,7 @@ final class UnattendedInstaller {
let vmTask = Task {
do {
try await vm.run(
- noDisplay: true,
+ displayMode: .none,
sharedDirectories: [],
mount: nil,
vncPort: vncPort,
@@ -117,7 +117,7 @@ final class UnattendedInstaller {
while attempts < maxAttempts {
do {
try await vm.run(
- noDisplay: true,
+ displayMode: .none,
sharedDirectories: [],
mount: nil,
vncPort: vncPort,
diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swift
index c649cca2db..91c5895dd8 100644
--- a/libs/lume/src/Utils/CommandDocExtractor.swift
+++ b/libs/lume/src/Utils/CommandDocExtractor.swift
@@ -342,12 +342,14 @@ enum CommandDocExtractor {
OptionDoc(name: "disk", shortName: nil, help: "Disk image to attach as a read-write virtio-blk device", type: "[String]", defaultValue: nil, isOptional: true),
OptionDoc(name: "registry", shortName: nil, help: "Container registry URL", type: "String", defaultValue: "ghcr.io", isOptional: false),
OptionDoc(name: "organization", shortName: nil, help: "Organization to pull from", type: "String", defaultValue: "trycua", isOptional: false),
+ OptionDoc(name: "display", shortName: nil, help: "Local viewer to open: vnc, native, or none. The VNC server remains available in every mode", type: "DisplayMode", defaultValue: "vnc", isOptional: false),
OptionDoc(name: "vnc-port", shortName: nil, help: "Port for VNC server (0 for auto-assign)", type: "Int", defaultValue: "0", isOptional: false),
OptionDoc(name: "recovery-mode", shortName: nil, help: "For macOS VMs only, boot in recovery mode", type: "Bool", defaultValue: "false", isOptional: true),
OptionDoc(name: "storage", shortName: nil, help: "VM storage location to use", type: "String", defaultValue: nil, isOptional: true),
],
flags: [
- FlagDoc(name: "no-display", shortName: "d", help: "Do not start the VNC client", defaultValue: false),
+ FlagDoc(name: "no-display", shortName: "d", help: "Compatibility alias for --display none", defaultValue: false),
+ FlagDoc(name: "clipboard", shortName: nil, help: "Enable bidirectional clipboard sync via SSH. Automatic for native macOS display", defaultValue: false),
],
subcommands: []
)
diff --git a/libs/lume/src/VM/DarwinVM.swift b/libs/lume/src/VM/DarwinVM.swift
index 7d4316e91d..2d009516ff 100644
--- a/libs/lume/src/VM/DarwinVM.swift
+++ b/libs/lume/src/VM/DarwinVM.swift
@@ -9,13 +9,15 @@ final class DarwinVM: VM {
vmDirContext: VMDirContext,
virtualizationServiceFactory: @escaping (VMVirtualizationServiceContext) throws -> VMVirtualizationService = { try DarwinVirtualizationService(configuration: $0) },
vncServiceFactory: @escaping (VMDirectory) -> VNCService = { DefaultVNCService(vmDirectory: $0) },
+ displayPresenterFactory: @escaping @MainActor (DisplayMode, VNCService) -> VMDisplayPresenter = defaultDisplayPresenter,
imageLoader: ImageLoader
) {
self.imageLoader = imageLoader
super.init(
vmDirContext: vmDirContext,
virtualizationServiceFactory: virtualizationServiceFactory,
- vncServiceFactory: vncServiceFactory
+ vncServiceFactory: vncServiceFactory,
+ displayPresenterFactory: displayPresenterFactory
)
}
diff --git a/libs/lume/src/VM/DisplayMode.swift b/libs/lume/src/VM/DisplayMode.swift
new file mode 100644
index 0000000000..c912dbe800
--- /dev/null
+++ b/libs/lume/src/VM/DisplayMode.swift
@@ -0,0 +1,13 @@
+import ArgumentParser
+import Foundation
+
+/// Controls which local viewer Lume presents. The VNC server remains available in every mode.
+enum DisplayMode: String, CaseIterable, Codable, ExpressibleByArgument, Sendable {
+ case vnc
+ case native
+ case none
+
+ static func resolve(requested: DisplayMode, noDisplay: Bool) -> DisplayMode {
+ noDisplay ? .none : requested
+ }
+}
diff --git a/libs/lume/src/VM/LinuxVM.swift b/libs/lume/src/VM/LinuxVM.swift
index 76de4995b4..57d9bfc426 100644
--- a/libs/lume/src/VM/LinuxVM.swift
+++ b/libs/lume/src/VM/LinuxVM.swift
@@ -6,12 +6,14 @@ final class LinuxVM: VM {
override init(
vmDirContext: VMDirContext,
virtualizationServiceFactory: @escaping (VMVirtualizationServiceContext) throws -> VMVirtualizationService = { try LinuxVirtualizationService(configuration: $0) },
- vncServiceFactory: @escaping (VMDirectory) -> VNCService = { DefaultVNCService(vmDirectory: $0) }
+ vncServiceFactory: @escaping (VMDirectory) -> VNCService = { DefaultVNCService(vmDirectory: $0) },
+ displayPresenterFactory: @escaping @MainActor (DisplayMode, VNCService) -> VMDisplayPresenter = defaultDisplayPresenter
) {
super.init(
vmDirContext: vmDirContext,
virtualizationServiceFactory: virtualizationServiceFactory,
- vncServiceFactory: vncServiceFactory
+ vncServiceFactory: vncServiceFactory,
+ displayPresenterFactory: displayPresenterFactory
)
}
diff --git a/libs/lume/src/VM/NativeApplicationLoop.swift b/libs/lume/src/VM/NativeApplicationLoop.swift
new file mode 100644
index 0000000000..1ed6dc73aa
--- /dev/null
+++ b/libs/lume/src/VM/NativeApplicationLoop.swift
@@ -0,0 +1,110 @@
+import AppKit
+import Foundation
+
+private final class NativeOperationBridge: @unchecked Sendable {
+ var result: Result<Void, Error>?
+}
+
+/// Hosts native-display VM work inside a conventional AppKit application loop.
+///
+/// This must be entered synchronously from the process entry point, before any async
+/// MainActor command task is active. AppKit owns the main thread, while
+/// Virtualization.framework uses a dedicated serial queue for VM operations.
+@MainActor
+enum NativeApplicationLoop {
+ private(set) static var isActive = false
+ private static var startupWindow: NSWindow?
+
+ static func nativeWindowDidOpen() {
+ startupWindow?.orderOut(nil)
+ startupWindow?.close()
+ startupWindow = nil
+ }
+
+ static func run(
+ operation: @escaping @MainActor @Sendable () async throws -> Void
+ ) throws {
+ precondition(!isActive, "The native AppKit loop is already running")
+
+ let application = NSApplication.shared
+ let terminationReason = "Lume is running a virtual machine"
+ ProcessInfo.processInfo.disableAutomaticTermination(terminationReason)
+ ProcessInfo.processInfo.disableSuddenTermination()
+ defer {
+ ProcessInfo.processInfo.enableSuddenTermination()
+ ProcessInfo.processInfo.enableAutomaticTermination(terminationReason)
+ }
+
+ if application.activationPolicy() != .regular {
+ guard application.setActivationPolicy(.regular) else {
+ throw VMDisplayPresenterError.applicationSetupFailed
+ }
+ }
+ application.finishLaunching()
+
+ let startupWindow = makeStartupWindow()
+ self.startupWindow = startupWindow
+ startupWindow.makeKeyAndOrderFront(nil)
+ application.activate(ignoringOtherApps: true)
+
+ isActive = true
+ defer {
+ nativeWindowDidOpen()
+ isActive = false
+ }
+
+ let bridge = NativeOperationBridge()
+ DispatchQueue.main.async { @Sendable in
+ Task { @MainActor in
+ do {
+ try await operation()
+ bridge.result = .success(())
+ } catch {
+ bridge.result = .failure(error)
+ }
+
+ let application = NSApplication.shared
+ application.stop(nil)
+ if let wakeEvent = NSEvent.otherEvent(
+ with: .applicationDefined,
+ location: .zero,
+ modifierFlags: [],
+ timestamp: 0,
+ windowNumber: 0,
+ context: nil,
+ subtype: 0,
+ data1: 0,
+ data2: 0
+ ) {
+ application.postEvent(wakeEvent, atStart: false)
+ }
+ }
+ }
+
+ application.run()
+
+ guard let result = bridge.result else {
+ throw VMDisplayPresenterError.applicationSetupFailed
+ }
+ try result.get()
+ }
+
+ private static func makeStartupWindow() -> NSWindow {
+ let window = NSWindow(
+ contentRect: NSRect(x: 0, y: 0, width: 460, height: 150),
+ styleMask: [.titled],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "Starting Lume Native Display…"
+ window.isReleasedWhenClosed = false
+
+ let label = NSTextField(labelWithString: "Starting virtual machine…")
+ label.font = .systemFont(ofSize: 18, weight: .medium)
+ label.alignment = .center
+ label.frame = NSRect(x: 20, y: 50, width: 420, height: 28)
+ window.contentView?.addSubview(label)
+ window.center()
+ return window
+ }
+}
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index d85e1777f1..0e25e12ebb 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -1,5 +1,6 @@
-import Foundation
import CoreGraphics
+import Foundation
+import Virtualization
// MARK: - Support Types
@@ -50,9 +51,14 @@ class VM {
private var virtualizationService: VMVirtualizationService?
internal let vncService: VNCService
private var clipboardWatcher: ClipboardWatcher?
+ private var displayPresenter: VMDisplayPresenter?
+ private var activeSharedDirectories: [SharedDirectory] = []
+ private var scopedSharedDirectoryURLs: [URL] = []
+ private var sessionCleanedUp = true
internal let virtualizationServiceFactory:
(VMVirtualizationServiceContext) throws -> VMVirtualizationService
private let vncServiceFactory: (VMDirectory) -> VNCService
+ private let displayPresenterFactory: @MainActor (DisplayMode, VNCService) -> VMDisplayPresenter
// MARK: - Initialization
@@ -62,11 +68,14 @@ class VM {
VMVirtualizationService = { try DarwinVirtualizationService(configuration: $0) },
vncServiceFactory: @escaping (VMDirectory) -> VNCService = {
DefaultVNCService(vmDirectory: $0)
- }
+ },
+ displayPresenterFactory: @escaping @MainActor (DisplayMode, VNCService) -> VMDisplayPresenter =
+ defaultDisplayPresenter
) {
self.vmDirContext = vmDirContext
self.virtualizationServiceFactory = virtualizationServiceFactory
self.vncServiceFactory = vncServiceFactory
+ self.displayPresenterFactory = displayPresenterFactory
// Initialize VNC service
self.vncService = vncServiceFactory(vmDirContext.dir)
@@ -142,10 +151,19 @@ class VM {
// MARK: - VM Lifecycle Management
+ static func shouldStartClipboardWatcher(
+ displayMode: DisplayMode,
+ osType: String,
+ explicitlyRequested: Bool
+ ) -> Bool {
+ explicitlyRequested
+ || (displayMode == .native && osType.caseInsensitiveCompare("macOS") == .orderedSame)
+ }
+
func run(
- noDisplay: Bool, sharedDirectories: [SharedDirectory], mount: Path?, vncPort: Int = 0,
- vncPassword: String? = nil, recoveryMode: Bool = false, usbMassStoragePaths: [Path]? = nil,
- additionalDiskPaths: [Path]? = nil,
+ displayMode: DisplayMode = .vnc, sharedDirectories: [SharedDirectory], mount: Path?,
+ vncPort: Int = 0, vncPassword: String? = nil, recoveryMode: Bool = false,
+ usbMassStoragePaths: [Path]? = nil, additionalDiskPaths: [Path]? = nil,
networkMode: NetworkMode? = nil, clipboard: Bool = false
) async throws {
guard let resizeGuard = try vmDirContext.dir.tryAcquireResizeGuard(exclusive: false) else {
@@ -159,7 +177,7 @@ class VM {
"VM.run method called",
metadata: [
"name": vmDirContext.name,
- "noDisplay": "\(noDisplay)",
+ "displayMode": displayMode.rawValue,
"recoveryMode": "\(recoveryMode)",
])
@@ -226,6 +244,12 @@ class VM {
}
}
Logger.info("Successfully acquired lock", metadata: ["name": vmDirContext.name])
+ defer {
+ flock(fileHandle.fileDescriptor, LOCK_UN)
+ try? fileHandle.close()
+ }
+ sessionCleanedUp = false
+ activeSharedDirectories = sharedDirectories
Logger.info(
"Running VM with configuration",
@@ -280,11 +304,21 @@ class VM {
"Successfully initialized virtualization service",
metadata: ["name": vmDirContext.name])
+ guard let service = virtualizationService else {
+ Logger.error("Virtualization service is nil", metadata: ["name": vmDirContext.name])
+ throw VMError.internalError("Virtualization service not initialized")
+ }
+
+ let presenter = displayPresenterFactory(displayMode, vncService)
+ displayPresenter = presenter
+
+ // VNC remains active for automation and late remote attachment in every
+ // display mode, including the in-process native viewer.
Logger.info(
"Setting up VNC",
metadata: [
"name": vmDirContext.name,
- "noDisplay": "\(noDisplay)",
+ "displayMode": displayMode.rawValue,
"port": "\(vncPort)",
])
let vncInfo = try await setupSession(
@@ -309,10 +343,6 @@ class VM {
"VNC setup successful", metadata: ["name": vmDirContext.name, "vncInfo": vncInfo])
// Start the VM
- guard let service = virtualizationService else {
- Logger.error("Virtualization service is nil", metadata: ["name": vmDirContext.name])
- throw VMError.internalError("Virtualization service not initialized")
- }
Logger.info(
"Starting VM via virtualization service", metadata: ["name": vmDirContext.name])
try await service.start()
@@ -324,12 +354,49 @@ class VM {
)
}
- // Open the VNC client only after VM start to avoid connecting to an empty framebuffer.
- if !noDisplay {
+ // macOS does not include a SPICE guest agent, so its native viewer uses
+ // Lume's SSH bridge automatically. Keep --clipboard as an explicit opt-in
+ // for other display modes and guest operating systems.
+ if Self.shouldStartClipboardWatcher(
+ displayMode: displayMode,
+ osType: getOSType(),
+ explicitlyRequested: clipboard
+ ) {
+ clipboardWatcher = ClipboardWatcher(
+ vmName: vmDirContext.name,
+ storage: vmDirContext.storage
+ )
+ await clipboardWatcher?.start()
+ }
+
+ if displayMode == .vnc {
await waitForVisibleFramebufferBeforeOpeningClient()
- Logger.info("Starting VNC session", metadata: ["name": vmDirContext.name])
- try await vncService.openClient(url: vncInfo)
}
+ // Attach VZVirtualMachineView only once the guest has entered its live state.
+ // Attaching a native view to a stopped VM can leave its display black.
+ try await presenter.show(
+ context: VMDisplayContext(
+ virtualMachine: service.displayVirtualMachine,
+ vncURL: vncInfo,
+ resolution: vmDirContext.config.display,
+ vmName: vmDirContext.name,
+ copyFromGuest: { [weak self] in
+ guard let self else { throw ClipboardSyncError.unavailable }
+ try await self.copyClipboardFromGuest()
+ },
+ pasteIntoGuest: { [weak self] in
+ guard let self else { throw ClipboardSyncError.unavailable }
+ try await self.pasteClipboardIntoGuest()
+ },
+ addSharedFolder: { [weak self] url, readOnly in
+ guard let self else {
+ throw VMError.internalError("The VM session is no longer available")
+ }
+ try await self.addSharedFolder(url, readOnly: readOnly)
+ }
+ )
+ )
+ presenter.virtualMachineDidStart()
// Write VNC config into VM via SSH (background task).
// VirtioFS mounts are blocked by macOS TCC for LaunchAgent processes,
@@ -343,16 +410,9 @@ class VM {
}
}
- // Start clipboard watcher for automatic host-to-VM clipboard sync
- // Requires SSH/Remote Login to be enabled on the VM
- if clipboard {
- clipboardWatcher = ClipboardWatcher(vmName: vmDirContext.name, storage: vmDirContext.storage)
- await clipboardWatcher?.start()
- }
-
- while true {
- try await Task.sleep(nanoseconds: UInt64(1e9))
- }
+ try await service.waitForStop()
+ Logger.info("VM lifecycle ended", metadata: ["name": vmDirContext.name])
+ await cleanupSession()
} catch {
Logger.error(
"Failed in VM.run",
@@ -361,24 +421,99 @@ class VM {
"error": error.localizedDescription,
"errorType": "\(type(of: error))",
])
- await clipboardWatcher?.stop()
- clipboardWatcher = nil
- virtualizationService = nil
- vncService.stop()
- // Release lock
- Logger.info("Releasing file lock after error", metadata: ["name": vmDirContext.name])
- flock(fileHandle.fileDescriptor, LOCK_UN)
- try? fileHandle.close()
+ // Presentation/startup failure and task cancellation must not leave a running guest.
+ if let service = virtualizationService,
+ service.state == .running || service.state == .paused
+ {
+ try? await service.stop()
+ }
+ await cleanupSession()
+ throw error
+ }
+ }
- // Additionally, perform our aggressive unlock to ensure no locks remain
- Logger.info(
- "Performing additional lock cleanup after error",
- metadata: ["name": vmDirContext.name])
- unlockConfigFile()
+ 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)
+ }
+
+ private func pasteClipboardIntoGuest() async throws {
+ guard let clipboardWatcher else {
+ throw ClipboardSyncError.unavailable
+ }
+
+ try await clipboardWatcher.pushHostClipboardToVM()
+ try await sendGuestClipboardShortcut("v")
+ }
+
+ private func sendGuestClipboardShortcut(_ character: Character) async throws {
+ try await vncService.connectInputClient()
+ defer { vncService.disconnectInputClient() }
+ try await vncService.sendCharWithModifiers(character, modifiers: .command)
+ }
+
+ private func addSharedFolder(_ url: URL, readOnly: Bool) async throws {
+ var isDirectory: ObjCBool = false
+ guard url.isFileURL,
+ FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
+ isDirectory.boolValue else {
+ throw VMError.internalError("Select an existing host directory")
+ }
+ guard let virtualizationService else {
+ throw VMError.internalError("Virtualization service is not initialized")
+ }
+
+ let standardizedPath = url.standardizedFileURL.path
+ let sharedDirectory = SharedDirectory(
+ hostPath: standardizedPath,
+ tag: VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag,
+ readOnly: readOnly
+ )
+ let existing = activeSharedDirectories.filter {
+ URL(fileURLWithPath: $0.hostPath).standardizedFileURL.path != standardizedPath
+ }
+ let updated = existing + [sharedDirectory]
+
+ let gainedScopedAccess = url.startAccessingSecurityScopedResource()
+ do {
+ try await virtualizationService.updateSharedDirectories(updated)
+ } catch {
+ if gainedScopedAccess {
+ url.stopAccessingSecurityScopedResource()
+ }
throw error
}
+ if gainedScopedAccess {
+ scopedSharedDirectoryURLs.append(url)
+ }
+ activeSharedDirectories = updated
+ if let sessionURL = vncService.url {
+ saveSessionData(url: sessionURL, sharedDirectories: updated)
+ }
+ }
+
+ private func cleanupSession() async {
+ guard !sessionCleanedUp else { return }
+ sessionCleanedUp = true
+
+ // Detach native display before releasing the framework VM.
+ displayPresenter?.hide()
+ displayPresenter = nil
+ await clipboardWatcher?.stop()
+ clipboardWatcher = nil
+ for url in scopedSharedDirectoryURLs {
+ url.stopAccessingSecurityScopedResource()
+ }
+ scopedSharedDirectoryURLs.removeAll()
+ activeSharedDirectories.removeAll()
+ vncService.stop()
+ virtualizationService = nil
}
@MainActor
@@ -395,20 +530,12 @@ class VM {
Logger.info(
"Stopping VM via virtualization service", metadata: ["name": vmDirContext.name])
try await service.stop()
- await clipboardWatcher?.stop()
- clipboardWatcher = nil
- virtualizationService = nil
- vncService.stop()
+ await cleanupSession()
Logger.info(
"VM stopped successfully via virtualization service",
metadata: ["name": vmDirContext.name])
- // Try to ensure any existing locks are released
- Logger.info(
- "Attempting to clear any locks on config file",
- metadata: ["name": vmDirContext.name])
- unlockConfigFile()
-
+ // VM.run owns the lock and releases it as its lifecycle wait returns.
return
} catch let error {
Logger.error(
@@ -796,7 +923,11 @@ class VM {
throw VMError.internalError("Virtualization service not initialized")
}
- try await vncService.start(port: port, password: password, virtualMachine: service.getVirtualMachine())
+ try await vncService.start(
+ port: port,
+ password: password,
+ virtualMachine: service.displayVirtualMachine
+ )
guard let url = vncService.url else {
throw VMError.vncNotConfigured
diff --git a/libs/lume/src/VM/VMDisplayPresenter.swift b/libs/lume/src/VM/VMDisplayPresenter.swift
new file mode 100644
index 0000000000..1f1cc3ddb3
--- /dev/null
+++ b/libs/lume/src/VM/VMDisplayPresenter.swift
@@ -0,0 +1,614 @@
+import AppKit
+import Foundation
+import Virtualization
+
+struct VMDisplayContext {
+ let virtualMachine: VZVirtualMachine?
+ let vncURL: String
+ let resolution: VMDisplayResolution
+ let vmName: String
+ let copyFromGuest: (@MainActor () async throws -> Void)?
+ let pasteIntoGuest: (@MainActor () async throws -> Void)?
+ let addSharedFolder: (@MainActor (URL, Bool) async throws -> Void)?
+
+ init(
+ virtualMachine: VZVirtualMachine?,
+ vncURL: String,
+ resolution: VMDisplayResolution,
+ vmName: String = "Lume VM",
+ copyFromGuest: (@MainActor () async throws -> Void)? = nil,
+ pasteIntoGuest: (@MainActor () async throws -> Void)? = nil,
+ addSharedFolder: (@MainActor (URL, Bool) async throws -> Void)? = nil
+ ) {
+ self.virtualMachine = virtualMachine
+ self.vncURL = vncURL
+ self.resolution = resolution
+ self.vmName = vmName
+ self.copyFromGuest = copyFromGuest
+ self.pasteIntoGuest = pasteIntoGuest
+ self.addSharedFolder = addSharedFolder
+ }
+}
+
+/// Presents a local view of a VM without owning its lifecycle or remote display service.
+@MainActor
+protocol VMDisplayPresenter: AnyObject {
+ func show(context: VMDisplayContext) async throws
+ func virtualMachineDidStart()
+ func hide()
+}
+
+extension VMDisplayPresenter {
+ func virtualMachineDidStart() {}
+}
+
+@MainActor
+final class NoDisplayPresenter: VMDisplayPresenter {
+ func show(context: VMDisplayContext) async throws {}
+ func hide() {}
+}
+
+@MainActor
+final class VNCClientPresenter: VMDisplayPresenter {
+ private let vncService: VNCService
+
+ init(vncService: VNCService) {
+ self.vncService = vncService
+ }
+
+ func show(context: VMDisplayContext) async throws {
+ try await vncService.openClient(url: context.vncURL)
+ }
+
+ func hide() {}
+}
+
+enum VMDisplayPresenterError: LocalizedError {
+ case virtualMachineUnavailable
+ case applicationSetupFailed
+
+ var errorDescription: String? {
+ switch self {
+ case .virtualMachineUnavailable:
+ return "The native display requires a Virtualization.framework virtual machine."
+ case .applicationSetupFailed:
+ return "Failed to initialize the native display application."
+ }
+ }
+}
+
+private enum NativeClipboardShortcut {
+ case copy
+ case paste
+}
+
+@MainActor
+private final class NativeVirtualMachineView: VZVirtualMachineView {
+ var onClipboardShortcut: ((NativeClipboardShortcut) -> Bool)?
+
+ override func keyDown(with event: NSEvent) {
+ let modifiers = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
+ if !event.isARepeat, modifiers.contains(.command) {
+ let shortcut: NativeClipboardShortcut?
+ switch event.keyCode {
+ case 8:
+ shortcut = .copy
+ case 9:
+ shortcut = .paste
+ default:
+ shortcut = nil
+ }
+ if let shortcut, onClipboardShortcut?(shortcut) == true {
+ return
+ }
+ }
+ super.keyDown(with: event)
+ }
+}
+
+private extension NSToolbarItem.Identifier {
+ static let lumeCopy = NSToolbarItem.Identifier("ai.cua.lume.native.copy")
+ static let lumePaste = NSToolbarItem.Identifier("ai.cua.lume.native.paste")
+ static let lumeShareFolder = NSToolbarItem.Identifier("ai.cua.lume.native.share-folder")
+ static let lumeCaptureKeys = NSToolbarItem.Identifier("ai.cua.lume.native.capture-keys")
+}
+
+/// An in-process AppKit window attached to the VZVirtualMachine owned by Lume.
+/// Closing this window only detaches the view; it never stops the guest.
+@MainActor
+final class NativeVMDisplayPresenter: NSObject, VMDisplayPresenter, NSWindowDelegate,
+ NSApplicationDelegate, NSToolbarDelegate
+{
+ private var window: NSWindow?
+ private var machineView: NativeVirtualMachineView?
+ private weak var virtualMachine: VZVirtualMachine?
+ private var overlayView: NSVisualEffectView?
+ private var overlayLabel: NSTextField?
+ private var overlayTask: Task<Void, Never>?
+ private var resolution = VMDisplayResolution(string: "1024x768")!
+ private var vmName = "Lume VM"
+ 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 captureSystemKeysItem: NSMenuItem?
+ private var captureSystemKeysToolbarItem: NSToolbarItem?
+ private var showWindowItem: NSMenuItem?
+ private var ownsApplicationRunLoop = false
+
+ func show(context: VMDisplayContext) async throws {
+ guard let virtualMachine = context.virtualMachine else {
+ throw VMDisplayPresenterError.virtualMachineUnavailable
+ }
+
+ self.virtualMachine = virtualMachine
+ resolution = context.resolution
+ vmName = context.vmName
+ copyFromGuestAction = context.copyFromGuest
+ pasteIntoGuestAction = context.pasteIntoGuest
+ addSharedFolderAction = context.addSharedFolder
+
+ let application = NSApplication.shared
+ if application.activationPolicy() != .regular {
+ guard application.setActivationPolicy(.regular) else {
+ throw VMDisplayPresenterError.applicationSetupFailed
+ }
+ }
+ application.delegate = self
+ application.dockTile.badgeLabel = vmName
+ application.dockTile.display()
+ if !application.isRunning && !NativeApplicationLoop.isActive {
+ application.finishLaunching()
+ }
+
+ installMenu(in: application)
+ createWindowIfNeeded()
+ attachAndShow()
+ NativeApplicationLoop.nativeWindowDidOpen()
+ }
+
+ func virtualMachineDidStart() {
+ guard !NativeApplicationLoop.isActive else { return }
+
+ // Fallback for callers that invoke Run directly instead of using Lume.main.
+ if !NSApplication.shared.isRunning {
+ ownsApplicationRunLoop = true
+ DispatchQueue.main.async { [weak self] in
+ guard self?.ownsApplicationRunLoop == true else { return }
+ NSApplication.shared.run()
+ }
+ }
+ }
+
+ func hide() {
+ overlayTask?.cancel()
+ overlayTask = nil
+ machineView?.onClipboardShortcut = nil
+ machineView?.virtualMachine = nil
+ window?.delegate = nil
+ window?.orderOut(nil)
+ window?.close()
+ window = nil
+ machineView = nil
+ overlayView = nil
+ overlayLabel = nil
+ virtualMachine = nil
+ copyFromGuestAction = nil
+ pasteIntoGuestAction = nil
+ addSharedFolderAction = nil
+ captureSystemKeysItem = nil
+ captureSystemKeysToolbarItem = nil
+ showWindowItem = nil
+
+ let application = NSApplication.shared
+ if application.delegate === self {
+ application.delegate = nil
+ }
+ application.dockTile.badgeLabel = nil
+ application.dockTile.display()
+ if ownsApplicationRunLoop {
+ ownsApplicationRunLoop = false
+ if application.isRunning {
+ application.stop(nil)
+ if let wakeEvent = NSEvent.otherEvent(
+ with: .applicationDefined,
+ location: .zero,
+ modifierFlags: [],
+ timestamp: 0,
+ windowNumber: 0,
+ context: nil,
+ subtype: 0,
+ data1: 0,
+ data2: 0
+ ) {
+ application.postEvent(wakeEvent, atStart: false)
+ }
+ }
+ }
+ }
+
+ private func createWindowIfNeeded() {
+ guard window == nil else { return }
+
+ let initialSize = initialWindowSize(for: resolution)
+ let container = NSView(frame: NSRect(origin: .zero, size: initialSize))
+
+ let view = NativeVirtualMachineView(frame: container.bounds)
+ view.autoresizingMask = [.width, .height]
+ // Keep fixed scaling until native/VNC dynamic-resolution coexistence is validated.
+ view.automaticallyReconfiguresDisplay = false
+ view.capturesSystemKeys = false
+ view.onClipboardShortcut = { [weak self] shortcut in
+ guard let self else { return false }
+ switch shortcut {
+ case .copy:
+ guard copyFromGuestAction != nil else { return false }
+ requestCopyFromGuest()
+ case .paste:
+ guard pasteIntoGuestAction != nil else { return false }
+ requestPasteIntoGuest()
+ }
+ return true
+ }
+ container.addSubview(view)
+
+ let overlayView = NSVisualEffectView()
+ overlayView.translatesAutoresizingMaskIntoConstraints = false
+ overlayView.material = .hudWindow
+ overlayView.blendingMode = .withinWindow
+ overlayView.state = .active
+ overlayView.isHidden = true
+ overlayView.wantsLayer = true
+ overlayView.layer?.cornerRadius = 10
+ overlayView.layer?.masksToBounds = true
+
+ let overlayLabel = NSTextField(labelWithString: "")
+ overlayLabel.translatesAutoresizingMaskIntoConstraints = false
+ overlayLabel.alignment = .center
+ overlayLabel.font = .systemFont(ofSize: 15, weight: .semibold)
+ overlayLabel.textColor = .white
+ overlayLabel.isBezeled = false
+ overlayLabel.isEditable = false
+ overlayLabel.isSelectable = false
+ overlayView.addSubview(overlayLabel)
+ container.addSubview(overlayView)
+ NSLayoutConstraint.activate([
+ overlayView.centerXAnchor.constraint(equalTo: container.centerXAnchor),
+ overlayView.centerYAnchor.constraint(equalTo: container.centerYAnchor),
+ overlayView.widthAnchor.constraint(equalToConstant: 360),
+ overlayView.heightAnchor.constraint(equalToConstant: 48),
+ overlayLabel.leadingAnchor.constraint(equalTo: overlayView.leadingAnchor, constant: 16),
+ overlayLabel.trailingAnchor.constraint(equalTo: overlayView.trailingAnchor, constant: -16),
+ overlayLabel.centerYAnchor.constraint(equalTo: overlayView.centerYAnchor),
+ ])
+
+ let window = NSWindow(
+ contentRect: NSRect(origin: .zero, size: initialSize),
+ styleMask: [.titled, .closable, .miniaturizable, .resizable],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "Lume — \(vmName)"
+ window.subtitle = "System keys remain with host"
+ window.contentView = container
+ window.contentAspectRatio = NSSize(width: resolution.width, height: resolution.height)
+ window.isReleasedWhenClosed = false
+ window.delegate = self
+ window.collectionBehavior.insert(.fullScreenPrimary)
+ window.toolbarStyle = .unified
+ window.toolbar = makeToolbar()
+ window.center()
+
+ self.machineView = view
+ self.overlayView = overlayView
+ self.overlayLabel = overlayLabel
+ self.window = window
+ }
+
+ private func makeToolbar() -> NSToolbar {
+ let toolbar = NSToolbar(identifier: "ai.cua.lume.native.toolbar")
+ toolbar.delegate = self
+ toolbar.displayMode = .iconAndLabel
+ toolbar.allowsUserCustomization = false
+ toolbar.autosavesConfiguration = false
+ return toolbar
+ }
+
+ private func initialWindowSize(for resolution: VMDisplayResolution) -> NSSize {
+ let requested = NSSize(width: resolution.width, height: resolution.height)
+ guard let visibleFrame = NSScreen.main?.visibleFrame else { return requested }
+
+ let maxWidth = max(640, visibleFrame.width * 0.9)
+ let maxHeight = max(480, visibleFrame.height * 0.9)
+ let scale = min(1, maxWidth / requested.width, maxHeight / requested.height)
+ return NSSize(width: requested.width * scale, height: requested.height * scale)
+ }
+
+ private func attachAndShow() {
+ guard let window, let machineView, let virtualMachine else { return }
+ machineView.virtualMachine = virtualMachine
+ window.makeKeyAndOrderFront(nil)
+ window.makeFirstResponder(machineView)
+ NSApplication.shared.activate(ignoringOtherApps: true)
+ }
+
+ private func installMenu(in application: NSApplication) {
+ let mainMenu = NSMenu()
+
+ let applicationItem = NSMenuItem()
+ applicationItem.submenu = NSMenu(title: "Lume — \(vmName)")
+ mainMenu.addItem(applicationItem)
+
+ let fileItem = NSMenuItem()
+ let fileMenu = NSMenu(title: "File")
+ fileItem.submenu = fileMenu
+ mainMenu.addItem(fileItem)
+
+ let shareFolderItem = NSMenuItem(
+ title: "Share Folder…",
+ action: #selector(shareFolder(_:)),
+ keyEquivalent: ""
+ )
+ shareFolderItem.target = self
+ fileMenu.addItem(shareFolderItem)
+
+ let editItem = NSMenuItem()
+ let editMenu = NSMenu(title: "Edit")
+ editItem.submenu = editMenu
+ mainMenu.addItem(editItem)
+
+ let copyItem = NSMenuItem(
+ title: "Copy from VM",
+ action: #selector(copyFromGuest(_:)),
+ keyEquivalent: "c"
+ )
+ copyItem.target = self
+ editMenu.addItem(copyItem)
+
+ let pasteItem = NSMenuItem(
+ title: "Paste into VM",
+ action: #selector(pasteIntoGuest(_:)),
+ keyEquivalent: "v"
+ )
+ pasteItem.target = self
+ editMenu.addItem(pasteItem)
+
+ let windowItem = NSMenuItem()
+ let windowMenu = NSMenu(title: "Window")
+ windowItem.submenu = windowMenu
+ mainMenu.addItem(windowItem)
+
+ let showItem = NSMenuItem(
+ title: "Show VM Window",
+ action: #selector(showWindow(_:)),
+ keyEquivalent: "0"
+ )
+ showItem.target = self
+ windowMenu.addItem(showItem)
+ showWindowItem = showItem
+
+ windowMenu.addItem(.separator())
+ let captureItem = NSMenuItem(
+ title: "Capture System Keys",
+ action: #selector(toggleSystemKeyCapture(_:)),
+ keyEquivalent: "k"
+ )
+ captureItem.keyEquivalentModifierMask = [.command, .shift]
+ captureItem.target = self
+ captureItem.state = .off
+ windowMenu.addItem(captureItem)
+ captureSystemKeysItem = captureItem
+
+ application.mainMenu = mainMenu
+ application.windowsMenu = windowMenu
+ }
+
+ @objc private func showWindow(_ sender: Any?) {
+ createWindowIfNeeded()
+ attachAndShow()
+ }
+
+ @objc private func copyFromGuest(_ sender: Any?) {
+ requestCopyFromGuest()
+ }
+
+ @objc private func pasteIntoGuest(_ sender: Any?) {
+ requestPasteIntoGuest()
+ }
+
+ @objc private func shareFolder(_ sender: Any?) {
+ guard let window, let addSharedFolderAction else {
+ showOverlay("Folder sharing unavailable")
+ return
+ }
+
+ let panel = NSOpenPanel()
+ panel.title = "Share a Folder with \(vmName)"
+ panel.prompt = "Share"
+ panel.canChooseDirectories = true
+ panel.canChooseFiles = false
+ panel.allowsMultipleSelection = false
+ panel.canCreateDirectories = true
+
+ let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 260, height: 28))
+ let readOnlyButton = NSButton(
+ checkboxWithTitle: "Share as read-only",
+ target: nil,
+ action: nil
+ )
+ readOnlyButton.frame = accessory.bounds
+ accessory.addSubview(readOnlyButton)
+ panel.accessoryView = accessory
+
+ panel.beginSheetModal(for: window) { [weak self] response in
+ guard response == .OK, let url = panel.url else { return }
+ let readOnly = readOnlyButton.state == .on
+ Task { @MainActor [weak self] in
+ self?.showOverlay("Sharing \(url.lastPathComponent)…")
+ do {
+ try await addSharedFolderAction(url, readOnly)
+ self?.showOverlay("Shared in /Volumes/My Shared Files")
+ } catch {
+ self?.showOverlay("Share failed — \(error.localizedDescription)")
+ }
+ }
+ }
+ }
+
+ private func requestCopyFromGuest() {
+ guard let copyFromGuestAction else {
+ showOverlay("Copy unavailable")
+ return
+ }
+ showOverlay("Sending ⌘C to VM…")
+ Task { @MainActor [weak self] in
+ do {
+ try await copyFromGuestAction()
+ self?.showOverlay("Copied from VM")
+ } catch {
+ self?.showOverlay("Copy failed — \(error.localizedDescription)")
+ }
+ }
+ }
+
+ private func requestPasteIntoGuest() {
+ guard let pasteIntoGuestAction else {
+ showOverlay("Paste unavailable")
+ return
+ }
+ showOverlay("Syncing clipboard to VM…")
+ Task { @MainActor [weak self] in
+ do {
+ try await pasteIntoGuestAction()
+ self?.showOverlay("Pasted into VM")
+ } catch {
+ self?.showOverlay("Paste failed — \(error.localizedDescription)")
+ }
+ }
+ }
+
+ private func showOverlay(_ message: String) {
+ guard let overlayView, let overlayLabel else { return }
+ overlayTask?.cancel()
+ overlayLabel.stringValue = message
+ overlayView.alphaValue = 1
+ overlayView.isHidden = false
+
+ 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 }
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.25
+ overlayView.animator().alphaValue = 0
+ } completionHandler: {
+ Task { @MainActor in
+ overlayView.isHidden = true
+ overlayView.alphaValue = 1
+ }
+ }
+ }
+ }
+
+ @objc private func toggleSystemKeyCapture(_ sender: Any?) {
+ let shouldCapture = !(machineView?.capturesSystemKeys ?? false)
+ machineView?.capturesSystemKeys = shouldCapture
+ captureSystemKeysItem?.state = shouldCapture ? .on : .off
+ captureSystemKeysToolbarItem?.label = shouldCapture ? "Release Keys" : "Capture Keys"
+ captureSystemKeysToolbarItem?.toolTip = shouldCapture
+ ? "Return system shortcuts to the host (⇧⌘K)"
+ : "Send system shortcuts to the VM (⇧⌘K)"
+ window?.subtitle = shouldCapture
+ ? "System keys captured — ⇧⌘K to release"
+ : "System keys remain with host"
+ showOverlay(shouldCapture ? "Keyboard capture enabled" : "Keyboard capture disabled")
+ window?.makeFirstResponder(machineView)
+ }
+
+ func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
+ [.lumeCopy, .lumePaste, .lumeShareFolder, .flexibleSpace, .lumeCaptureKeys]
+ }
+
+ func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
+ [.lumeCopy, .lumePaste, .lumeShareFolder, .flexibleSpace, .lumeCaptureKeys]
+ }
+
+ func toolbar(
+ _ toolbar: NSToolbar,
+ itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,
+ willBeInsertedIntoToolbar flag: Bool
+ ) -> NSToolbarItem? {
+ 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.target = self
+ item.action = #selector(copyFromGuest(_:))
+ 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.target = self
+ item.action = #selector(pasteIntoGuest(_:))
+ case .lumeShareFolder:
+ item.label = "Share Folder"
+ item.paletteLabel = "Share Folder"
+ item.toolTip = "Expose a host folder to the running VM with VirtioFS"
+ item.image = NSImage(
+ systemSymbolName: "folder.badge.plus",
+ accessibilityDescription: "Share Folder"
+ )
+ item.target = self
+ item.action = #selector(shareFolder(_:))
+ case .lumeCaptureKeys:
+ item.label = "Capture Keys"
+ item.paletteLabel = "Capture System Keys"
+ item.toolTip = "Send system shortcuts to the VM (⇧⌘K)"
+ item.image = NSImage(systemSymbolName: "keyboard", accessibilityDescription: "Capture Keys")
+ item.target = self
+ item.action = #selector(toggleSystemKeyCapture(_:))
+ captureSystemKeysToolbarItem = item
+ default:
+ return nil
+ }
+ return item
+ }
+
+ func windowShouldClose(_ sender: NSWindow) -> Bool {
+ machineView?.virtualMachine = nil
+ sender.orderOut(nil)
+ return false
+ }
+
+ func applicationShouldHandleReopen(
+ _ sender: NSApplication,
+ hasVisibleWindows flag: Bool
+ ) -> Bool {
+ if !flag {
+ createWindowIfNeeded()
+ attachAndShow()
+ }
+ return true
+ }
+
+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
+ // The guest lifecycle remains authoritative. A Dock Quit request hides the viewer.
+ machineView?.virtualMachine = nil
+ window?.orderOut(nil)
+ return .terminateCancel
+ }
+}
+
+@MainActor
+func defaultDisplayPresenter(mode: DisplayMode, vncService: VNCService) -> VMDisplayPresenter {
+ switch mode {
+ case .vnc:
+ return VNCClientPresenter(vncService: vncService)
+ case .native:
+ return NativeVMDisplayPresenter()
+ case .none:
+ return NoDisplayPresenter()
+ }
+}
diff --git a/libs/lume/src/VNC/VNCService.swift b/libs/lume/src/VNC/VNCService.swift
index 67fdbb204c..6a6daa6e24 100644
--- a/libs/lume/src/VNC/VNCService.swift
+++ b/libs/lume/src/VNC/VNCService.swift
@@ -8,7 +8,7 @@ import Network
@MainActor
protocol VNCService {
var url: String? { get }
- func start(port: Int, password: String?, virtualMachine: Any?) async throws
+ func start(port: Int, password: String?, virtualMachine: VZVirtualMachine?) async throws
func stop()
func openClient(url: String) async throws
@@ -69,7 +69,7 @@ final class DefaultVNCService: VNCService {
}
}
- func start(port: Int, password: String? = nil, virtualMachine: Any?) async throws {
+ func start(port: Int, password: String? = nil, virtualMachine: VZVirtualMachine?) async throws {
let password = password ?? Array(PassphraseGenerator().prefix(4)).joined(separator: "-")
let securityConfiguration = Dynamic._VZVNCAuthenticationSecurityConfiguration(password: password)
@@ -80,9 +80,9 @@ final class DefaultVNCService: VNCService {
let server = Dynamic._VZVNCServer(port: port, queue: DispatchQueue.main,
securityConfiguration: securityConfiguration)
- if let vm = virtualMachine as? VZVirtualMachine {
- server.virtualMachine = vm
- _virtualMachine = vm
+ if let virtualMachine {
+ server.virtualMachine = virtualMachine
+ _virtualMachine = virtualMachine
}
server.start()
diff --git a/libs/lume/src/Virtualization/VMVirtualMachineLifecycleMonitor.swift b/libs/lume/src/Virtualization/VMVirtualMachineLifecycleMonitor.swift
new file mode 100644
index 0000000000..6ad75363a4
--- /dev/null
+++ b/libs/lume/src/Virtualization/VMVirtualMachineLifecycleMonitor.swift
@@ -0,0 +1,59 @@
+import Foundation
+import Virtualization
+
+private enum VMTerminalEvent: Sendable {
+ case stopped
+ case failed(String)
+}
+
+private struct VMFatalStopError: LocalizedError {
+ let message: String
+ var errorDescription: String? { "The virtual machine stopped with an error: \(message)" }
+}
+
+/// Converts VZVirtualMachineDelegate terminal callbacks into one cancellable lifecycle wait.
+final class VMVirtualMachineLifecycleMonitor: NSObject, @unchecked Sendable,
+ VZVirtualMachineDelegate
+{
+ private let events: AsyncStream<VMTerminalEvent>
+ private let eventContinuation: AsyncStream<VMTerminalEvent>.Continuation
+ private var finished = false
+
+ override init() {
+ var continuation: AsyncStream<VMTerminalEvent>.Continuation!
+ events = AsyncStream { continuation = $0 }
+ eventContinuation = continuation
+ super.init()
+ }
+
+ func waitForStop() async throws {
+ for await event in events {
+ switch event {
+ case .stopped:
+ return
+ case .failed(let message):
+ throw VMFatalStopError(message: message)
+ }
+ }
+ throw CancellationError()
+ }
+
+ func stoppedByHost() {
+ finish(with: .stopped)
+ }
+
+ func guestDidStop(_ virtualMachine: VZVirtualMachine) {
+ finish(with: .stopped)
+ }
+
+ func virtualMachine(_ virtualMachine: VZVirtualMachine, didStopWithError error: any Error) {
+ finish(with: .failed(error.localizedDescription))
+ }
+
+ private func finish(with event: VMTerminalEvent) {
+ guard !finished else { return }
+ finished = true
+ eventContinuation.yield(event)
+ eventContinuation.finish()
+ }
+}
diff --git a/libs/lume/src/Virtualization/VMVirtualizationService.swift b/libs/lume/src/Virtualization/VMVirtualizationService.swift
index be8c8f2eb7..59a2cdf90a 100644
--- a/libs/lume/src/Virtualization/VMVirtualizationService.swift
+++ b/libs/lume/src/Virtualization/VMVirtualizationService.swift
@@ -1,4 +1,3 @@
-import AppKit
import Foundation
import Virtualization
@@ -24,39 +23,71 @@ struct VMVirtualizationServiceContext {
@MainActor
protocol VMVirtualizationService {
var state: VZVirtualMachine.State { get }
+ /// The framework VM used by native display and VNC. Test services may return nil.
+ var displayVirtualMachine: VZVirtualMachine? { get }
func start() async throws
func stop() async throws
func pause() async throws
func resume() async throws
- func getVirtualMachine() -> Any
+ func updateSharedDirectories(_ sharedDirectories: [SharedDirectory]) async throws
+ func waitForStop() async throws
}
/// Base implementation of VMVirtualizationService using VZVirtualMachine
@MainActor
class BaseVirtualizationService: VMVirtualizationService {
- let virtualMachine: VZVirtualMachine
+ final class VirtualMachineHandle: @unchecked Sendable {
+ let machine: VZVirtualMachine
+ let queue: DispatchQueue
+
+ init(machine: VZVirtualMachine, queue: DispatchQueue) {
+ self.machine = machine
+ self.queue = queue
+ }
+ }
+
+ let virtualMachineHandle: VirtualMachineHandle
+ var virtualMachine: VZVirtualMachine { virtualMachineHandle.machine }
let recoveryMode: Bool // Store whether we should start in recovery mode
+ private let lifecycleMonitor: VMVirtualMachineLifecycleMonitor
var state: VZVirtualMachine.State {
- virtualMachine.state
+ let handle = virtualMachineHandle
+ return handle.queue.sync { handle.machine.state }
}
- init(virtualMachine: VZVirtualMachine, recoveryMode: Bool = false) {
- self.virtualMachine = virtualMachine
+ var displayVirtualMachine: VZVirtualMachine? {
+ virtualMachine
+ }
+
+ init(
+ virtualMachine: VZVirtualMachine,
+ queue: DispatchQueue,
+ recoveryMode: Bool = false
+ ) {
+ self.virtualMachineHandle = VirtualMachineHandle(machine: virtualMachine, queue: queue)
self.recoveryMode = recoveryMode
+ self.lifecycleMonitor = VMVirtualMachineLifecycleMonitor()
+ let handle = virtualMachineHandle
+ let monitor = lifecycleMonitor
+ handle.queue.sync {
+ handle.machine.delegate = monitor
+ }
}
func start() async throws {
+ let handle = virtualMachineHandle
+ let recoveryMode = recoveryMode
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<Void, Error>) in
- Task { @MainActor in
+ handle.queue.async {
if #available(macOS 13, *) {
let startOptions = VZMacOSVirtualMachineStartOptions()
startOptions.startUpFromMacOSRecovery = recoveryMode
if recoveryMode {
Logger.info("Starting VM in recovery mode")
}
- virtualMachine.start(options: startOptions) { error in
+ handle.machine.start(options: startOptions) { error in
if let error = error {
continuation.resume(throwing: error)
} else {
@@ -65,7 +96,7 @@ class BaseVirtualizationService: VMVirtualizationService {
}
} else {
Logger.info("Starting VM in normal mode")
- virtualMachine.start { result in
+ handle.machine.start { result in
switch result {
case .success:
continuation.resume()
@@ -79,48 +110,79 @@ class BaseVirtualizationService: VMVirtualizationService {
}
func stop() async throws {
+ let handle = virtualMachineHandle
+ let monitor = lifecycleMonitor
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<Void, Error>) in
- virtualMachine.stop { error in
- if let error = error {
- continuation.resume(throwing: error)
- } else {
- continuation.resume()
+ handle.queue.async {
+ handle.machine.stop { error in
+ if let error = error {
+ continuation.resume(throwing: error)
+ } else {
+ monitor.stoppedByHost()
+ continuation.resume()
+ }
}
}
}
}
func pause() async throws {
+ let handle = virtualMachineHandle
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<Void, Error>) in
- virtualMachine.pause { result in
- switch result {
- case .success:
- continuation.resume()
- case .failure(let error):
- continuation.resume(throwing: error)
+ handle.queue.async {
+ handle.machine.pause { result in
+ switch result {
+ case .success:
+ continuation.resume()
+ case .failure(let error):
+ continuation.resume(throwing: error)
+ }
}
}
}
}
func resume() async throws {
+ let handle = virtualMachineHandle
+ try await withCheckedThrowingContinuation {
+ (continuation: CheckedContinuation<Void, Error>) in
+ handle.queue.async {
+ handle.machine.resume { result in
+ switch result {
+ case .success:
+ continuation.resume()
+ case .failure(let error):
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ }
+ }
+
+ func updateSharedDirectories(_ sharedDirectories: [SharedDirectory]) async throws {
+ let handle = virtualMachineHandle
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<Void, Error>) in
- virtualMachine.resume { result in
- switch result {
- case .success:
- continuation.resume()
- case .failure(let error):
- continuation.resume(throwing: error)
+ handle.queue.async {
+ guard let device = handle.machine.directorySharingDevices.first(where: {
+ ($0 as? VZVirtioFileSystemDevice)?.tag
+ == VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag
+ }) as? VZVirtioFileSystemDevice else {
+ continuation.resume(
+ throwing: VMError.internalError(
+ "The VM was not started with a live shared-folder device"))
+ return
}
+ device.share = Self.createDirectoryShare(sharedDirectories)
+ continuation.resume()
}
}
}
- func getVirtualMachine() -> Any {
- return virtualMachine
+ func waitForStop() async throws {
+ try await lifecycleMonitor.waitForStop()
}
// Helper methods for creating common configurations
@@ -214,13 +276,31 @@ class BaseVirtualizationService: VMVirtualizationService {
static func createDirectorySharingDevices(sharedDirectories: [SharedDirectory]?)
-> [VZDirectorySharingDeviceConfiguration]
{
- return sharedDirectories?.map { sharedDir in
- let device = VZVirtioFileSystemDeviceConfiguration(tag: sharedDir.tag)
- let url = URL(fileURLWithPath: sharedDir.hostPath)
- device.share = VZSingleDirectoryShare(
- directory: VZSharedDirectory(url: url, readOnly: sharedDir.readOnly))
+ let grouped = Dictionary(grouping: sharedDirectories ?? [], by: \.tag)
+ return grouped.map { tag, directories in
+ let device = VZVirtioFileSystemDeviceConfiguration(tag: tag)
+ device.share = createDirectoryShare(directories)
return device
- } ?? []
+ }
+ }
+
+ nonisolated static func createDirectoryShare(
+ _ sharedDirectories: [SharedDirectory]
+ ) -> VZDirectoryShare {
+ var directories: [String: VZSharedDirectory] = [:]
+ for sharedDirectory in sharedDirectories {
+ let url = URL(fileURLWithPath: sharedDirectory.hostPath)
+ let directory = VZSharedDirectory(url: url, readOnly: sharedDirectory.readOnly)
+ let baseName = url.lastPathComponent.isEmpty ? "Shared Folder" : url.lastPathComponent
+ var name = baseName
+ var suffix = 2
+ while directories[name] != nil {
+ name = "\(baseName) (\(suffix))"
+ suffix += 1
+ }
+ directories[name] = directory
+ }
+ return VZMultipleDirectoryShare(directories: directories)
}
}
@@ -259,26 +339,18 @@ final class DarwinVirtualizationService: BaseVirtualizationService {
vzConfig.platform = platform
vzConfig.bootLoader = VZMacOSBootLoader()
- // Graphics configuration
- // Use host screen-based display configuration when available for better
- // display compositor integration (helps with screenshot capture in VMs)
+ // Use an explicit framebuffer configuration. Deriving the display from host
+ // points and backing scale can leave VZVirtualMachineView with a black
+ // framebuffer when native and VNC displays are attached concurrently.
let display = VMDisplayResolution(string: config.display)!
let graphics = VZMacGraphicsDeviceConfiguration()
- if let hostMainScreen = NSScreen.main {
- let vmScreenSize = NSSize(width: display.width, height: display.height)
- graphics.displays = [
- VZMacGraphicsDisplayConfiguration(for: hostMainScreen, sizeInPoints: vmScreenSize)
- ]
- } else {
- // Fallback to pixel-based configuration if no host screen available
- graphics.displays = [
- VZMacGraphicsDisplayConfiguration(
- widthInPixels: display.width,
- heightInPixels: display.height,
- pixelsPerInch: 220
- )
- ]
- }
+ graphics.displays = [
+ VZMacGraphicsDisplayConfiguration(
+ widthInPixels: display.width,
+ heightInPixels: display.height,
+ pixelsPerInch: 220
+ )
+ ]
vzConfig.graphicsDevices = [graphics]
// Common configurations
@@ -371,12 +443,19 @@ final class DarwinVirtualizationService: BaseVirtualizationService {
}
}
- // Directory sharing
- let directorySharingDevices = createDirectorySharingDevices(
+ // Directory sharing. Keep an empty macOS automount device available so the
+ // native toolbar can replace its share while the VM is running.
+ var directorySharingDevices = createDirectorySharingDevices(
sharedDirectories: config.sharedDirectories)
- if !directorySharingDevices.isEmpty {
- vzConfig.directorySharingDevices = directorySharingDevices
+ let automountTag = VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag
+ if !directorySharingDevices.contains(where: {
+ ($0 as? VZVirtioFileSystemDeviceConfiguration)?.tag == automountTag
+ }) {
+ let device = VZVirtioFileSystemDeviceConfiguration(tag: automountTag)
+ device.share = createDirectoryShare([])
+ directorySharingDevices.append(device)
}
+ vzConfig.directorySharingDevices = directorySharingDevices
// USB Controller configuration
if #available(macOS 15.0, *) {
@@ -405,8 +484,13 @@ final class DarwinVirtualizationService: BaseVirtualizationService {
init(configuration: VMVirtualizationServiceContext) throws {
let vzConfig = try Self.createConfiguration(configuration)
+ let queue = DispatchQueue(
+ label: "ai.cua.lume.virtual-machine.darwin",
+ qos: .userInteractive
+ )
super.init(
- virtualMachine: VZVirtualMachine(configuration: vzConfig),
+ virtualMachine: VZVirtualMachine(configuration: vzConfig, queue: queue),
+ queue: queue,
recoveryMode: configuration.recoveryMode)
}
@@ -586,6 +670,13 @@ final class LinuxVirtualizationService: BaseVirtualizationService {
init(configuration: VMVirtualizationServiceContext) throws {
let vzConfig = try Self.createConfiguration(configuration)
- super.init(virtualMachine: VZVirtualMachine(configuration: vzConfig))
+ let queue = DispatchQueue(
+ label: "ai.cua.lume.virtual-machine.linux",
+ qos: .userInteractive
+ )
+ super.init(
+ virtualMachine: VZVirtualMachine(configuration: vzConfig, queue: queue),
+ queue: queue
+ )
}
}
diff --git a/libs/lume/tests/DisplayModeTests.swift b/libs/lume/tests/DisplayModeTests.swift
new file mode 100644
index 0000000000..d54fba7686
--- /dev/null
+++ b/libs/lume/tests/DisplayModeTests.swift
@@ -0,0 +1,50 @@
+import ArgumentParser
+import Foundation
+import Testing
+
+@testable import lume
+
+@Test("DisplayMode parses all supported values")
+func displayModeParsing() throws {
+ #expect(try Run.parse(["test-vm", "--display", "vnc"]).display == .vnc)
+ #expect(try Run.parse(["test-vm", "--display", "native"]).display == .native)
+ #expect(try Run.parse(["test-vm", "--display", "none"]).display == .none)
+ #expect(throws: Error.self) {
+ _ = try Run.parse(["test-vm", "--display", "invalid"])
+ }
+}
+
+@MainActor
+@Test("Native macOS display enables the SSH clipboard fallback")
+func nativeClipboardFallbackSelection() {
+ #expect(
+ VM.shouldStartClipboardWatcher(
+ displayMode: .native,
+ osType: "macOS",
+ explicitlyRequested: false
+ )
+ )
+ #expect(
+ !VM.shouldStartClipboardWatcher(
+ displayMode: .native,
+ osType: "linux",
+ explicitlyRequested: false
+ )
+ )
+ #expect(
+ VM.shouldStartClipboardWatcher(
+ displayMode: .vnc,
+ osType: "linux",
+ explicitlyRequested: true
+ )
+ )
+}
+
+@Test("--no-display remains an alias for display none")
+func noDisplayCompatibility() throws {
+ let command = try Run.parse(["test-vm", "--display", "native", "--no-display"])
+ let shortCommand = try Run.parse(["test-vm", "-d"])
+ #expect(command.noDisplay)
+ #expect(shortCommand.noDisplay)
+ #expect(DisplayMode.resolve(requested: command.display, noDisplay: command.noDisplay) == .none)
+}
diff --git a/libs/lume/tests/Mocks/MockVM.swift b/libs/lume/tests/Mocks/MockVM.swift
index e5c136bcbf..169d9035b2 100644
--- a/libs/lume/tests/Mocks/MockVM.swift
+++ b/libs/lume/tests/Mocks/MockVM.swift
@@ -22,14 +22,14 @@ class MockVM: VM {
}
override func run(
- noDisplay: Bool, sharedDirectories: [SharedDirectory], mount: Path?, vncPort: Int = 0,
- vncPassword: String? = nil, recoveryMode: Bool = false, usbMassStoragePaths: [Path]? = nil,
- additionalDiskPaths: [Path]? = nil,
+ displayMode: DisplayMode = .vnc, sharedDirectories: [SharedDirectory], mount: Path?,
+ vncPort: Int = 0, vncPassword: String? = nil, recoveryMode: Bool = false,
+ usbMassStoragePaths: [Path]? = nil, additionalDiskPaths: [Path]? = nil,
networkMode: NetworkMode? = nil, clipboard: Bool = false
) async throws {
mockIsRunning = true
try await super.run(
- noDisplay: noDisplay, sharedDirectories: sharedDirectories, mount: mount,
+ displayMode: displayMode, sharedDirectories: sharedDirectories, mount: mount,
vncPort: vncPort, vncPassword: vncPassword, recoveryMode: recoveryMode,
usbMassStoragePaths: usbMassStoragePaths,
additionalDiskPaths: additionalDiskPaths,
diff --git a/libs/lume/tests/Mocks/MockVMVirtualizationService.swift b/libs/lume/tests/Mocks/MockVMVirtualizationService.swift
index 7e24a6e333..383ad543c2 100644
--- a/libs/lume/tests/Mocks/MockVMVirtualizationService.swift
+++ b/libs/lume/tests/Mocks/MockVMVirtualizationService.swift
@@ -2,6 +2,11 @@ import Foundation
import Virtualization
@testable import lume
+private enum MockVMTerminalEvent: Sendable {
+ case stopped
+ case failed(String)
+}
+
@MainActor
final class MockVMVirtualizationService: VMVirtualizationService {
private(set) var currentState: VZVirtualMachine.State = .stopped
@@ -9,57 +14,93 @@ final class MockVMVirtualizationService: VMVirtualizationService {
private(set) var stopCallCount = 0
private(set) var pauseCallCount = 0
private(set) var resumeCallCount = 0
-
- var state: VZVirtualMachine.State {
- currentState
+ private(set) var updateSharedDirectoriesCallCount = 0
+ private(set) var sharedDirectories: [SharedDirectory] = []
+
+ private let terminalEvents: AsyncStream<MockVMTerminalEvent>
+ private let terminalEventContinuation: AsyncStream<MockVMTerminalEvent>.Continuation
+ private var didTerminate = false
+ private var shouldFailNextOperation = false
+ private var operationError: Error = VMError.internalError("Mock operation failed")
+
+ init() {
+ var continuation: AsyncStream<MockVMTerminalEvent>.Continuation!
+ terminalEvents = AsyncStream { continuation = $0 }
+ terminalEventContinuation = continuation
}
-
- private var _shouldFailNextOperation = false
- private var _operationError: Error = VMError.internalError("Mock operation failed")
-
- nonisolated func configure(shouldFail: Bool, error: Error = VMError.internalError("Mock operation failed")) async {
+
+ var state: VZVirtualMachine.State { currentState }
+ var displayVirtualMachine: VZVirtualMachine? { nil }
+
+ nonisolated func configure(
+ shouldFail: Bool,
+ error: Error = VMError.internalError("Mock operation failed")
+ ) async {
await setConfiguration(shouldFail: shouldFail, error: error)
}
-
- @MainActor
+
private func setConfiguration(shouldFail: Bool, error: Error) {
- _shouldFailNextOperation = shouldFail
- _operationError = error
+ shouldFailNextOperation = shouldFail
+ operationError = error
}
-
+
func start() async throws {
startCallCount += 1
- if _shouldFailNextOperation {
- throw _operationError
- }
+ if shouldFailNextOperation { throw operationError }
currentState = .running
}
-
+
func stop() async throws {
stopCallCount += 1
- if _shouldFailNextOperation {
- throw _operationError
+ if shouldFailNextOperation { throw operationError }
+ currentState = .stopped
+ finish(with: .stopped)
+ }
+
+ func updateSharedDirectories(_ sharedDirectories: [SharedDirectory]) async throws {
+ updateSharedDirectoriesCallCount += 1
+ if shouldFailNextOperation { throw operationError }
+ self.sharedDirectories = sharedDirectories
+ }
+
+ func waitForStop() async throws {
+ for await event in terminalEvents {
+ switch event {
+ case .stopped:
+ return
+ case .failed(let message):
+ throw VMError.internalError(message)
+ }
}
+ throw CancellationError()
+ }
+
+ func simulateGuestStop() {
currentState = .stopped
+ finish(with: .stopped)
}
-
+
+ func simulateFatalStop(error: Error = VMError.internalError("Mock VM stopped fatally")) {
+ currentState = .stopped
+ finish(with: .failed(error.localizedDescription))
+ }
+
+ private func finish(with event: MockVMTerminalEvent) {
+ guard !didTerminate else { return }
+ didTerminate = true
+ terminalEventContinuation.yield(event)
+ terminalEventContinuation.finish()
+ }
+
func pause() async throws {
pauseCallCount += 1
- if _shouldFailNextOperation {
- throw _operationError
- }
+ if shouldFailNextOperation { throw operationError }
currentState = .paused
}
-
+
func resume() async throws {
resumeCallCount += 1
- if _shouldFailNextOperation {
- throw _operationError
- }
+ if shouldFailNextOperation { throw operationError }
currentState = .running
}
-
- func getVirtualMachine() -> Any {
- return "mock_vm"
- }
-}
\ No newline at end of file
+}
diff --git a/libs/lume/tests/Mocks/MockVNCService.swift b/libs/lume/tests/Mocks/MockVNCService.swift
index 1bc8f16d8d..0961da3887 100644
--- a/libs/lume/tests/Mocks/MockVNCService.swift
+++ b/libs/lume/tests/Mocks/MockVNCService.swift
@@ -8,17 +8,19 @@ final class MockVNCService: VNCService {
private(set) var url: String?
private(set) var isRunning = false
private(set) var clientOpenCount = 0
- private var _attachedVM: Any?
+ private(set) var startCallCount = 0
+ private(set) var stopCallCount = 0
+ private var _attachedVM: VZVirtualMachine?
private let vmDirectory: VMDirectory
init(vmDirectory: VMDirectory) {
self.vmDirectory = vmDirectory
}
- nonisolated var attachedVM: String? {
+ nonisolated var hasAttachedVM: Bool {
get async {
await Task { @MainActor in
- _attachedVM as? String
+ _attachedVM != nil
}.value
}
}
@@ -29,13 +31,15 @@ final class MockVNCService: VNCService {
return nil
}
- func start(port: Int, password: String? = nil, virtualMachine: Any?) async throws {
+ func start(port: Int, password: String? = nil, virtualMachine: VZVirtualMachine?) async throws {
+ startCallCount += 1
isRunning = true
url = "vnc://localhost:\(port)"
_attachedVM = virtualMachine
}
func stop() {
+ stopCallCount += 1
isRunning = false
url = nil
_attachedVM = nil
diff --git a/libs/lume/tests/VMDisplayLifecycleTests.swift b/libs/lume/tests/VMDisplayLifecycleTests.swift
new file mode 100644
index 0000000000..c587fe6622
--- /dev/null
+++ b/libs/lume/tests/VMDisplayLifecycleTests.swift
@@ -0,0 +1,192 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+private enum PresenterTestError: Error {
+ case showFailed
+}
+
+@MainActor
+private final class MockDisplayPresenter: VMDisplayPresenter {
+ private(set) var showCount = 0
+ private(set) var hideCount = 0
+ var showError: Error?
+
+ func show(context: VMDisplayContext) async throws {
+ showCount += 1
+ if let showError { throw showError }
+ }
+
+ func hide() {
+ hideCount += 1
+ }
+}
+
+private func makeDisplayTestDirectory() throws -> (URL, VMDirectory, VMDirContext) {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let directory = VMDirectory(Path(root.path))
+ try Data(repeating: 0, count: 1024).write(to: directory.diskPath.url)
+ try Data(repeating: 0, count: 1024).write(to: directory.nvramPath.url)
+
+ var config = try VMConfig(
+ os: "mock-os",
+ cpuCount: 1,
+ memorySize: 1024,
+ diskSize: 1024,
+ display: "1024x768"
+ )
+ config.setMacAddress("00:11:22:33:44:55")
+ try directory.saveConfig(config)
+ try Data().write(to: directory.dir.file(".initialized").url)
+
+ return (
+ root,
+ directory,
+ VMDirContext(
+ dir: directory,
+ config: config,
+ home: Home(fileManager: .default),
+ storage: nil
+ )
+ )
+}
+
+@MainActor
+private func waitUntil(
+ timeout: Duration = .seconds(2),
+ _ condition: @escaping @MainActor () -> Bool
+) async throws {
+ let clock = ContinuousClock()
+ let deadline = clock.now.advanced(by: timeout)
+ while !condition() {
+ guard clock.now < deadline else {
+ Issue.record("Timed out waiting for asynchronous VM state")
+ return
+ }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+}
+
+@MainActor
+@Test("Every display mode uses the selected presenter and cleans it up once")
+func presenterSelectionAndGuestShutdownCleanup() async throws {
+ for mode in DisplayMode.allCases {
+ let (root, _, context) = try makeDisplayTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = MockDisplayPresenter()
+ var selectedMode: DisplayMode?
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { mode, _ in
+ selectedMode = mode
+ return presenter
+ }
+ )
+
+ let runTask = Task {
+ try await vm.run(displayMode: mode, sharedDirectories: [], mount: nil)
+ }
+ try await waitUntil { presenter.showCount == 1 }
+ service.simulateGuestStop()
+ try await runTask.value
+
+ #expect(selectedMode == mode)
+ #expect(presenter.showCount == 1)
+ #expect(presenter.hideCount == 1)
+ #expect(vnc.startCallCount == 1)
+ #expect(vnc.stopCallCount == 1)
+ #expect(service.stopCallCount == 0)
+ }
+}
+
+@MainActor
+@Test("Fatal guest stop releases presenter and VNC resources")
+func fatalGuestStopCleanup() async throws {
+ let (root, _, context) = try makeDisplayTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = MockDisplayPresenter()
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in presenter }
+ )
+
+ let runTask = Task {
+ try await vm.run(displayMode: .native, sharedDirectories: [], mount: nil)
+ }
+ try await waitUntil { presenter.showCount == 1 }
+ service.simulateFatalStop()
+ await #expect(throws: VMError.self) {
+ try await runTask.value
+ }
+
+ #expect(service.stopCallCount == 0)
+ #expect(presenter.hideCount == 1)
+ #expect(vnc.stopCallCount == 1)
+}
+
+@MainActor
+@Test("Native presenter creation failure stops the VM and releases session resources")
+func presenterFailureCleanup() async throws {
+ let (root, _, context) = try makeDisplayTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = MockDisplayPresenter()
+ presenter.showError = PresenterTestError.showFailed
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in presenter }
+ )
+
+ await #expect(throws: PresenterTestError.self) {
+ try await vm.run(displayMode: .native, sharedDirectories: [], mount: nil)
+ }
+ #expect(service.stopCallCount == 1)
+ #expect(presenter.hideCount == 1)
+ #expect(vnc.stopCallCount == 1)
+}
+
+@MainActor
+@Test("Cancelling VM run stops the guest and cleans up exactly once")
+func cancellationCleanup() async throws {
+ let (root, _, context) = try makeDisplayTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = MockDisplayPresenter()
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in presenter }
+ )
+
+ let runTask = Task {
+ try await vm.run(displayMode: .none, sharedDirectories: [], mount: nil)
+ }
+ try await waitUntil { presenter.showCount == 1 }
+ runTask.cancel()
+ await #expect(throws: CancellationError.self) {
+ try await runTask.value
+ }
+
+ #expect(service.stopCallCount == 1)
+ #expect(presenter.hideCount == 1)
+ #expect(vnc.stopCallCount == 1)
+}
diff --git a/libs/lume/tests/VMTests.swift b/libs/lume/tests/VMTests.swift
index 9afdca8311..3a58f039cf 100644
--- a/libs/lume/tests/VMTests.swift
+++ b/libs/lume/tests/VMTests.swift
@@ -99,7 +99,7 @@ func testVMRunAndStop() async throws {
// Test running VM
let runTask = Task {
try await vm.run(
- noDisplay: false, sharedDirectories: [], mount: nil as Path?, vncPort: 0,
+ displayMode: .vnc, sharedDirectories: [], mount: nil as Path?, vncPort: 0,
recoveryMode: false)
}
diff --git a/libs/lume/tests/VMVirtualizationServiceTests.swift b/libs/lume/tests/VMVirtualizationServiceTests.swift
index 6346335896..ede73af384 100644
--- a/libs/lume/tests/VMVirtualizationServiceTests.swift
+++ b/libs/lume/tests/VMVirtualizationServiceTests.swift
@@ -3,6 +3,7 @@ import Testing
import Virtualization
@testable import lume
+@MainActor
@Test("VMVirtualizationService starts correctly")
func testVMVirtualizationServiceStart() async throws {
let service = MockVMVirtualizationService()
@@ -17,6 +18,7 @@ func testVMVirtualizationServiceStart() async throws {
#expect(await service.startCallCount == 1)
}
+@MainActor
@Test("VMVirtualizationService stops correctly")
func testVMVirtualizationServiceStop() async throws {
let service = MockVMVirtualizationService()
@@ -29,6 +31,7 @@ func testVMVirtualizationServiceStop() async throws {
#expect(await service.stopCallCount == 1)
}
+@MainActor
@Test("VMVirtualizationService handles pause and resume")
func testVMVirtualizationServicePauseResume() async throws {
let service = MockVMVirtualizationService()
@@ -45,6 +48,7 @@ func testVMVirtualizationServicePauseResume() async throws {
#expect(await service.resumeCallCount == 1)
}
+@MainActor
@Test("VMVirtualizationService handles operation failures")
func testVMVirtualizationServiceFailures() async throws {
let service = MockVMVirtualizationService()
@@ -65,4 +69,27 @@ func testVMVirtualizationServiceFailures() async throws {
#expect(await service.state == .stopped)
#expect(await service.startCallCount == 1)
-}
\ No newline at end of file
+}
+
+@MainActor
+@Test("Shared directories with one tag use a disambiguated multiple-directory share")
+func testSharedDirectoryGrouping() throws {
+ let tag = VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag
+ let sharedDirectories = [
+ SharedDirectory(hostPath: "/tmp/first/Shared", tag: tag, readOnly: false),
+ SharedDirectory(hostPath: "/tmp/second/Shared", tag: tag, readOnly: true),
+ ]
+
+ let devices = BaseVirtualizationService.createDirectorySharingDevices(
+ sharedDirectories: sharedDirectories
+ )
+ let device = try #require(devices.first as? VZVirtioFileSystemDeviceConfiguration)
+ let share = try #require(device.share as? VZMultipleDirectoryShare)
+
+ #expect(devices.count == 1)
+ #expect(device.tag == tag)
+ let names = Swift.Set<String>(share.directories.keys)
+ #expect(names == Swift.Set(["Shared", "Shared (2)"]))
+ #expect(share.directories["Shared"]?.isReadOnly == false)
+ #expect(share.directories["Shared (2)"]?.isReadOnly == true)
+}
\ No newline at end of file
diff --git a/libs/lume/tests/VNCServiceTests.swift b/libs/lume/tests/VNCServiceTests.swift
index 44dd8989d2..29c8a98cc3 100644
--- a/libs/lume/tests/VNCServiceTests.swift
+++ b/libs/lume/tests/VNCServiceTests.swift
@@ -70,17 +70,16 @@ func testVNCServiceClient() async throws {
}
}
-@Test("VNCService handles virtual machine attachment")
+@MainActor
+@Test("VNCService accepts an unavailable typed virtual machine")
func testVNCServiceVMAttachment() async throws {
let tempDir = try createTempDirectory()
defer { try? FileManager.default.removeItem(at: tempDir) }
let vmDir = VMDirectory(Path(tempDir.path))
- let service = await MockVNCService(vmDirectory: vmDir)
- let mockVM = "mock_vm"
-
- try await service.start(port: 5900, virtualMachine: mockVM)
- let attachedVM = await service.attachedVM
- #expect(attachedVM == mockVM)
+ let service = MockVNCService(vmDirectory: vmDir)
+
+ try await service.start(port: 5900, virtualMachine: nil)
+ #expect(await !service.hasAttachedVM)
}
private func createTempDirectory() throws -> URL {