Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(lume): add live display attach and guest power commands (#2642)
Francesco Bonacci57fae6aed071
diff --git a/docs/content/docs/how-to-guides/lume/create-vanilla-vm.mdx b/docs/content/docs/how-to-guides/lume/create-vanilla-vm.mdxindex 99b99d0531..a3c930ad01 100644--- a/docs/content/docs/how-to-guides/lume/create-vanilla-vm.mdx+++ b/docs/content/docs/how-to-guides/lume/create-vanilla-vm.mdx@@ -37,13 +37,15 @@ lume lslume ssh macos-tahoe 'sw_vers; id -un'```-Use `lume run` with no `--no-display` flag when you want the VNC display. Use-`lume run --no-display macos-tahoe` for a headless boot.+`lume run` starts without opening a viewer while keeping VNC available. Use+`lume attach macos-tahoe` to open the preferred viewer, or select one explicitly+with `--display native` or `--display vnc`.## Stop or remove it```bash-lume stop macos-tahoe+lume shutdown macos-tahoe # graceful guest shutdown+lume stop macos-tahoe # immediate process-level stoplume delete macos-tahoe```diff --git a/docs/content/docs/how-to-guides/lume/manage-vms.mdx b/docs/content/docs/how-to-guides/lume/manage-vms.mdxindex 3ca7483377..1ab316f3de 100644--- a/docs/content/docs/how-to-guides/lume/manage-vms.mdx+++ b/docs/content/docs/how-to-guides/lume/manage-vms.mdx@@ -23,42 +23,48 @@ lume get macos-tahoeThe details include the VM state, IP address, display session, resources, andSSH availability when the VM is running.-## Run and stop a VM+## Run, attach to, and stop a VM-Run Tahoe with the default Screen Sharing viewer:+Run Tahoe without automatically opening a viewer:```bashlume run macos-tahoe-# Equivalent to: lume run macos-tahoe --display vnc```-Use Lume's lower-latency native macOS viewer instead:+VNC remains active in the background. From another terminal, attach the+preferred viewer; Lume uses its native viewer when the owning process supports+live attachment and otherwise falls back to VNC:```bash-lume run macos-tahoe --display native+lume attach macos-tahoe```-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):+Select a viewer explicitly when needed:```bash-lume run macos-tahoe --display none+lume attach macos-tahoe --display native+lume attach macos-tahoe --display vnc```-VNC remains available in all three modes. To open Screen Sharing for an-already-running VM without restarting it:+You can also start and immediately open a viewer:```bash-open "$(lume get macos-tahoe --format json | \- plutil -extract 0.vncUrl raw -o - -)"+lume run macos-tahoe --display native+lume run macos-tahoe --display vnc```-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.+Closing the native window only hides it; it does not stop the guest. Reopen it+from Lume's Dock icon, **Window → Show VM Window**, or another `lume attach`+command. The older `--no-display` flag remains an alias for `--display none`.++Gracefully restart or shut down a guest over SSH:++```bash+lume restart macos-tahoe+lume shutdown macos-tahoe+```-Stop it when you are finished:+Keep `stop` for an immediate process-level stop:```bashlume stop macos-tahoediff --git a/docs/content/docs/how-to-guides/lume/run-openclaw.mdx b/docs/content/docs/how-to-guides/lume/run-openclaw.mdxindex c3e286a8d2..ca23a5cc61 100644--- a/docs/content/docs/how-to-guides/lume/run-openclaw.mdx+++ b/docs/content/docs/how-to-guides/lume/run-openclaw.mdx@@ -133,8 +133,9 @@ open an interactive guest shell and run `openclaw gateway install`.### A macOS permission prompt never appears-Restart the VM with `lume run openclaw`, open a terminal in the VM display, and-run the command that needs permission from that logged-in session.+Restart the VM with `lume run openclaw`, open its display with+`lume attach openclaw`, then run the command that needs permission from a guest+terminal in that logged-in session.## Related guidesdiff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdxindex 4797c20d6e..edf1f48018 100644--- a/docs/content/docs/reference/lume/cli-reference.mdx+++ b/docs/content/docs/reference/lume/cli-reference.mdx@@ -70,7 +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 |+| `--display` | DisplayMode | none | 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 |@@ -82,6 +82,61 @@ Run a virtual machine| `-d, --no-display` | false | Compatibility alias for --display none || `--clipboard` | false | Enable bidirectional clipboard sync via SSH. Automatic for native macOS display |+### lume attach++Open a viewer for a running virtual machine++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Name of the virtual machine |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `--display` | AttachDisplayMode | native with VNC fallback | Viewer to open: native or vnc |+| `--storage` | String | - | VM storage location to use |++### lume shutdown++Gracefully shut down a virtual machine++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Name of the virtual machine |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `-u, --user` | String | lume | SSH username |+| `-p, --password` | String | lume | SSH and sudo password |+| `--storage` | String | - | VM storage location to use |+| `-t, --timeout` | Int | 30 | SSH command timeout in seconds |++### lume restart++Gracefully restart a virtual machine++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Name of the virtual machine |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `-u, --user` | String | lume | SSH username |+| `-p, --password` | String | lume | SSH and sudo password |+| `--storage` | String | - | VM storage location to use |+| `-t, --timeout` | Int | 30 | SSH command timeout in seconds |+### lume stopStop a virtual machinediff --git a/libs/lume/src/Commands/Attach.swift b/libs/lume/src/Commands/Attach.swiftnew file mode 100644index 0000000000..49e96e7d4e--- /dev/null+++ b/libs/lume/src/Commands/Attach.swift@@ -0,0 +1,95 @@+import AppKit+import ArgumentParser+import Foundation++enum AttachDisplayMode: String, CaseIterable, ExpressibleByArgument, Sendable {+ case native+ case vnc+}++enum AttachError: LocalizedError {+ case vmNotRunning(String)+ case vncUnavailable(String)+ case failedToOpenVNC++ var errorDescription: String? {+ switch self {+ case .vmNotRunning(let name):+ return "VM '\(name)' is not running."+ case .vncUnavailable(let name):+ return "VM '\(name)' does not have an active VNC session."+ case .failedToOpenVNC:+ return "Failed to open the VNC session in Screen Sharing."+ }+ }+}++struct Attach: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "attach",+ abstract: "Open a viewer for a running virtual machine",+ discussion: """+ Native display is preferred when the owning `lume run` process supports+ live attachment. VNC is used as the automatic fallback.+ """+ )++ @Argument(help: "Name of the virtual machine", completion: .custom(completeVMName))+ var name: String++ @Option(help: "Viewer to open: 'native' or 'vnc' (default: native with VNC fallback)")+ var display: AttachDisplayMode?++ @Option(name: .customLong("storage"), help: "VM storage location to use")+ var storage: String?++ @MainActor+ func run() async throws {+ TelemetryClient.shared.record(event: "lume_attach")++ let controller = LumeController()+ let details = try controller.getDetails(name: name, storage: storage)+ guard details.status == "running" else {+ throw AttachError.vmNotRunning(name)+ }+ let vm = try controller.get(name: name, storage: storage)+ let vmDirectory = vm.vmDirContext.dir++ switch display {+ case .native:+ try NativeDisplayAttachService.requestNativeDisplay(vmDirectory: vmDirectory)+ print("Requested native display for '\(name)'.")+ case .vnc:+ try openVNC(details: details)+ case nil:+ if NativeDisplayAttachService.isAvailable(vmDirectory: vmDirectory) {+ do {+ try NativeDisplayAttachService.requestNativeDisplay(vmDirectory: vmDirectory)+ print("Requested native display for '\(name)'.")+ return+ } catch {+ Logger.debug(+ "Native display attachment failed; falling back to VNC",+ metadata: [+ "name": name,+ "error": error.localizedDescription,+ ])+ }+ }+ try openVNC(details: details)+ }+ }++ private func openVNC(details: VMDetails) throws {+ guard let value = details.vncUrl,+ let url = URL(string: value),+ !value.isEmpty+ else {+ throw AttachError.vncUnavailable(name)+ }+ guard NSWorkspace.shared.open(url) else {+ throw AttachError.failedToOpenVNC+ }+ print("Opened VNC display for '\(name)'.")+ }+}diff --git a/libs/lume/src/Commands/GuestPower.swift b/libs/lume/src/Commands/GuestPower.swiftnew file mode 100644index 0000000000..b30ee36036--- /dev/null+++ b/libs/lume/src/Commands/GuestPower.swift@@ -0,0 +1,173 @@+import ArgumentParser+import Foundation++enum GuestPowerAction: Sendable {+ case shutdown+ case restart++ var commandName: String {+ switch self {+ case .shutdown: return "shutdown"+ case .restart: return "restart"+ }+ }++ var shutdownFlag: String {+ switch self {+ case .shutdown: return "-h"+ case .restart: return "-r"+ }+ }++ func remoteCommand(password: String) -> String {+ let escapedPassword = password.replacingOccurrences(of: "'", with: "'\\''")+ return+ "printf '%s\\n' '\(escapedPassword)' | sudo -S -p '' /bin/sh -c 'nohup /bin/sh -c \"sleep 1; /sbin/shutdown \(shutdownFlag) now\" >/dev/null 2>&1 &'"+ }+}++@MainActor+private func requestGuestPowerAction(+ _ action: GuestPowerAction,+ name: String,+ user: String,+ password: String,+ storage: String?,+ timeout: Int+) async throws {+ let controller = LumeController()+ let details: VMDetails+ do {+ details = try controller.getDetails(name: name, storage: storage)+ } catch {+ throw SSHError.vmNotFound(name)+ }++ guard details.status == "running" else {+ throw SSHError.vmNotRunning(name)+ }+ guard let ipAddress = details.ipAddress, !ipAddress.isEmpty else {+ throw SSHError.noIPAddress(name)+ }+ guard details.sshAvailable == true else {+ throw SSHError.sshNotAvailable(name)+ }++ let result = try await executeGuestPowerCommand(+ action.remoteCommand(password: password),+ host: ipAddress,+ user: user,+ password: password,+ timeout: timeout+ )+ guard result.exitCode == 0 else {+ throw SSHError.commandFailed(exitCode: result.exitCode, message: result.output)+ }++ print("Graceful \(action.commandName) requested for '\(name)'.")+}++@MainActor+private func executeGuestPowerCommand(+ _ command: String,+ host: String,+ user: String,+ password: String,+ timeout: Int+) async throws -> SSHResult {+ for attempt in 0..<2 {+ do {+ let client = SSHClient(host: host, port: 22, user: user, password: password)+ return try await client.execute(+ command: command,+ timeout: TimeInterval(timeout)+ )+ } catch let error as SSHError {+ guard case .connectionFailed = error else { throw error }+ if attempt == 0 {+ try await Task.sleep(for: .milliseconds(500))+ }+ }+ }++ Logger.debug(+ "NIO SSH connection failed for guest power command; using system SSH",+ metadata: ["host": host]+ )+ return try SystemSSHClient(+ host: host,+ port: 22,+ user: user,+ password: password+ ).execute(command: command, timeout: TimeInterval(timeout))+}++struct Shutdown: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "shutdown",+ abstract: "Gracefully shut down a virtual machine"+ )++ @Argument(help: "Name of the virtual machine", completion: .custom(completeVMName))+ var name: String++ @Option(name: [.short, .long], help: "SSH username (default: lume)")+ var user: String = "lume"++ @Option(name: [.short, .long], help: "SSH and sudo password (default: lume)")+ var password: String = "lume"++ @Option(name: .customLong("storage"), help: "VM storage location to use")+ var storage: String?++ @Option(name: [.short, .long], help: "SSH command timeout in seconds")+ var timeout: Int = 30++ @MainActor+ func run() async throws {+ TelemetryClient.shared.record(event: "lume_shutdown")+ try await requestGuestPowerAction(+ .shutdown,+ name: name,+ user: user,+ password: password,+ storage: storage,+ timeout: timeout+ )+ }+}++struct Restart: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "restart",+ abstract: "Gracefully restart a virtual machine"+ )++ @Argument(help: "Name of the virtual machine", completion: .custom(completeVMName))+ var name: String++ @Option(name: [.short, .long], help: "SSH username (default: lume)")+ var user: String = "lume"++ @Option(name: [.short, .long], help: "SSH and sudo password (default: lume)")+ var password: String = "lume"++ @Option(name: .customLong("storage"), help: "VM storage location to use")+ var storage: String?++ @Option(name: [.short, .long], help: "SSH command timeout in seconds")+ var timeout: Int = 30++ @MainActor+ func run() async throws {+ TelemetryClient.shared.record(event: "lume_restart")+ try await requestGuestPowerAction(+ .restart,+ name: name,+ user: user,+ password: password,+ storage: storage,+ timeout: timeout+ )+ }+}diff --git a/libs/lume/src/Commands/Run.swift b/libs/lume/src/Commands/Run.swiftindex 6a98c98c91..48642c9166 100644--- a/libs/lume/src/Commands/Run.swift+++ b/libs/lume/src/Commands/Run.swift@@ -15,7 +15,7 @@ struct Run: AsyncParsableCommand {@Option(help: "Local viewer to open: 'vnc', 'native', or 'none'. The VNC server remains available in every mode.")- var display: DisplayMode = .vnc+ var display: DisplayMode = .none@Flag(name: [.customShort("d"), .customLong("no-display")],diff --git a/libs/lume/src/Main.swift b/libs/lume/src/Main.swiftindex 1f2a9d6040..28859eff0e 100644--- a/libs/lume/src/Main.swift+++ b/libs/lume/src/Main.swift@@ -59,10 +59,12 @@ extension Lume {// MARK: - Command Executionextension Lume {public static func main() {- if let vmName = nativeDisplayVMName() {- ProcessInfo.processInfo.processName = "Lume — \(vmName)"+ if let runContext = directRunContext() {+ ProcessInfo.processInfo.processName = "Lume — \(runContext.vmName)"do {- try NativeApplicationLoop.run {+ try NativeApplicationLoop.run(+ showsStartupWindow: runContext.showsNativeDisplayAtLaunch+ ) {await executeInvocation()}} catch {@@ -106,24 +108,26 @@ extension Lume {}}- private static func nativeDisplayVMName() -> String? {+ private static func directRunContext() -> (+ vmName: String,+ showsNativeDisplayAtLaunch: Bool+ )? {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]+ guard args.first == "run" else { return nil }++ let noDisplay = args.contains("--no-display") || args.contains("-d")+ let usesNativeDisplay = !noDisplay+ && (args.contains("--display=native")+ || args.indices.contains { index in+ args[index] == "--display"+ && args.index(after: index) < args.endIndex+ && args[args.index(after: index)] == "native"+ })++ // The conventional form is `lume run VM_NAME [options]`. ArgumentParser+ // still produces a useful validation error if the positional name is absent.+ let vmName = args.count > 1 && !args[1].hasPrefix("-") ? args[1] : "VM"+ return (vmName, usesNativeDisplay)}private static func isTelemetryManagementInvocation() -> Bool {diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swiftindex 91c5895dd8..001bb41290 100644--- a/libs/lume/src/Utils/CommandDocExtractor.swift+++ b/libs/lume/src/Utils/CommandDocExtractor.swift@@ -85,7 +85,10 @@ enum CommandDocExtractor {setDoc,listDoc,runDoc,+ attachDoc,stopDoc,+ shutdownDoc,+ restartDoc,sshDoc,sipDoc,ipswDoc,@@ -342,7 +345,7 @@ 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: "display", shortName: nil, help: "Local viewer to open: vnc, native, or none. The VNC server remains available in every mode", type: "DisplayMode", defaultValue: "none", 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),@@ -355,6 +358,25 @@ enum CommandDocExtractor {)}+ // MARK: - Attach++ private static var attachDoc: CommandDoc {+ CommandDoc(+ name: "attach",+ abstract: "Open a viewer for a running virtual machine",+ discussion: "Native display is preferred when the owning lume run process supports live attachment. VNC is used as the automatic fallback.",+ arguments: [+ ArgumentDoc(name: "name", help: "Name of the virtual machine", type: "String", isOptional: false),+ ],+ options: [+ OptionDoc(name: "display", shortName: nil, help: "Viewer to open: native or vnc", type: "AttachDisplayMode", defaultValue: "native with VNC fallback", isOptional: true),+ OptionDoc(name: "storage", shortName: nil, help: "VM storage location to use", type: "String", defaultValue: nil, isOptional: true),+ ],+ flags: [],+ subcommands: []+ )+ }+// MARK: - Stopprivate static var stopDoc: CommandDoc {@@ -373,6 +395,41 @@ enum CommandDocExtractor {)}+ // MARK: - Guest power++ private static var shutdownDoc: CommandDoc {+ guestPowerDoc(+ name: "shutdown",+ abstract: "Gracefully shut down a virtual machine"+ )+ }++ private static var restartDoc: CommandDoc {+ guestPowerDoc(+ name: "restart",+ abstract: "Gracefully restart a virtual machine"+ )+ }++ private static func guestPowerDoc(name: String, abstract: String) -> CommandDoc {+ CommandDoc(+ name: name,+ abstract: abstract,+ discussion: "Requests the operation inside the guest over SSH. VMs created with --unattended use lume/lume credentials by default.",+ arguments: [+ ArgumentDoc(name: "name", help: "Name of the virtual machine", type: "String", isOptional: false),+ ],+ options: [+ OptionDoc(name: "user", shortName: "u", help: "SSH username", type: "String", defaultValue: "lume", isOptional: false),+ OptionDoc(name: "password", shortName: "p", help: "SSH and sudo password", type: "String", defaultValue: "lume", isOptional: false),+ OptionDoc(name: "storage", shortName: nil, help: "VM storage location to use", type: "String", defaultValue: nil, isOptional: true),+ OptionDoc(name: "timeout", shortName: "t", help: "SSH command timeout in seconds", type: "Int", defaultValue: "30", isOptional: false),+ ],+ flags: [],+ subcommands: []+ )+ }+// MARK: - SSHprivate static var sshDoc: CommandDoc {diff --git a/libs/lume/src/Utils/CommandRegistry.swift b/libs/lume/src/Utils/CommandRegistry.swiftindex a9b77b1e28..85d1d1f828 100644--- a/libs/lume/src/Utils/CommandRegistry.swift+++ b/libs/lume/src/Utils/CommandRegistry.swift@@ -13,7 +13,10 @@ enum CommandRegistry {Set.self,List.self,Run.self,+ Attach.self,Stop.self,+ Shutdown.self,+ Restart.self,SSH.self,Sip.self,IPSW.self,diff --git a/libs/lume/src/VM/NativeApplicationLoop.swift b/libs/lume/src/VM/NativeApplicationLoop.swiftindex 1ed6dc73aa..a65e499d90 100644--- a/libs/lume/src/VM/NativeApplicationLoop.swift+++ b/libs/lume/src/VM/NativeApplicationLoop.swift@@ -5,10 +5,11 @@ private final class NativeOperationBridge: @unchecked Sendable {var result: Result<Void, Error>?}-/// Hosts native-display VM work inside a conventional AppKit application loop.+/// Hosts direct `lume run` 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+/// MainActor command task is active. It stays accessory-only for background runs but+/// keeps them ready for a later native attach. AppKit owns the main thread while/// Virtualization.framework uses a dedicated serial queue for VM operations.@MainActorenum NativeApplicationLoop {@@ -22,6 +23,7 @@ enum NativeApplicationLoop {}static func run(+ showsStartupWindow: Bool,operation: @escaping @MainActor @Sendable () async throws -> Void) throws {precondition(!isActive, "The native AppKit loop is already running")@@ -35,17 +37,21 @@ enum NativeApplicationLoop {ProcessInfo.processInfo.enableAutomaticTermination(terminationReason)}- if application.activationPolicy() != .regular {- guard application.setActivationPolicy(.regular) else {+ let activationPolicy: NSApplication.ActivationPolicy =+ showsStartupWindow ? .regular : .accessory+ if application.activationPolicy() != activationPolicy {+ guard application.setActivationPolicy(activationPolicy) else {throw VMDisplayPresenterError.applicationSetupFailed}}application.finishLaunching()- let startupWindow = makeStartupWindow()- self.startupWindow = startupWindow- startupWindow.makeKeyAndOrderFront(nil)- application.activate(ignoringOtherApps: true)+ if showsStartupWindow {+ let startupWindow = makeStartupWindow()+ self.startupWindow = startupWindow+ startupWindow.makeKeyAndOrderFront(nil)+ application.activate(ignoringOtherApps: true)+ }isActive = truedefer {diff --git a/libs/lume/src/VM/NativeDisplayAttachService.swift b/libs/lume/src/VM/NativeDisplayAttachService.swiftnew file mode 100644index 0000000000..687900dbdc--- /dev/null+++ b/libs/lume/src/VM/NativeDisplayAttachService.swift@@ -0,0 +1,131 @@+import Darwin+import Foundation++enum NativeDisplayAttachError: LocalizedError {+ case unavailable+ case requestFailed++ var errorDescription: String? {+ switch self {+ case .unavailable:+ return "The running VM process does not support native display attachment."+ case .requestFailed:+ return "Failed to ask the running VM process to show its native display."+ }+ }+}++private struct NativeDisplayOwner: Codable {+ let processIdentifier: Int32+}++/// Provides a small, process-local control channel for revealing the native viewer.+///+/// The owning `lume run` process registers SIGUSR1 and writes its PID into the VM+/// directory. An `attach` process verifies that PID still owns the VM configuration+/// lock before signaling it. The signal never crosses into an unrelated Lume daemon.+@MainActor+enum NativeDisplayAttachService {+ private nonisolated static let ownerFileName = ".native-display-owner.json"+ private static var signalSource: DispatchSourceSignal?+ private static var ownerFileURL: URL?+ private static var showAction: (@MainActor @Sendable () async -> Void)?++ static func register(+ vmDirectory: VMDirectory,+ show: @escaping @MainActor @Sendable () async -> Void+ ) throws {+ unregister()++ let owner = NativeDisplayOwner(processIdentifier: getpid())+ let fileURL = ownerURL(for: vmDirectory)+ let data = try JSONEncoder().encode(owner)+ try data.write(to: fileURL, options: .atomic)+ chmod(fileURL.path, S_IRUSR | S_IWUSR)++ showAction = show+ ownerFileURL = fileURL+ signal(SIGUSR1, SIG_IGN)++ let source = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main)+ source.setEventHandler {+ Task { @MainActor in+ await showAction?()+ }+ }+ signalSource = source+ source.resume()+ }++ static func unregister() {+ signalSource?.cancel()+ signalSource = nil+ showAction = nil++ if let ownerFileURL,+ let data = try? Data(contentsOf: ownerFileURL),+ let owner = try? JSONDecoder().decode(NativeDisplayOwner.self, from: data),+ owner.processIdentifier == getpid()+ {+ try? FileManager.default.removeItem(at: ownerFileURL)+ }+ ownerFileURL = nil+ }++ nonisolated static func isAvailable(vmDirectory: VMDirectory) -> Bool {+ guard let owner = validatedOwner(for: vmDirectory) else { return false }+ return kill(owner.processIdentifier, 0) == 0+ }++ nonisolated static func requestNativeDisplay(vmDirectory: VMDirectory) throws {+ guard let owner = validatedOwner(for: vmDirectory) else {+ throw NativeDisplayAttachError.unavailable+ }+ guard kill(owner.processIdentifier, SIGUSR1) == 0 else {+ throw NativeDisplayAttachError.requestFailed+ }+ }++ private nonisolated static func validatedOwner(+ for vmDirectory: VMDirectory+ ) -> NativeDisplayOwner? {+ let fileURL = ownerURL(for: vmDirectory)+ guard let data = try? Data(contentsOf: fileURL),+ let owner = try? JSONDecoder().decode(NativeDisplayOwner.self, from: data),+ owner.processIdentifier > 0,+ owner.processIdentifier == lockOwnerPID(for: vmDirectory.configPath.url)+ else {+ return nil+ }+ return owner+ }++ private nonisolated static func ownerURL(for vmDirectory: VMDirectory) -> URL {+ vmDirectory.dir.file(ownerFileName).url+ }++ private nonisolated static func lockOwnerPID(for configURL: URL) -> Int32? {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")+ process.arguments = ["-t", configURL.path]+ let output = Pipe()+ process.standardOutput = output+ process.standardError = FileHandle.nullDevice++ do {+ try process.run()+ process.waitUntilExit()+ guard process.terminationStatus == 0,+ let data = try output.fileHandleForReading.readToEnd(),+ let value = String(data: data, encoding: .utf8)?+ .split(whereSeparator: \.isNewline).first,+ let pid = Int32(value)+ else {+ return nil+ }+ return pid+ } catch {+ return nil+ }+ }+}diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swiftindex 0e25e12ebb..db1e4549c5 100644--- a/libs/lume/src/VM/VM.swift+++ b/libs/lume/src/VM/VM.swift@@ -52,6 +52,8 @@ class VM {internal let vncService: VNCServiceprivate var clipboardWatcher: ClipboardWatcher?private var displayPresenter: VMDisplayPresenter?+ private var displayContext: VMDisplayContext?+ private var nativeAttachRegistered = falseprivate var activeSharedDirectories: [SharedDirectory] = []private var scopedSharedDirectoryURLs: [URL] = []private var sessionCleanedUp = true@@ -362,11 +364,7 @@ class VM {osType: getOSType(),explicitlyRequested: clipboard) {- clipboardWatcher = ClipboardWatcher(- vmName: vmDirContext.name,- storage: vmDirContext.storage- )- await clipboardWatcher?.start()+ await startClipboardWatcherIfNeeded()}if displayMode == .vnc {@@ -374,30 +372,48 @@ class VM {}// 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)+ let 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)+ })+ displayContext = context+ try await presenter.show(context: context)presenter.virtualMachineDidStart()+ if NativeApplicationLoop.isActive {+ do {+ try NativeDisplayAttachService.register(+ vmDirectory: vmDirContext.dir+ ) { [weak self] in+ await self?.showNativeDisplay()+ }+ nativeAttachRegistered = true+ } catch {+ Logger.debug(+ "Live native display attachment is unavailable",+ metadata: [+ "name": vmDirContext.name,+ "error": error.localizedDescription,+ ])+ }+ }+// Write VNC config into VM via SSH (background task).// VirtioFS mounts are blocked by macOS TCC for LaunchAgent processes,// so we also write vnc.env directly to the guest's home directory.@@ -433,6 +449,50 @@ class VM {}}+ private func showNativeDisplay() async {+ guard let context = displayContext else {+ Logger.error(+ "Cannot attach native display without an active VM context",+ metadata: ["name": vmDirContext.name])+ return+ }++ do {+ if getOSType().caseInsensitiveCompare("macOS") == .orderedSame {+ await startClipboardWatcherIfNeeded()+ }++ if let nativePresenter = displayPresenter as? NativeVMDisplayPresenter {+ try await nativePresenter.show(context: context)+ } else {+ let nativePresenter = NativeVMDisplayPresenter()+ try await nativePresenter.show(context: context)+ displayPresenter?.hide()+ displayPresenter = nativePresenter+ }+ Logger.info(+ "Attached native display to running VM",+ metadata: ["name": vmDirContext.name])+ } catch {+ Logger.error(+ "Failed to attach native display",+ metadata: [+ "name": vmDirContext.name,+ "error": error.localizedDescription,+ ])+ }+ }++ private func startClipboardWatcherIfNeeded() async {+ guard clipboardWatcher == nil else { return }+ let watcher = ClipboardWatcher(+ vmName: vmDirContext.name,+ storage: vmDirContext.storage+ )+ clipboardWatcher = watcher+ await watcher.start()+ }+private func copyClipboardFromGuest() async throws {guard let clipboardWatcher else {throw ClipboardSyncError.unavailable@@ -503,8 +563,13 @@ class VM {sessionCleanedUp = true// Detach native display before releasing the framework VM.+ if nativeAttachRegistered {+ NativeDisplayAttachService.unregister()+ nativeAttachRegistered = false+ }displayPresenter?.hide()displayPresenter = nil+ displayContext = nilawait clipboardWatcher?.stop()clipboardWatcher = nilfor url in scopedSharedDirectoryURLs {diff --git a/libs/lume/tests/AttachCommandTests.swift b/libs/lume/tests/AttachCommandTests.swiftnew file mode 100644index 0000000000..3daec286c7--- /dev/null+++ b/libs/lume/tests/AttachCommandTests.swift@@ -0,0 +1,33 @@+import ArgumentParser+import Foundation+import Testing++@testable import lume++@Test("Attach parses native and VNC display choices")+func attachCommandParsing() throws {+ let automatic = try Attach.parse(["test-vm"])+ let native = try Attach.parse(["test-vm", "--display", "native"])+ let vnc = try Attach.parse(["test-vm", "--display=vnc", "--storage", "external"])++ #expect(automatic.display == nil)+ #expect(native.display == .native)+ #expect(vnc.display == .vnc)+ #expect(vnc.storage == "external")+ #expect(throws: Error.self) {+ _ = try Attach.parse(["test-vm", "--display", "none"])+ }+}++@Test("A VM without a registered owner cannot accept native attachment")+func nativeAttachRequiresRegisteredOwner() throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }++ let directory = VMDirectory(Path(root.path))+ #expect(!NativeDisplayAttachService.isAvailable(vmDirectory: directory))+ #expect(throws: NativeDisplayAttachError.self) {+ try NativeDisplayAttachService.requestNativeDisplay(vmDirectory: directory)+ }+}diff --git a/libs/lume/tests/DisplayModeTests.swift b/libs/lume/tests/DisplayModeTests.swiftindex d54fba7686..41ab094ea2 100644--- a/libs/lume/tests/DisplayModeTests.swift+++ b/libs/lume/tests/DisplayModeTests.swift@@ -6,6 +6,7 @@ import Testing@Test("DisplayMode parses all supported values")func displayModeParsing() throws {+ #expect(try Run.parse(["test-vm"]).display == .none)#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)diff --git a/libs/lume/tests/GuestPowerCommandTests.swift b/libs/lume/tests/GuestPowerCommandTests.swiftnew file mode 100644index 0000000000..b7e0d73b1a--- /dev/null+++ b/libs/lume/tests/GuestPowerCommandTests.swift@@ -0,0 +1,35 @@+import ArgumentParser+import Testing++@testable import lume++@Test("Graceful guest power commands parse credential and storage options")+func guestPowerCommandParsing() throws {+ let shutdown = try Shutdown.parse([+ "test-vm", "--user", "admin", "--password", "secret", "--storage", "external",+ "--timeout", "45",+ ])+ let restart = try Restart.parse(["test-vm"])++ #expect(shutdown.name == "test-vm")+ #expect(shutdown.user == "admin")+ #expect(shutdown.password == "secret")+ #expect(shutdown.storage == "external")+ #expect(shutdown.timeout == 45)+ #expect(restart.name == "test-vm")+ #expect(restart.user == "lume")+ #expect(restart.password == "lume")+ #expect(restart.timeout == 30)+}++@Test("Graceful guest power commands use the correct shutdown mode and shell escaping")+func guestPowerRemoteCommands() {+ #expect(+ GuestPowerAction.shutdown.remoteCommand(password: "pa'ss")+ == "printf '%s\\n' 'pa'\\''ss' | sudo -S -p '' /bin/sh -c 'nohup /bin/sh -c \"sleep 1; /sbin/shutdown -h now\" >/dev/null 2>&1 &'"+ )+ #expect(+ GuestPowerAction.restart.remoteCommand(password: "lume")+ == "printf '%s\\n' 'lume' | sudo -S -p '' /bin/sh -c 'nohup /bin/sh -c \"sleep 1; /sbin/shutdown -r now\" >/dev/null 2>&1 &'"+ )+}diff --git a/scripts/docs-generators/lume.ts b/scripts/docs-generators/lume.tsindex 8bd1184477..539465e5e2 100644--- a/scripts/docs-generators/lume.ts+++ b/scripts/docs-generators/lume.ts@@ -330,7 +330,10 @@ export function generateCLIReferenceMDX(docs: CLIDocumentation): string {lines.push('');const groups = [- { title: 'VM Management', commands: ['create', 'run', 'stop', 'delete', 'clone'] },+ {+ title: 'VM Management',+ commands: ['create', 'run', 'attach', 'shutdown', 'restart', 'stop', 'delete', 'clone'],+ },{ title: 'VM Information and Configuration', commands: ['ls', 'get', 'set'] },{title: 'Image Management',