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): support running without a VNC listener (#3209)

Francesco Bonacciab957bdb7566
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 29c1059023..9b4d28631d 100644
--- a/docs/content/docs/how-to-guides/lume/manage-vms.mdx
+++ b/docs/content/docs/how-to-guides/lume/manage-vms.mdx
@@ -66,6 +66,25 @@ 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`.
+### Run without a VNC server
+
+`--display` chooses a local viewer, but Lume still starts a VNC server in every
+display mode so automation and `lume attach --display vnc` keep working. Opt out
+of the VNC server entirely with `--vnc disabled`:
+
+```bash
+lume run macos-tahoe --display none --vnc disabled
+```
+
+That run binds no VNC port, writes no VNC password to the guest, and reports
+`"vncUrl": null` in `lume get` and `lume list`. `lume stop`, `lume delete`, and
+running status still work across processes, including for `--detach` runs.
+
+`--vnc disabled` is rejected together with `--display vnc`, `--vnc-port`, or
+`--vnc-password`, since each of those needs a VNC server. Guest clipboard
+shortcuts in the native viewer travel over VNC, so they are unavailable in a
+VNC-disabled run.
+
### Copy files into a native guest
Drop one or more files or folders from Finder onto the native VM screen. Lume
diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdx
index e47ad00d15..be6ea3ebab 100644
--- a/docs/content/docs/reference/lume/cli-reference.mdx
+++ b/docs/content/docs/reference/lume/cli-reference.mdx
@@ -72,6 +72,7 @@ Run a virtual machine
| `--organization` | String | trycua | Organization to pull from |
| `--display` | DisplayMode | native | Local viewer to open: vnc, native, or none. The VNC server remains available in every mode |
| `--log-file` | String | ~/Library/Logs/lume/{vm}.log | Log path for --detach |
+| `--vnc` | VNCPolicy | enabled | VNC server policy: enabled or disabled. disabled starts the VM with no VNC listener and reports a null vncUrl |
| `--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 |
diff --git a/docs/content/docs/reference/lume/http-api.mdx b/docs/content/docs/reference/lume/http-api.mdx
index b511e15aa3..bb8afc2706 100644
--- a/docs/content/docs/reference/lume/http-api.mdx
+++ b/docs/content/docs/reference/lume/http-api.mdx
@@ -388,6 +388,7 @@ Start a virtual machine
| recoveryMode | boolean | No | Boot macOS VM in recovery mode (default: false) |
| storage | string | No | VM storage location |
| clipboard | boolean | No | Enable bidirectional clipboard sync via SSH (experimental) (default: false) |
+| vnc | string | No | VNC server policy: 'enabled' or 'disabled'. 'disabled' requires noDisplay=true, starts no VNC listener, and reports a null vncUrl (default: enabled) |
#### Example Request
diff --git a/libs/lume/src/Commands/Run.swift b/libs/lume/src/Commands/Run.swift
index 9411e3a5e1..1b727d9674 100644
--- a/libs/lume/src/Commands/Run.swift
+++ b/libs/lume/src/Commands/Run.swift
@@ -66,6 +66,13 @@ struct Run: AsyncParsableCommand {
@Option(help: "Organization to pull the images from. Defaults to trycua")
var organization: String = "trycua"
+ @Option(
+ name: .customLong("vnc"),
+ help:
+ "VNC server policy: 'enabled' (default) or 'disabled'. 'disabled' starts the VM with no VNC listener and reports a null vncUrl."
+ )
+ var vnc: VNCPolicy = .enabled
+
@Option(
name: [.customLong("vnc-port")],
help: "Port to use for the VNC server. Defaults to 0 (auto-assign)")
@@ -168,6 +175,18 @@ struct Run: AsyncParsableCommand {
init() {
}
+ func validate() throws {
+ if let option = VNCPolicy.conflictingOption(
+ policy: vnc,
+ displayMode: DisplayMode.resolve(requested: display, noDisplay: noDisplay),
+ vncPort: vncPort,
+ vncPassword: vncPassword
+ ) {
+ throw ValidationError(
+ "'--vnc disabled' starts no VNC server, so it cannot be combined with '\(option)'.")
+ }
+ }
+
@MainActor
func run() async throws {
if detach {
@@ -205,7 +224,8 @@ struct Run: AsyncParsableCommand {
usbMassStoragePaths: parsedUSBStorageDevices.isEmpty ? nil : parsedUSBStorageDevices,
additionalDiskPaths: parsedAdditionalDisks.isEmpty ? nil : parsedAdditionalDisks,
networkMode: parsedNetworkMode,
- clipboard: clipboard
+ clipboard: clipboard,
+ vncPolicy: vnc
)
}
}
diff --git a/libs/lume/src/Errors/Errors.swift b/libs/lume/src/Errors/Errors.swift
index 0e280ae54a..9ae00684d8 100644
--- a/libs/lume/src/Errors/Errors.swift
+++ b/libs/lume/src/Errors/Errors.swift
@@ -181,6 +181,7 @@ enum VMError: Error, LocalizedError {
case resizeTooSmall(current: UInt64, requested: UInt64)
case vncNotConfigured
case vncPortBindingFailed(requested: Int, actual: Int)
+ case vncDisabledConflict(String)
case internalError(String)
case unsupportedOS(String)
case invalidDisplayResolution(String)
@@ -210,6 +211,8 @@ enum VMError: Error, LocalizedError {
return "Could not bind to VNC port \(requested) (port already in use). Try a different port or use port 0 for auto-assign."
}
return "Could not bind to VNC port \(requested) (port already in use). System assigned port \(actual) instead. Try a different port or use port 0 for auto-assign."
+ case .vncDisabledConflict(let option):
+ return "VNC is disabled for this run, so '\(option)' cannot be used."
case .internalError(let message):
return "Internal error: \(message)"
case .unsupportedOS(let os):
diff --git a/libs/lume/src/FileSystem/VMDirectory.swift b/libs/lume/src/FileSystem/VMDirectory.swift
index 3b36f6050b..2a3e8fe767 100644
--- a/libs/lume/src/FileSystem/VMDirectory.swift
+++ b/libs/lume/src/FileSystem/VMDirectory.swift
@@ -251,13 +251,55 @@ extension VMDirectory {
// MARK: - VNC Session Management
+/// Marker written while a VM session is running.
+///
+/// Legacy markers carry only `url` and `sharedDirectories`; both still decode
+/// unchanged, and a VNC-backed session still encodes exactly those two fields.
+/// A VNC-disabled session has no URL, so it omits `url` and instead records the
+/// owning `lume run` process, which `get`/`list` verify against the config-file
+/// run lock. Older Lume binaries fail to decode that marker and therefore
+/// report the VM as stopped instead of acting on stale information.
struct VNCSession: Codable {
- let url: String
+ let url: String?
let sharedDirectories: [SharedDirectory]?
-
- init(url: String, sharedDirectories: [SharedDirectory]? = nil) {
+ /// Absent on legacy markers, which always described a VNC-backed session.
+ let vncEnabled: Bool?
+ /// PID of the owning `lume run` process. Written only for VNC-disabled
+ /// sessions, which have no listening port to probe for liveness.
+ let pid: Int32?
+ /// Unix timestamp of when the session started.
+ let startedAt: Double?
+
+ /// A marker without `vncEnabled` predates the policy and described VNC.
+ var isVNCEnabled: Bool { vncEnabled ?? true }
+
+ init(
+ url: String?,
+ sharedDirectories: [SharedDirectory]? = nil,
+ vncEnabled: Bool? = nil,
+ pid: Int32? = nil,
+ startedAt: Double? = nil
+ ) {
self.url = url
self.sharedDirectories = sharedDirectories
+ self.vncEnabled = vncEnabled
+ self.pid = pid
+ self.startedAt = startedAt
+ }
+
+ /// Marker for a run started with `--vnc disabled`.
+ static func vncDisabled(
+ pid: Int32,
+ startedAt: Double,
+ sharedDirectories: [SharedDirectory]? = nil
+ ) -> VNCSession {
+ VNCSession(
+ url: nil,
+ sharedDirectories: sharedDirectories,
+ vncEnabled: false,
+ pid: pid,
+ startedAt: startedAt
+ )
}
}
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index cdba97a70d..30ac2e3f20 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -69,17 +69,20 @@ final class LumeController {
let home: Home
private let imageLoaderFactory: ImageLoaderFactory
private let vmFactory: VMFactory
+ private let runLockProbe: RunLockProbe
// MARK: - Initialization
init(
home: Home = Home(),
imageLoaderFactory: ImageLoaderFactory = DefaultImageLoaderFactory(),
- vmFactory: VMFactory = DefaultVMFactory()
+ vmFactory: VMFactory = DefaultVMFactory(),
+ runLockProbe: RunLockProbe = LsofRunLockProbe()
) {
self.home = home
self.imageLoaderFactory = imageLoaderFactory
self.vmFactory = vmFactory
+ self.runLockProbe = runLockProbe
}
// MARK: - Public VM Management Methods
@@ -214,15 +217,42 @@ final class LumeController {
var sshAvailable: Bool? = nil
// If not in cache, check if session file exists (cross-process fallback)
- // Session files are created when VM starts and deleted when VM stops
- // Validate that the VNC port is actually in use to detect stale sessions
+ // Session files are created when VM starts and deleted when VM stops.
+ // Each marker kind carries its own liveness proof, and a marker that
+ // cannot prove liveness is stale and gets cleaned up.
+ var sessionSuppressesVNCUrl = false
if !isRunning {
if let session = try? vmDir.loadSession() {
- // Parse VNC port from URL like "vnc://:[email protected]:62295"
- if let port = parseVNCPort(from: session.url),
- NetworkUtils.isLocalPortInUse(port: port) {
+ if !session.isVNCEnabled {
+ sessionSuppressesVNCUrl = true
+ // No port to probe: the VM is running only while the PID it
+ // recorded is still the live holder of the run lock. The PID
+ // alone proves nothing — it can be recycled.
+ let live: Bool?
+ if let pid = session.pid {
+ live = runLockProbe.isLiveLockHolder(
+ pid: pid, ofFileAt: vmDir.configPath.path)
+ } else {
+ live = false
+ }
+ if live == true {
+ isRunning = true
+ } else if live == false {
+ vmDir.clearSession()
+ Logger.info(
+ "Cleaned up stale VNC-disabled session marker",
+ metadata: ["name": vmName])
+ } else {
+ Logger.info(
+ "Could not verify VNC-disabled session marker; preserving it",
+ metadata: ["name": vmName])
+ }
+ } else if let url = session.url,
+ let port = parseVNCPort(from: url),
+ NetworkUtils.isLocalPortInUse(port: port) {
+ // Parse VNC port from URL like "vnc://:[email protected]:62295"
isRunning = true
- vncUrl = session.url
+ vncUrl = url
} else {
// Stale session file - VNC port not in use, clean it up
vmDir.clearSession()
@@ -233,8 +263,11 @@ final class LumeController {
if isRunning {
// Try to get VNC URL from session file (if not already loaded)
- if vncUrl == nil {
- vncUrl = try? vmDir.loadSession().url
+ if vncUrl == nil && !sessionSuppressesVNCUrl {
+ let session = try? vmDir.loadSession()
+ if session?.isVNCEnabled == true {
+ vncUrl = session?.url
+ }
}
// Try to get IP address from DHCP lease if we have MAC address
@@ -1051,15 +1084,25 @@ final class LumeController {
additionalDiskPaths: [Path]? = nil,
networkMode: NetworkMode? = nil,
clipboard: Bool = false,
+ vncPolicy: VNCPolicy = .enabled,
telemetryTransport: TelemetryTransport = .cli
) async throws {
let normalizedName = normalizeVMName(name: name)
let effectiveDisplayMode = displayMode ?? (noDisplay ? .none : .vnc)
+ if let option = VNCPolicy.conflictingOption(
+ policy: vncPolicy,
+ displayMode: effectiveDisplayMode,
+ vncPort: vncPort,
+ vncPassword: vncPassword
+ ) {
+ throw VMError.vncDisabledConflict(option)
+ }
Logger.info(
"Running VM",
metadata: [
"name": normalizedName,
"display_mode": effectiveDisplayMode.rawValue,
+ "vnc_policy": vncPolicy.rawValue,
"shared_directories":
"\(sharedDirectories.map( { $0.string } ).joined(separator: ", "))",
"mount": mount?.path ?? "none",
@@ -1179,7 +1222,8 @@ final class LumeController {
usbMassStoragePaths: usbMassStoragePaths,
additionalDiskPaths: additionalDiskPaths,
networkMode: networkMode,
- clipboard: clipboard)
+ clipboard: clipboard,
+ vncPolicy: vncPolicy)
Logger.info("VM started successfully", metadata: ["name": normalizedName])
} catch {
SharedVM.shared.removeVM(name: normalizedName)
diff --git a/libs/lume/src/Server/APIDocExtractor.swift b/libs/lume/src/Server/APIDocExtractor.swift
index 875417924b..a303a12f8e 100644
--- a/libs/lume/src/Server/APIDocExtractor.swift
+++ b/libs/lume/src/Server/APIDocExtractor.swift
@@ -310,7 +310,8 @@ enum APIDocExtractor {
APIFieldDoc(name: "sharedDirectories", type: "array", required: false, description: "Directories to share with the VM", defaultValue: nil),
APIFieldDoc(name: "recoveryMode", type: "boolean", required: false, description: "Boot macOS VM in recovery mode", defaultValue: "false"),
APIFieldDoc(name: "storage", type: "string", required: false, description: "VM storage location", defaultValue: nil),
- APIFieldDoc(name: "clipboard", type: "boolean", required: false, description: "Enable bidirectional clipboard sync via SSH (experimental)", defaultValue: "false")
+ APIFieldDoc(name: "clipboard", type: "boolean", required: false, description: "Enable bidirectional clipboard sync via SSH (experimental)", defaultValue: "false"),
+ APIFieldDoc(name: "vnc", type: "string", required: false, description: "VNC server policy: 'enabled' or 'disabled'. 'disabled' requires noDisplay=true, starts no VNC listener, and reports a null vncUrl", defaultValue: "enabled")
]
),
responseBody: APIResponseDoc(
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 9710011bda..0530075978 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -428,11 +428,18 @@ extension Server {
do {
Logger.info("Creating VM controller and parsing request", metadata: ["name": name])
- let request =
- body.flatMap { try? JSONDecoder().decode(RunVMRequest.self, from: $0) }
- ?? RunVMRequest(
+ let request: RunVMRequest
+ if let body {
+ do {
+ request = try JSONDecoder().decode(RunVMRequest.self, from: body)
+ } catch {
+ throw ValidationError("Invalid run request body")
+ }
+ } else {
+ request = RunVMRequest(
noDisplay: nil, sharedDirectories: nil, recoveryMode: nil, storage: nil,
- diskPath: nil, nvramPath: nil, network: nil, clipboard: nil)
+ diskPath: nil, nvramPath: nil, network: nil, clipboard: nil, vnc: nil)
+ }
// Record telemetry
TelemetryClient.shared.record(event: TelemetryEvent.apiVMRun, properties: [
@@ -455,19 +462,22 @@ extension Server {
metadata: ["name": name, "count": "\(dirs.count)"])
let networkMode = try request.parseNetworkMode()
+ let vncPolicy = try request.validatedVNCPolicy(noDisplayDefault: false)
+ let noDisplay = request.noDisplay ?? false
// Start VM in background
Logger.info("Starting VM in background", metadata: ["name": name])
startVM(
name: name,
- noDisplay: request.noDisplay ?? false,
+ noDisplay: noDisplay,
sharedDirectories: dirs,
recoveryMode: request.recoveryMode ?? false,
storage: request.storage,
diskPath: request.diskPath.map { Path($0) },
nvramPath: request.nvramPath.map { Path($0) },
networkMode: networkMode,
- clipboard: request.clipboard ?? false
+ clipboard: request.clipboard ?? false,
+ vncPolicy: vncPolicy
)
Logger.info("VM start initiated in background", metadata: ["name": name])
@@ -947,7 +957,8 @@ extension Server {
diskPath: Path? = nil,
nvramPath: Path? = nil,
networkMode: NetworkMode? = nil,
- clipboard: Bool = false
+ clipboard: Bool = false,
+ vncPolicy: VNCPolicy = .enabled
) {
Logger.info(
"Starting VM in detached task",
@@ -957,6 +968,7 @@ extension Server {
"recoveryMode": "\(recoveryMode)",
"storage": String(describing: storage),
"networkMode": networkMode?.description ?? "vm-config",
+ "vncPolicy": vncPolicy.rawValue,
])
Task.detached { @MainActor @Sendable in
@@ -981,6 +993,7 @@ extension Server {
nvramPath: nvramPath,
networkMode: networkMode,
clipboard: clipboard,
+ vncPolicy: vncPolicy,
telemetryTransport: .http
)
Logger.info("VM started successfully in background task", metadata: ["name": name])
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
index a46c1c5773..5c14ecb704 100644
--- a/libs/lume/src/Server/MCPServer.swift
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -374,6 +374,11 @@ final class LumeMCPServer {
"type": .string("boolean"),
"description": .string("Run headless without VNC window (default: true)")
]),
+ "vnc": .object([
+ "type": .string("string"),
+ "enum": .array([.string("enabled"), .string("disabled")]),
+ "description": .string("VNC server policy. 'disabled' starts no VNC listener and reports a null vncUrl (default: enabled)")
+ ]),
"storage": .object([
"type": .string("string"),
"description": .string("Optional storage location name or path")
@@ -650,6 +655,30 @@ final class LumeMCPServer {
let noDisplay = args?["no_display"]?.boolValue ?? true
let clipboard = args?["clipboard"]?.boolValue ?? false
+ let vncPolicy: VNCPolicy
+ if let requested = args?["vnc"]?.stringValue {
+ guard let policy = VNCPolicy(rawValue: requested) else {
+ return CallTool.Result(
+ content: [
+ .text("Error: 'vnc' must be 'enabled' or 'disabled', got '\(requested)'")
+ ],
+ isError: true)
+ }
+ vncPolicy = policy
+ } else {
+ vncPolicy = .enabled
+ }
+ if let option = VNCPolicy.conflictingOption(
+ policy: vncPolicy,
+ displayMode: noDisplay ? .none : .vnc,
+ vncPort: 0,
+ vncPassword: nil
+ ) {
+ return CallTool.Result(
+ content: [.text("Error: \(VMError.vncDisabledConflict(option).localizedDescription)")],
+ isError: true)
+ }
+
var sharedDirectories: [SharedDirectory] = []
if let sharedDir = args?["shared_dir"]?.stringValue {
// Expand ~ to home directory
@@ -667,6 +696,7 @@ final class LumeMCPServer {
sharedDirectories: sharedDirectories,
storage: storage,
clipboard: clipboard,
+ vncPolicy: vncPolicy,
telemetryTransport: .mcpStdio
)
} catch {
diff --git a/libs/lume/src/Server/Requests.swift b/libs/lume/src/Server/Requests.swift
index 9a1a83820e..2bb3b0da5e 100644
--- a/libs/lume/src/Server/Requests.swift
+++ b/libs/lume/src/Server/Requests.swift
@@ -20,6 +20,9 @@ struct RunVMRequest: Codable {
let nvramPath: String?
let network: String?
let clipboard: Bool?
+ /// "enabled" (default) or "disabled". Absent keeps the historic behavior of
+ /// always starting a VNC server.
+ let vnc: String?
struct SharedDirectoryRequest: Codable {
let hostPath: String
@@ -53,6 +56,31 @@ struct RunVMRequest: Codable {
}
return try parseNetworkModeString(network)
}
+
+ func parseVNCPolicy() throws -> VNCPolicy {
+ guard let vnc else {
+ return .enabled
+ }
+ guard let policy = VNCPolicy(rawValue: vnc) else {
+ throw ValidationError(
+ "Invalid vnc policy '\(vnc)'. Expected 'enabled' or 'disabled'.")
+ }
+ return policy
+ }
+
+ func validatedVNCPolicy(noDisplayDefault: Bool) throws -> VNCPolicy {
+ let policy = try parseVNCPolicy()
+ let noDisplay = self.noDisplay ?? noDisplayDefault
+ if let option = VNCPolicy.conflictingOption(
+ policy: policy,
+ displayMode: noDisplay ? .none : .vnc,
+ vncPort: 0,
+ vncPassword: nil
+ ) {
+ throw VMError.vncDisabledConflict(option)
+ }
+ return policy
+ }
}
struct PullRequest: Codable {
diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swift
index 41838c984a..c819bc6ef5 100644
--- a/libs/lume/src/Utils/CommandDocExtractor.swift
+++ b/libs/lume/src/Utils/CommandDocExtractor.swift
@@ -348,6 +348,7 @@ enum CommandDocExtractor {
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: "native", isOptional: false),
OptionDoc(name: "log-file", shortName: nil, help: "Log path for --detach", type: "String", defaultValue: "~/Library/Logs/lume/{vm}.log", isOptional: true),
+ OptionDoc(name: "vnc", shortName: nil, help: "VNC server policy: enabled or disabled. disabled starts the VM with no VNC listener and reports a null vncUrl", type: "VNCPolicy", defaultValue: "enabled", 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),
diff --git a/libs/lume/src/Utils/RunLockProbe.swift b/libs/lume/src/Utils/RunLockProbe.swift
new file mode 100644
index 0000000000..16373b69a4
--- /dev/null
+++ b/libs/lume/src/Utils/RunLockProbe.swift
@@ -0,0 +1,117 @@
+import Darwin
+import Foundation
+
+/// Resolves which processes currently hold a VM's `config.json` open.
+///
+/// `lume run` keeps that file open under an exclusive `flock` for the entire
+/// lifetime of a session, so its holder is the authoritative cross-process
+/// liveness signal. `stop` and `attach` already trust it; VNC-disabled runs
+/// reuse it because they have no VNC port to probe.
+protocol RunLockProbe: Sendable {
+ /// Process identifiers holding the file at `path` open, in `lsof` order.
+ /// Empty means no process has it open. Nil means the probe was inconclusive.
+ func lockHolderPIDs(ofFileAt path: String) -> [pid_t]?
+}
+
+extension RunLockProbe {
+ /// The single owning process, matching the "first holder wins" rule that
+ /// `stop` and `attach` have always used.
+ func lockOwnerPID(ofFileAt path: String) -> pid_t? {
+ lockHolderPIDs(ofFileAt: path)?.first
+ }
+
+ /// True only when `pid` is a live holder of the run lock.
+ ///
+ /// A recorded PID is never trusted on its own: the process may have exited
+ /// and had its identifier recycled by something unrelated.
+ func isLiveLockHolder(pid: pid_t, ofFileAt path: String) -> Bool? {
+ guard pid > 0 else { return false }
+ return lockHolderPIDs(ofFileAt: path)?.contains(pid)
+ }
+}
+
+/// Carries a reference across a `@Sendable` boundary where the compiler cannot
+/// prove safety but the callee's use is thread-safe.
+private final class UncheckedBox<Value>: @unchecked Sendable {
+ let value: Value
+
+ init(_ value: Value) {
+ self.value = value
+ }
+}
+
+/// `lsof`-backed probe with a hard wall-clock bound.
+///
+/// `lume list` runs this once per VM that recorded a VNC-disabled session, so a
+/// slow or wedged `lsof` must never stall the caller indefinitely.
+struct LsofRunLockProbe: RunLockProbe {
+ static let defaultTimeout: TimeInterval = 2.0
+
+ let timeout: TimeInterval
+
+ init(timeout: TimeInterval = LsofRunLockProbe.defaultTimeout) {
+ self.timeout = timeout
+ }
+
+ func lockHolderPIDs(ofFileAt path: String) -> [pid_t]? {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
+ process.arguments = ["-n", "-P", "-w", "-t", path]
+ let output = Pipe()
+ process.standardOutput = output
+ // Share one pipe so exit 1 with no bytes means "no holders", while an
+ // lsof diagnostic cannot be mistaken for that definitive empty result.
+ process.standardError = output
+
+ do {
+ try process.run()
+ } catch {
+ Logger.debug(
+ "Could not run lsof to resolve the VM run lock owner",
+ metadata: ["path": path, "error": error.localizedDescription])
+ return nil
+ }
+
+ // Terminating the child closes the pipe, so the pending read below
+ // always unblocks even if lsof itself is stuck. `Process` is
+ // thread-safe for termination but not `Sendable`, so it crosses into
+ // the watchdog through an explicit box.
+ let box = UncheckedBox(process)
+ let watchdog = DispatchWorkItem {
+ let child = box.value
+ if child.isRunning {
+ child.terminate()
+ }
+ }
+ DispatchQueue.global(qos: .userInitiated).asyncAfter(
+ deadline: .now() + timeout, execute: watchdog)
+ let data = (try? output.fileHandleForReading.readToEnd()) ?? Data()
+ process.waitUntilExit()
+ watchdog.cancel()
+
+ if process.terminationReason == .uncaughtSignal {
+ return nil
+ }
+ if process.terminationStatus == 1 && data.isEmpty {
+ return []
+ }
+ guard process.terminationStatus == 0 else {
+ return nil
+ }
+ return Self.parsePIDs(from: data)
+ }
+
+ /// Parses `lsof -t` output, which emits one decimal PID per holder.
+ static func parsePIDs(from data: Data) -> [pid_t]? {
+ guard let text = String(data: data, encoding: .utf8) else { return nil }
+ let lines = text.split(whereSeparator: \.isNewline)
+ var result: [pid_t] = []
+ for line in lines {
+ guard let pid = pid_t(line), pid > 0 else {
+ return nil
+ }
+ result.append(pid)
+ }
+ return result
+ }
+}
diff --git a/libs/lume/src/VM/NativeDisplayAttachService.swift b/libs/lume/src/VM/NativeDisplayAttachService.swift
index 687900dbdc..8d87b10c23 100644
--- a/libs/lume/src/VM/NativeDisplayAttachService.swift
+++ b/libs/lume/src/VM/NativeDisplayAttachService.swift
@@ -105,27 +105,6 @@ enum NativeDisplayAttachService {
}
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
- }
+ LsofRunLockProbe(timeout: 10).lockOwnerPID(ofFileAt: configURL.path)
}
}
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index 57606e7731..8997093215 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -58,10 +58,18 @@ class VM {
private var scopedSharedDirectoryURLs: [URL] = []
private var clipboardTransferInProgress = false
private var sessionCleanedUp = true
+ /// Policy of the session currently owned by this object. Cleanup needs it
+ /// because a VNC-disabled session's marker is not owned by `vncService`.
+ private var activeVNCPolicy: VNCPolicy = .enabled
+ private var activeNoVNCSession: VNCSession?
internal let virtualizationServiceFactory:
(VMVirtualizationServiceContext) throws -> VMVirtualizationService
private let vncServiceFactory: (VMDirectory) -> VNCService
private let displayPresenterFactory: @MainActor (DisplayMode, VNCService) -> VMDisplayPresenter
+ /// Resolves the config-file run-lock owner during cross-process `stop`.
+ // Lifecycle commands may run while the host is under VM boot I/O. Give
+ // their one-shot lock lookup more time than list/get's latency-bound probe.
+ private let runLockProbe: RunLockProbe = LsofRunLockProbe(timeout: 10)
// MARK: - Initialization
@@ -167,8 +175,20 @@ class VM {
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
+ networkMode: NetworkMode? = nil, clipboard: Bool = false,
+ vncPolicy: VNCPolicy = .enabled
) async throws {
+ // Defense in depth: the CLI and the controller reject these combinations
+ // first, but no caller may reach a VNC-dependent path with VNC disabled.
+ if let option = VNCPolicy.conflictingOption(
+ policy: vncPolicy,
+ displayMode: displayMode,
+ vncPort: vncPort,
+ vncPassword: vncPassword
+ ) {
+ throw VMError.vncDisabledConflict(option)
+ }
+
guard let resizeGuard = try vmDirContext.dir.tryAcquireResizeGuard(exclusive: false) else {
throw DiskResizeError.resizeInProgress(vmDirContext.name)
}
@@ -181,6 +201,7 @@ class VM {
metadata: [
"name": vmDirContext.name,
"displayMode": displayMode.rawValue,
+ "vncPolicy": vncPolicy.rawValue,
"recoveryMode": "\(recoveryMode)",
])
@@ -252,6 +273,8 @@ class VM {
try? fileHandle.close()
}
sessionCleanedUp = false
+ activeVNCPolicy = vncPolicy
+ activeNoVNCSession = nil
activeSharedDirectories = sharedDirectories
Logger.info(
@@ -273,15 +296,20 @@ class VM {
// host directory contents, so the guest will see the file once written).
let lumeConfigDir = FileManager.default.temporaryDirectory
.appendingPathComponent("lume-config-\(vmDirContext.name)")
- try? FileManager.default.createDirectory(at: lumeConfigDir, withIntermediateDirectories: true)
// Remove stale vnc.env from a previous run so the guest doesn't
- // read outdated port/password before the new file is written.
+ // read outdated port/password before the new file is written. A
+ // VNC-disabled run does the same removal so nothing left by an
+ // earlier VNC-enabled run of this VM can leak into the guest.
try? FileManager.default.removeItem(
at: lumeConfigDir.appendingPathComponent("vnc.env"))
- let lumeConfigSharedDir = SharedDirectory(
- hostPath: lumeConfigDir.path, tag: "lume-config", readOnly: true)
var allSharedDirectories = sharedDirectories
- allSharedDirectories.append(lumeConfigSharedDir)
+ if vncPolicy.isEnabled {
+ try? FileManager.default.createDirectory(
+ at: lumeConfigDir, withIntermediateDirectories: true)
+ allSharedDirectories.append(
+ SharedDirectory(
+ hostPath: lumeConfigDir.path, tag: "lume-config", readOnly: true))
+ }
Logger.info(
"Creating virtualization service context", metadata: ["name": vmDirContext.name])
@@ -315,35 +343,54 @@ class VM {
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,
- "displayMode": displayMode.rawValue,
- "port": "\(vncPort)",
- ])
- let vncInfo = try await setupSession(
- port: vncPort, password: vncPassword, sharedDirectories: sharedDirectories)
-
- // Parse VNC port and password from the VNC URL for config distribution.
- // URL format: vnc://:password@host:port — URLComponents needs http:// to parse correctly.
+ // Parsed from the VNC URL for config distribution; both stay nil for
+ // a VNC-disabled run so no credential is ever written or sent.
var vncPortValue: Int?
var vncPasswordValue: String?
- if let components = URLComponents(string: vncInfo.replacingOccurrences(of: "vnc://", with: "http://")),
- let port = components.port {
- vncPortValue = port
- vncPasswordValue = components.password ?? ""
- let envContent = "VNC_PORT=\(port)\nVNC_PASSWORD=\(vncPasswordValue!)\n"
- try? envContent.write(
- to: lumeConfigDir.appendingPathComponent("vnc.env"),
- atomically: true, encoding: .utf8)
- Logger.info("Wrote VNC config to shared directory", metadata: [
- "port": "\(port)", "path": lumeConfigDir.path])
+ let vncInfo: String?
+
+ if vncPolicy.isEnabled {
+ // 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,
+ "displayMode": displayMode.rawValue,
+ "port": "\(vncPort)",
+ ])
+ let url = try await setupSession(
+ port: vncPort, password: vncPassword, sharedDirectories: sharedDirectories)
+ vncInfo = url
+
+ // URL format: vnc://:password@host:port — URLComponents needs http:// to parse correctly.
+ if let components = URLComponents(
+ string: url.replacingOccurrences(of: "vnc://", with: "http://")),
+ let port = components.port {
+ vncPortValue = port
+ vncPasswordValue = components.password ?? ""
+ let envContent = "VNC_PORT=\(port)\nVNC_PASSWORD=\(vncPasswordValue!)\n"
+ try? envContent.write(
+ to: lumeConfigDir.appendingPathComponent("vnc.env"),
+ atomically: true, encoding: .utf8)
+ Logger.info("Wrote VNC config to shared directory", metadata: [
+ "port": "\(port)", "path": lumeConfigDir.path])
+ }
+ Logger.info(
+ "VNC setup successful", metadata: ["name": vmDirContext.name, "vncInfo": url])
+ } else {
+ vncInfo = nil
+ // No listener, no credentials, no vnc.env. The session marker
+ // still records the owning process so a detached `get`/`list`
+ // in another process can prove this VM is running.
+ saveNoVNCSessionData(sharedDirectories: sharedDirectories)
+ Logger.info(
+ "VNC disabled for this run; no VNC server will be started",
+ metadata: [
+ "name": vmDirContext.name,
+ "displayMode": displayMode.rawValue,
+ ])
}
- Logger.info(
- "VNC setup successful", metadata: ["name": vmDirContext.name, "vncInfo": vncInfo])
// Start the VM
Logger.info(
@@ -603,8 +650,12 @@ class VM {
scopedSharedDirectoryURLs.append(url)
}
activeSharedDirectories = updated
- if let sessionURL = vncService.url {
- saveSessionData(url: sessionURL, sharedDirectories: updated)
+ if activeVNCPolicy.isEnabled {
+ if let sessionURL = vncService.url {
+ saveSessionData(url: sessionURL, sharedDirectories: updated)
+ }
+ } else if activeNoVNCSession != nil {
+ saveNoVNCSessionData(sharedDirectories: updated)
}
}
@@ -671,6 +722,12 @@ class VM {
scopedSharedDirectoryURLs.removeAll()
activeSharedDirectories.removeAll()
vncService.stop()
+ if !activeVNCPolicy.isEnabled {
+ // No VNC service owns this run's marker, so drop it here. Doing it
+ // unconditionally also covers a failed start that never booted.
+ vmDirContext.dir.clearSession()
+ activeNoVNCSession = nil
+ }
virtualizationService = nil
}
@@ -725,23 +782,10 @@ class VM {
throw VMError.notRunning(vmDirContext.name)
}
- // Get the PID of the process holding the lock using lsof command
+ // Get the PID of the process holding the lock
Logger.info(
"Finding process holding lock on config file", metadata: ["name": vmDirContext.name])
- let task = Process()
- task.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
- task.arguments = ["-F", "p", vmDirContext.dir.configPath.path]
-
- let outputPipe = Pipe()
- task.standardOutput = outputPipe
-
- try task.run()
- task.waitUntilExit()
-
- let outputData = try outputPipe.fileHandleForReading.readToEnd() ?? Data()
- guard let outputString = String(data: outputData, encoding: .utf8),
- let pidString = outputString.split(separator: "\n").first?.dropFirst(), // Drop the 'p' prefix
- let pid = pid_t(pidString)
+ guard let pid = runLockProbe.lockOwnerPID(ofFileAt: vmDirContext.dir.configPath.path)
else {
try? fileHandle.close()
Logger.info(
@@ -1112,6 +1156,33 @@ class VM {
}
}
+ /// Persists the session marker for a run started with `--vnc disabled`.
+ ///
+ /// There is no URL or port to record, so the marker carries this process's
+ /// PID and start time. `get`/`list` in another process treat the VM as
+ /// running only after proving that PID still holds the config-file run lock.
+ private func saveNoVNCSessionData(sharedDirectories: [SharedDirectory]) {
+ let session = VNCSession.vncDisabled(
+ pid: activeNoVNCSession?.pid ?? getpid(),
+ startedAt: activeNoVNCSession?.startedAt ?? Date().timeIntervalSince1970,
+ sharedDirectories: sharedDirectories.isEmpty ? nil : sharedDirectories
+ )
+ do {
+ try vmDirContext.dir.saveSession(session)
+ activeNoVNCSession = session
+ Logger.info(
+ "Saved VNC-disabled session marker",
+ metadata: [
+ "name": vmDirContext.name,
+ "pid": "\(session.pid ?? 0)",
+ "sessionsPath": vmDirContext.dir.sessionsPath.path,
+ ])
+ } catch {
+ Logger.error(
+ "Failed to save VNC-disabled session marker", metadata: ["error": "\(error)"])
+ }
+ }
+
/// Main session setup method that handles VNC and persists session data
private func setupSession(
port: Int = 0, password: String? = nil, sharedDirectories: [SharedDirectory] = []
diff --git a/libs/lume/src/VM/VMDisplayPresenter.swift b/libs/lume/src/VM/VMDisplayPresenter.swift
index a337941540..f2ca68dea9 100644
--- a/libs/lume/src/VM/VMDisplayPresenter.swift
+++ b/libs/lume/src/VM/VMDisplayPresenter.swift
@@ -4,7 +4,8 @@ import Virtualization
struct VMDisplayContext {
let virtualMachine: VZVirtualMachine?
- let vncURL: String
+ /// Nil when the run started with `--vnc disabled`, which has no listener.
+ let vncURL: String?
let resolution: VMDisplayResolution
let vmName: String
let copyFromGuest: (@MainActor () async throws -> Void)?
@@ -14,7 +15,7 @@ struct VMDisplayContext {
init(
virtualMachine: VZVirtualMachine?,
- vncURL: String,
+ vncURL: String?,
resolution: VMDisplayResolution,
vmName: String = "Lume VM",
copyFromGuest: (@MainActor () async throws -> Void)? = nil,
@@ -60,7 +61,10 @@ final class VNCClientPresenter: VMDisplayPresenter {
}
func show(context: VMDisplayContext) async throws {
- try await vncService.openClient(url: context.vncURL)
+ guard let vncURL = context.vncURL else {
+ throw VMError.vncNotConfigured
+ }
+ try await vncService.openClient(url: vncURL)
}
func hide() {}
diff --git a/libs/lume/src/VM/VNCPolicy.swift b/libs/lume/src/VM/VNCPolicy.swift
new file mode 100644
index 0000000000..1b2ac2d976
--- /dev/null
+++ b/libs/lume/src/VM/VNCPolicy.swift
@@ -0,0 +1,32 @@
+import ArgumentParser
+import Foundation
+
+/// Whether a run exposes a VNC server at all.
+///
+/// This is orthogonal to `DisplayMode`: the display mode selects which local
+/// viewer Lume opens, while the policy decides whether the remote VNC listener
+/// exists. `enabled` is the default and preserves historic behavior for every
+/// display mode. `disabled` is an explicit opt-in that starts no listener,
+/// publishes no credentials, and reports a nil `vncUrl`.
+enum VNCPolicy: String, CaseIterable, Codable, ExpressibleByArgument, Sendable {
+ case enabled
+ case disabled
+
+ var isEnabled: Bool { self == .enabled }
+
+ /// The option that conflicts with `disabled`, or nil when the combination is
+ /// valid. Shared by the CLI, the controller, and the HTTP/MCP surfaces so all
+ /// of them reject the same combinations.
+ static func conflictingOption(
+ policy: VNCPolicy,
+ displayMode: DisplayMode,
+ vncPort: Int,
+ vncPassword: String?
+ ) -> String? {
+ guard policy == .disabled else { return nil }
+ if displayMode == .vnc { return "--display vnc" }
+ if vncPort != 0 { return "--vnc-port" }
+ if vncPassword != nil { return "--vnc-password" }
+ return nil
+ }
+}
diff --git a/libs/lume/src/VNC/VNCService.swift b/libs/lume/src/VNC/VNCService.swift
index 6a6daa6e24..fac0255da9 100644
--- a/libs/lume/src/VNC/VNCService.swift
+++ b/libs/lume/src/VNC/VNCService.swift
@@ -65,7 +65,8 @@ final class DefaultVNCService: VNCService {
var url: String? {
get {
- return try? vmDirectory.loadSession().url
+ // A VNC-disabled marker has no URL, so this stays nil for those runs.
+ return (try? vmDirectory.loadSession())?.url
}
}
diff --git a/libs/lume/tests/Mocks/MockVM.swift b/libs/lume/tests/Mocks/MockVM.swift
index 169d9035b2..31013b8ea4 100644
--- a/libs/lume/tests/Mocks/MockVM.swift
+++ b/libs/lume/tests/Mocks/MockVM.swift
@@ -25,7 +25,8 @@ class MockVM: VM {
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
+ networkMode: NetworkMode? = nil, clipboard: Bool = false,
+ vncPolicy: VNCPolicy = .enabled
) async throws {
mockIsRunning = true
try await super.run(
@@ -33,7 +34,8 @@ class MockVM: VM {
vncPort: vncPort, vncPassword: vncPassword, recoveryMode: recoveryMode,
usbMassStoragePaths: usbMassStoragePaths,
additionalDiskPaths: additionalDiskPaths,
- networkMode: networkMode, clipboard: clipboard
+ networkMode: networkMode, clipboard: clipboard,
+ vncPolicy: vncPolicy
)
}
diff --git a/libs/lume/tests/VNCPolicyTests.swift b/libs/lume/tests/VNCPolicyTests.swift
new file mode 100644
index 0000000000..e841706085
--- /dev/null
+++ b/libs/lume/tests/VNCPolicyTests.swift
@@ -0,0 +1,558 @@
+import ArgumentParser
+import Foundation
+import Testing
+
+@testable import lume
+
+// MARK: - Helpers
+
+private enum VNCPolicyTestError: Error {
+ case presenterFailed
+}
+
+@MainActor
+private final class RecordingPresenter: VMDisplayPresenter {
+ private(set) var showCount = 0
+ private(set) var hideCount = 0
+ private(set) var lastContext: VMDisplayContext?
+ var showError: Error?
+
+ func show(context: VMDisplayContext) async throws {
+ showCount += 1
+ lastContext = context
+ if let showError { throw showError }
+ }
+
+ func hide() {
+ hideCount += 1
+ }
+}
+
+private struct StubRunLockProbe: RunLockProbe {
+ let holdersByPath: [String: [pid_t]]
+ var inconclusivePaths: Swift.Set<String> = []
+
+ func lockHolderPIDs(ofFileAt path: String) -> [pid_t]? {
+ if inconclusivePaths.contains(path) { return nil }
+ return holdersByPath[path] ?? []
+ }
+}
+
+private func makeVMTestDirectory() throws -> (URL, 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)
+
+ return (
+ root,
+ 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))
+ }
+}
+
+/// Path of the VirtioFS file that publishes VNC credentials to the guest.
+private func vncEnvURL(forVMNamed name: String) -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-config-\(name)")
+ .appendingPathComponent("vnc.env")
+}
+
+// MARK: - CLI surface
+
+@Test("run defaults to an enabled VNC server")
+func vncPolicyDefaultsToEnabled() throws {
+ let command = try Run.parse(["test-vm"])
+ #expect(command.vnc == .enabled)
+ try command.validate()
+}
+
+@Test("--vnc accepts both policies and rejects anything else")
+func vncPolicyParsing() throws {
+ #expect(try Run.parse(["test-vm", "--vnc", "enabled"]).vnc == .enabled)
+ #expect(try Run.parse(["test-vm", "--vnc", "disabled"]).vnc == .disabled)
+ #expect(throws: Error.self) {
+ _ = try Run.parse(["test-vm", "--vnc", "off"])
+ }
+}
+
+@Test("--vnc disabled is accepted with the non-VNC display modes")
+func vncDisabledAcceptedForNonVNCDisplays() throws {
+ try Run.parse(["test-vm", "--vnc", "disabled", "--display", "none"]).validate()
+ try Run.parse(["test-vm", "--vnc", "disabled", "--display", "native"]).validate()
+ try Run.parse(["test-vm", "--vnc", "disabled"]).validate()
+ // --no-display wins over --display, so the resolved mode is not vnc.
+ try Run.parse(["test-vm", "--vnc", "disabled", "--display", "vnc", "--no-display"]).validate()
+}
+
+/// Parses and validates a `run` invocation, reporting whether it was rejected.
+/// ArgumentParser may surface a validation failure from either step, so both
+/// are treated as one rejection.
+private func runIsRejected(_ arguments: [String]) -> Bool {
+ do {
+ try Run.parse(arguments).validate()
+ return false
+ } catch {
+ return true
+ }
+}
+
+@Test("--vnc disabled is rejected with options that need a VNC server")
+func vncDisabledRejectsConflictingOptions() throws {
+ #expect(runIsRejected(["test-vm", "--vnc", "disabled", "--display", "vnc"]))
+ #expect(runIsRejected(["test-vm", "--vnc", "disabled", "--vnc-port", "5900"]))
+ #expect(runIsRejected(["test-vm", "--vnc", "disabled", "--vnc-password", "hunter2"]))
+ // The same rejection must reach the root command parser.
+ #expect(throws: Error.self) {
+ _ = try Lume.parseAsRoot(["run", "test-vm", "--vnc", "disabled", "--display", "vnc"])
+ }
+}
+
+@Test("enabled runs keep accepting every VNC option")
+func vncEnabledKeepsExistingCombinations() throws {
+ try Run.parse(["test-vm", "--display", "vnc", "--vnc-port", "5900"]).validate()
+ try Run.parse(["test-vm", "--vnc", "enabled", "--vnc-password", "hunter2"]).validate()
+}
+
+@Test("Detached child arguments preserve the VNC policy")
+func detachedChildArgumentsPreserveVNCPolicy() {
+ let separated = DetachedVMRunner.childArguments(from: [
+ "/path/to/lume", "run", "test-vm", "--detach", "--vnc", "disabled",
+ ])
+ #expect(separated == ["run", "test-vm", "--vnc", "disabled", "--display", "none"])
+
+ let joined = DetachedVMRunner.childArguments(from: [
+ "/path/to/lume", "run", "test-vm", "--detach", "--vnc=disabled", "--display", "native",
+ ])
+ #expect(joined == ["run", "test-vm", "--vnc=disabled", "--display", "native"])
+}
+
+// MARK: - Session marker compatibility
+
+@Test("Legacy session markers still decode as VNC-enabled")
+func legacySessionDecoding() throws {
+ let legacy = Data(
+ #"{"url":"vnc://:[email protected]:62295"}"#.utf8)
+ let session = try JSONDecoder().decode(VNCSession.self, from: legacy)
+
+ #expect(session.url == "vnc://:[email protected]:62295")
+ #expect(session.isVNCEnabled)
+ #expect(session.pid == nil)
+ #expect(session.startedAt == nil)
+
+ let withDirs = Data(
+ #"{"url":"vnc://:[email protected]:62295","sharedDirectories":[{"hostPath":"/tmp","tag":"com.apple.virtio-fs.automount","readOnly":false}]}"#
+ .utf8)
+ let decoded = try JSONDecoder().decode(VNCSession.self, from: withDirs)
+ #expect(decoded.sharedDirectories?.count == 1)
+ #expect(decoded.isVNCEnabled)
+}
+
+@Test("VNC-disabled session markers decode with their liveness fields")
+func noVNCSessionDecoding() throws {
+ let data = Data(#"{"vncEnabled":false,"pid":4242,"startedAt":1750000000.0}"#.utf8)
+ let session = try JSONDecoder().decode(VNCSession.self, from: data)
+
+ #expect(session.url == nil)
+ #expect(!session.isVNCEnabled)
+ #expect(session.pid == 4242)
+ #expect(session.startedAt == 1_750_000_000.0)
+}
+
+@Test("An enabled session marker still encodes only the legacy fields")
+func enabledSessionEncodingStaysLegacy() throws {
+ let data = try JSONEncoder().encode(VNCSession(url: "vnc://:[email protected]:62295"))
+ let decoded = try JSONSerialization.jsonObject(with: data)
+ let object = try #require(decoded as? [String: Any])
+
+ #expect(Swift.Set(object.keys) == Swift.Set(["url"]))
+}
+
+@Test("A VNC-disabled marker round-trips through the VM directory")
+func noVNCSessionRoundTrip() throws {
+ let (root, context) = try makeVMTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try context.dir.saveSession(
+ VNCSession.vncDisabled(pid: 4242, startedAt: 1_750_000_000.0))
+ let loaded = try context.dir.loadSession()
+
+ #expect(loaded.url == nil)
+ #expect(!loaded.isVNCEnabled)
+ #expect(loaded.pid == 4242)
+ #expect(loaded.startedAt == 1_750_000_000.0)
+}
+
+// MARK: - VM lifecycle
+
+@MainActor
+@Test("A VNC-disabled run never starts VNC and clears its marker on shutdown")
+func disabledRunNeverStartsVNC() async throws {
+ let (root, context) = try makeVMTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let envURL = vncEnvURL(forVMNamed: context.name)
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = RecordingPresenter()
+ 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, vncPolicy: .disabled)
+ }
+ try await waitUntil { presenter.showCount == 1 }
+
+ #expect(vnc.startCallCount == 0)
+ #expect(vm.getVNCUrl() == nil)
+ let displayContext = try #require(presenter.lastContext)
+ #expect(displayContext.vncURL == nil)
+ #expect(!FileManager.default.fileExists(atPath: envURL.path))
+
+ let session = try context.dir.loadSession()
+ #expect(!session.isVNCEnabled)
+ #expect(session.url == nil)
+ #expect(session.pid == getpid())
+ #expect((session.startedAt ?? 0) > 0)
+
+ service.simulateGuestStop()
+ try await runTask.value
+
+ #expect(vnc.startCallCount == 0)
+ #expect(!context.dir.sessionsPath.exists())
+ #expect(!FileManager.default.fileExists(atPath: envURL.path))
+}
+
+@MainActor
+@Test("Every display mode keeps starting VNC when the policy is enabled")
+func enabledRunKeepsStartingVNCForEveryDisplayMode() async throws {
+ for mode in DisplayMode.allCases {
+ let (root, context) = try makeVMTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = RecordingPresenter()
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in presenter }
+ )
+
+ let runTask = Task {
+ try await vm.run(displayMode: mode, sharedDirectories: [], mount: nil)
+ }
+ try await waitUntil { presenter.showCount == 1 }
+
+ #expect(vnc.startCallCount == 1)
+ let session = try context.dir.loadSession()
+ #expect(session.isVNCEnabled)
+ #expect(session.url != nil)
+ #expect(session.pid == nil)
+ let displayContext = try #require(presenter.lastContext)
+ #expect(displayContext.vncURL != nil)
+
+ service.simulateGuestStop()
+ try await runTask.value
+ }
+}
+
+@MainActor
+@Test("A failed start on a VNC-disabled run removes the session marker")
+func disabledRunClearsMarkerOnStartFailure() async throws {
+ let (root, context) = try makeVMTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let presenter = RecordingPresenter()
+ presenter.showError = VNCPolicyTestError.presenterFailed
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in presenter }
+ )
+
+ await #expect(throws: VNCPolicyTestError.self) {
+ try await vm.run(
+ displayMode: .none, sharedDirectories: [], mount: nil, vncPolicy: .disabled)
+ }
+
+ #expect(service.stopCallCount == 1)
+ #expect(vnc.startCallCount == 0)
+ #expect(!context.dir.sessionsPath.exists())
+}
+
+@MainActor
+@Test("VM.run refuses a VNC-disabled run that needs a VNC server")
+func vmRunRefusesConflictingVNCPolicy() async throws {
+ let (root, context) = try makeVMTestDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let service = MockVMVirtualizationService()
+ let vnc = MockVNCService(vmDirectory: context.dir)
+ let vm = MockVM(
+ vmDirContext: context,
+ virtualizationServiceFactory: { _ in service },
+ vncServiceFactory: { _ in vnc },
+ displayPresenterFactory: { _, _ in RecordingPresenter() }
+ )
+
+ await #expect(throws: VMError.self) {
+ try await vm.run(
+ displayMode: .vnc, sharedDirectories: [], mount: nil, vncPolicy: .disabled)
+ }
+ await #expect(throws: VMError.self) {
+ try await vm.run(
+ displayMode: .none, sharedDirectories: [], mount: nil, vncPort: 5900,
+ vncPolicy: .disabled)
+ }
+ #expect(vnc.startCallCount == 0)
+ #expect(!context.dir.sessionsPath.exists())
+}
+
+// MARK: - Run lock probe
+
+@Test("lsof -t output parses into holder PIDs")
+func runLockProbeParsesHolders() {
+ #expect(LsofRunLockProbe.parsePIDs(from: Data("123\n456\n".utf8)) == [123, 456])
+ #expect(LsofRunLockProbe.parsePIDs(from: Data("".utf8)) == [])
+ #expect(LsofRunLockProbe.parsePIDs(from: Data("f3\ntext\n".utf8)) == nil)
+}
+
+@Test("A recorded PID is trusted only while it holds the run lock")
+func runLockProbeLiveHolderRule() {
+ let probe = StubRunLockProbe(holdersByPath: ["/vm/config.json": [4242]])
+
+ #expect(probe.isLiveLockHolder(pid: 4242, ofFileAt: "/vm/config.json") == true)
+ #expect(probe.isLiveLockHolder(pid: 999, ofFileAt: "/vm/config.json") == false)
+ #expect(probe.isLiveLockHolder(pid: 0, ofFileAt: "/vm/config.json") == false)
+ #expect(probe.isLiveLockHolder(pid: 4242, ofFileAt: "/other/config.json") == false)
+ #expect(probe.lockOwnerPID(ofFileAt: "/vm/config.json") == 4242)
+ #expect(probe.lockOwnerPID(ofFileAt: "/other/config.json") == nil)
+}
+
+// MARK: - Cross-process status
+
+/// Creates an isolated storage location holding one stopped VM.
+///
+/// Addressing the location by absolute path keeps these tests off the shared
+/// settings file, so they never race other tests over `XDG_CONFIG_HOME`.
+private func makeStoppedVMLocation(named name: String) throws -> (URL, VMDirectory) {
+ let storage = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: storage, withIntermediateDirectories: true)
+
+ let vmDir = VMDirectory(Path(storage.path).directory(name))
+ try FileManager.default.createDirectory(
+ at: vmDir.dir.url, withIntermediateDirectories: true)
+ try Data(repeating: 0, count: 1024).write(to: vmDir.diskPath.url)
+ try Data(repeating: 0, count: 1024).write(to: vmDir.nvramPath.url)
+ try vmDir.saveConfig(
+ VMConfig(
+ os: "macOS",
+ cpuCount: 1,
+ memorySize: 1024,
+ diskSize: 1024,
+ display: "1024x768"
+ ))
+ return (storage, vmDir)
+}
+
+@MainActor
+@Test("A VNC-disabled VM reports running while its PID holds the run lock")
+func noVNCStatusIsRunningForLiveLockHolder() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "no-vnc-live")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ try vmDir.saveSession(
+ VNCSession.vncDisabled(pid: 4242, startedAt: Date().timeIntervalSince1970))
+
+ let controller = LumeController(
+ runLockProbe: StubRunLockProbe(holdersByPath: [vmDir.configPath.path: [4242]]))
+
+ let details = try controller.getDetails(name: "no-vnc-live", storage: storage.path)
+ #expect(details.status == "running")
+ #expect(details.vncUrl == nil)
+ #expect(vmDir.sessionsPath.exists())
+
+ let all = try controller.list(storage: storage.path)
+ let listed = try #require(all.first)
+ #expect(listed.name == "no-vnc-live")
+ #expect(listed.status == "running")
+ #expect(listed.vncUrl == nil)
+}
+
+@MainActor
+@Test("A VNC-disabled marker whose PID no longer holds the lock is stale")
+func noVNCStatusIsStoppedForDeadLockHolder() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "no-vnc-stale")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ try vmDir.saveSession(
+ VNCSession.vncDisabled(pid: 4242, startedAt: Date().timeIntervalSince1970))
+
+ let controller = LumeController(runLockProbe: StubRunLockProbe(holdersByPath: [:]))
+
+ let details = try controller.getDetails(name: "no-vnc-stale", storage: storage.path)
+ #expect(details.status == "stopped")
+ #expect(details.vncUrl == nil)
+ #expect(!vmDir.sessionsPath.exists())
+}
+
+@MainActor
+@Test("A recycled PID does not make a VNC-disabled VM look running")
+func noVNCStatusRejectsRecycledPID() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "no-vnc-recycled")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ try vmDir.saveSession(
+ VNCSession.vncDisabled(pid: 4242, startedAt: Date().timeIntervalSince1970))
+
+ let controller = LumeController(
+ runLockProbe: StubRunLockProbe(holdersByPath: [vmDir.configPath.path: [777]]))
+
+ let details = try controller.getDetails(name: "no-vnc-recycled", storage: storage.path)
+ #expect(details.status == "stopped")
+ #expect(!vmDir.sessionsPath.exists())
+}
+
+@MainActor
+@Test("A VNC-disabled marker without a PID is never trusted")
+func noVNCStatusRejectsMarkerWithoutPID() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "no-vnc-pidless")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ try vmDir.saveSession(VNCSession(url: nil, vncEnabled: false))
+
+ let controller = LumeController(
+ runLockProbe: StubRunLockProbe(holdersByPath: [vmDir.configPath.path: [4242]]))
+
+ let details = try controller.getDetails(name: "no-vnc-pidless", storage: storage.path)
+ #expect(details.status == "stopped")
+ #expect(!vmDir.sessionsPath.exists())
+}
+
+@MainActor
+@Test("An inconclusive lock probe preserves a VNC-disabled marker")
+func noVNCStatusPreservesMarkerWhenProbeIsInconclusive() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "no-vnc-inconclusive")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ try vmDir.saveSession(
+ VNCSession.vncDisabled(pid: 4242, startedAt: Date().timeIntervalSince1970))
+
+ let controller = LumeController(
+ runLockProbe: StubRunLockProbe(
+ holdersByPath: [:], inconclusivePaths: [vmDir.configPath.path]))
+
+ let details = try controller.getDetails(name: "no-vnc-inconclusive", storage: storage.path)
+ #expect(details.status == "stopped")
+ #expect(details.vncUrl == nil)
+ #expect(vmDir.sessionsPath.exists())
+}
+
+@MainActor
+@Test("A stale VNC-backed marker is still detected by its port, not by the run lock")
+func vncEnabledStatusStillUsesPortProbe() throws {
+ let (storage, vmDir) = try makeStoppedVMLocation(named: "vnc-stale")
+ defer { try? FileManager.default.removeItem(at: storage) }
+ // Port 1 is never bound by a VM, so this marker must read as stale even
+ // though a process does hold the config file open.
+ try vmDir.saveSession(VNCSession(url: "vnc://:[email protected]:1"))
+
+ let controller = LumeController(
+ runLockProbe: StubRunLockProbe(holdersByPath: [vmDir.configPath.path: [getpid()]]))
+
+ let details = try controller.getDetails(name: "vnc-stale", storage: storage.path)
+ #expect(details.status == "stopped")
+ #expect(details.vncUrl == nil)
+ #expect(!vmDir.sessionsPath.exists())
+}
+
+// MARK: - HTTP / MCP request surfaces
+
+private func decodeRunRequest(_ json: String) throws -> RunVMRequest {
+ try JSONDecoder().decode(RunVMRequest.self, from: Data(json.utf8))
+}
+
+@Test("The run request body defaults to an enabled VNC server")
+func runRequestDefaultsToEnabled() throws {
+ #expect(try decodeRunRequest("{}").parseVNCPolicy() == .enabled)
+ #expect(try decodeRunRequest(#"{"noDisplay":true}"#).parseVNCPolicy() == .enabled)
+}
+
+@Test("The run request body carries an explicit VNC policy")
+func runRequestParsesVNCPolicy() throws {
+ #expect(try decodeRunRequest(#"{"vnc":"enabled"}"#).parseVNCPolicy() == .enabled)
+ #expect(try decodeRunRequest(#"{"vnc":"disabled"}"#).parseVNCPolicy() == .disabled)
+ #expect(throws: ValidationError.self) {
+ _ = try decodeRunRequest(#"{"vnc":"off"}"#).parseVNCPolicy()
+ }
+}
+
+@Test("HTTP-style VNC-disabled runs reject the default VNC display before dispatch")
+func httpRunVNCPolicyConflictIsSynchronous() throws {
+ let request = try decodeRunRequest(#"{"vnc":"disabled"}"#)
+ #expect(throws: VMError.self) {
+ _ = try request.validatedVNCPolicy(noDisplayDefault: false)
+ }
+ #expect(
+ try decodeRunRequest(#"{"vnc":"disabled","noDisplay":true}"#)
+ .validatedVNCPolicy(noDisplayDefault: false) == .disabled)
+}
+
+@Test("The conflicting-option rule is shared by every run surface")
+func conflictingOptionRule() {
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .enabled, displayMode: .vnc, vncPort: 5900, vncPassword: "x") == nil)
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .disabled, displayMode: .vnc, vncPort: 0, vncPassword: nil) == "--display vnc")
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .disabled, displayMode: .none, vncPort: 5900, vncPassword: nil) == "--vnc-port")
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .disabled, displayMode: .native, vncPort: 0, vncPassword: "x") == "--vnc-password")
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .disabled, displayMode: .none, vncPort: 0, vncPassword: nil) == nil)
+ #expect(
+ VNCPolicy.conflictingOption(
+ policy: .disabled, displayMode: .native, vncPort: 0, vncPassword: nil) == nil)
+}