Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(lume): refuse a macOS guest start at the host's macOS guest limit (#3958)

lorenzozane69ca401e2d6d
diff --git a/docs/content/docs/lume/reference/http-api.mdx b/docs/content/docs/lume/reference/http-api.mdx
index a1f6bac0eb..97adc5a9bb 100644
--- a/docs/content/docs/lume/reference/http-api.mdx
+++ b/docs/content/docs/lume/reference/http-api.mdx
@@ -415,6 +415,7 @@ const data = await response.json();
**Response**
- `202`: VM start initiated (async operation).
+- `409`: Host limit of running macOS guests reached.
- `400`: Invalid request or VM not found.
### Stop a running virtual machine
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index 2ac4ba79a3..4c6c512e3d 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -22,6 +22,12 @@ final class SharedVM {
func removeVM(name: String) {
runningVMs.removeValue(forKey: name)
}
+
+ /// Drops cached VMs whose guest no longer runs in this process, such as a
+ /// guest that shut itself down.
+ func removeStoppedVMs() {
+ runningVMs = runningVMs.filter { $0.value.isRunActive }
+ }
}
// MARK: - Pull Progress Tracker
@@ -181,6 +187,15 @@ final class LumeController {
// MARK: - Public VM Management Methods
+ /// The VMs whose guests are running, across all storage locations unless
+ /// `storage` names one. Cache entries for guests that already stopped are
+ /// dropped first, so a guest that shut itself down is not counted as running.
+ @MainActor
+ public func runningVMs(storage: String? = nil) throws -> [VMDetails] {
+ SharedVM.shared.removeStoppedVMs()
+ return try list(storage: storage).filter { $0.status == "running" }
+ }
+
/// Lists all virtual machines in the system
/// Uses a lightweight path that reads config directly without instantiating full VM objects
@MainActor
diff --git a/libs/lume/src/Server/APIDocExtractor.swift b/libs/lume/src/Server/APIDocExtractor.swift
index ff886d9eff..41ea7cece6 100644
--- a/libs/lume/src/Server/APIDocExtractor.swift
+++ b/libs/lume/src/Server/APIDocExtractor.swift
@@ -327,6 +327,7 @@ enum APIDocExtractor {
),
statusCodes: [
APIStatusCodeDoc(code: 202, description: "VM start initiated (async operation)"),
+ APIStatusCodeDoc(code: 409, description: "Host limit of running macOS guests reached"),
APIStatusCodeDoc(code: 400, description: "Invalid request or VM not found")
]
)
diff --git a/libs/lume/src/Server/HTTP.swift b/libs/lume/src/Server/HTTP.swift
index 7efe0f2824..27d16de05f 100644
--- a/libs/lume/src/Server/HTTP.swift
+++ b/libs/lume/src/Server/HTTP.swift
@@ -23,7 +23,7 @@ struct HTTPRequest {
guard let requestString = String(data: data, encoding: .utf8) else { return nil }
let components = requestString.components(separatedBy: "\r\n\r\n")
guard components.count >= 1 else { return nil }
-
+
let headerLines = components[0].components(separatedBy: "\r\n")
guard !headerLines.isEmpty else { return nil }
@@ -59,6 +59,7 @@ struct HTTPResponse {
case ok = 200
case accepted = 202
case badRequest = 400
+ case conflict = 409
case notFound = 404
case internalServerError = 500
@@ -67,6 +68,7 @@ struct HTTPResponse {
case .ok: return "OK"
case .accepted: return "Accepted"
case .badRequest: return "Bad Request"
+ case .conflict: return "Conflict"
case .notFound: return "Not Found"
case .internalServerError: return "Internal Server Error"
}
@@ -118,4 +120,4 @@ final class HTTPServer {
init(port: UInt16) {
self.port = port
}
-}
\ No newline at end of file
+}
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 22e39f5425..04d6b44e2c 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -559,6 +559,24 @@ extension Server {
let vncPolicy = try request.validatedVNCPolicy(noDisplayDefault: false)
let noDisplay = request.noDisplay ?? false
+ // Virtualization.framework runs at most two macOS guests per host
+ // and fails a third start only after the async start was accepted,
+ // so refuse it up front. Linux guests are not limited.
+ let controller = LumeController()
+ if let target = try? controller.getDetails(name: name, storage: request.storage),
+ let capacityError = Self.macOSGuestCapacityError(
+ targetOS: target.os,
+ runningMacOSGuests: Self.runningMacOSGuestCount(
+ try controller.runningVMs(), excluding: target.name)
+ )
+ {
+ return HTTPResponse(
+ statusCode: .conflict,
+ headers: ["Content-Type": "application/json"],
+ body: try JSONEncoder().encode(APIError(message: capacityError))
+ )
+ }
+
// Start VM in background
Logger.info("Starting VM in background", metadata: ["name": name])
startVM(
@@ -1002,8 +1020,11 @@ extension Server {
/// Response structure for host status endpoint
struct HostStatusResponse: Codable {
let status: String
+ /// Running VMs, macOS and Linux.
let vmCount: Int
+ /// The most macOS guests the host runs at once.
let maxVMs: Int
+ /// macOS guests that can still start.
let availableSlots: Int
let version: String
@@ -1021,18 +1042,16 @@ extension Server {
do {
let vmController = LumeController()
- // Get all VMs across all storage locations
- let vms = try vmController.list(storage: nil)
-
- // Count running VMs (Apple policy: max 2 VMs per host)
- let runningVMs = vms.filter { $0.status == "running" }
- let maxVMs = 2 // Apple Virtualization Framework limit
+ // Running VMs across all storage locations. Only macOS guests
+ // take one of the host's slots (Virtualization.framework limit).
+ let runningVMs = try vmController.runningVMs()
+ let maxVMs = Self.maxRunningMacOSGuests
let response = HostStatusResponse(
status: "healthy",
vmCount: runningVMs.count,
maxVMs: maxVMs,
- availableSlots: max(0, maxVMs - runningVMs.count),
+ availableSlots: max(0, maxVMs - Self.runningMacOSGuestCount(runningVMs)),
version: Lume.Version.current
)
@@ -1045,6 +1064,30 @@ extension Server {
// MARK: - Private Helper Methods
+ /// Virtualization.framework runs at most two macOS guests per host at a
+ /// time. Linux guests do not count toward this limit.
+ static let maxRunningMacOSGuests = 2
+
+ static func isMacOSGuest(_ os: String) -> Bool {
+ os.lowercased() == "macos"
+ }
+
+ /// The running macOS guests in `vms`, leaving out the VM named `excluding`.
+ static func runningMacOSGuestCount(_ vms: [VMDetails], excluding name: String? = nil) -> Int {
+ vms.filter { $0.status == "running" && isMacOSGuest($0.os) && $0.name != name }.count
+ }
+
+ /// Why a VM with `targetOS` may not start while `runningMacOSGuests` macOS
+ /// guests run, or nil when it may.
+ static func macOSGuestCapacityError(
+ targetOS: String,
+ runningMacOSGuests: Int,
+ maxGuests: Int = maxRunningMacOSGuests
+ ) -> String? {
+ guard isMacOSGuest(targetOS), runningMacOSGuests >= maxGuests else { return nil }
+ return "VM start rejected: host limit of \(maxGuests) running macOS guests reached"
+ }
+
nonisolated private func startVM(
name: String,
noDisplay: Bool,
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index 352b0e1e81..a39a13fb5f 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -109,6 +109,10 @@ class VM {
/// The VM configuration
var config: VMConfig { vmDirContext.config }
+ /// Whether this process is running the guest: true from the moment `run`
+ /// starts until the guest stops or the run fails.
+ var isRunActive: Bool { !sessionCleanedUp }
+
// MARK: - VM State Management
private var isRunning: Bool {
diff --git a/libs/lume/tests/ServerHandlerTests.swift b/libs/lume/tests/ServerHandlerTests.swift
new file mode 100644
index 0000000000..9a2163829d
--- /dev/null
+++ b/libs/lume/tests/ServerHandlerTests.swift
@@ -0,0 +1,114 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+private func details(_ name: String, os: String, status: String = "running") -> VMDetails {
+ VMDetails(
+ name: name,
+ os: os,
+ cpuCount: 1,
+ memorySize: 1024,
+ diskSize: DiskSize(allocated: 0, total: 1024),
+ display: "1024x768",
+ status: status,
+ vncUrl: nil,
+ ipAddress: nil,
+ locationName: "home"
+ )
+}
+
+@MainActor
+@Test("Starting a macOS guest is refused when the host runs the most macOS guests")
+func runVMRefusesMacOSGuestAtLimit() {
+ let running = [details("mac-a", os: "macOS"), details("mac-b", os: "macOS")]
+ let count = Server.runningMacOSGuestCount(running, excluding: "mac-c")
+ #expect(count == Server.maxRunningMacOSGuests)
+ #expect(
+ Server.macOSGuestCapacityError(targetOS: "macOS", runningMacOSGuests: count)
+ == "VM start rejected: host limit of 2 running macOS guests reached")
+ #expect(Server.macOSGuestCapacityError(targetOS: "macOS", runningMacOSGuests: 1) == nil)
+}
+
+@MainActor
+@Test("Linux guests are never refused and do not count toward the macOS guest limit")
+func runVMIgnoresLinuxGuestsForTheLimit() {
+ let running = [
+ details("linux-a", os: "linux"),
+ details("linux-b", os: "linux"),
+ details("linux-c", os: "linux"),
+ details("mac-a", os: "macOS"),
+ details("mac-stopped", os: "macOS", status: "stopped"),
+ ]
+ let count = Server.runningMacOSGuestCount(running, excluding: "mac-b")
+ #expect(count == 1)
+ #expect(Server.macOSGuestCapacityError(targetOS: "macOS", runningMacOSGuests: count) == nil)
+ #expect(
+ Server.macOSGuestCapacityError(
+ targetOS: "linux", runningMacOSGuests: Server.maxRunningMacOSGuests) == nil)
+ // A VM is not counted against its own start.
+ #expect(Server.runningMacOSGuestCount(running, excluding: "mac-a") == 0)
+}
+
+@MainActor
+private final class GuestStopVMFactory: VMFactory {
+ private(set) var services: [MockVMVirtualizationService] = []
+
+ func createVM(vmDirContext: VMDirContext, imageLoader: ImageLoader?) throws -> VM {
+ MockVM(
+ vmDirContext: vmDirContext,
+ virtualizationServiceFactory: { [unowned self] _ in
+ let service = MockVMVirtualizationService()
+ self.services.append(service)
+ return service
+ },
+ vncServiceFactory: { MockVNCService(vmDirectory: $0) }
+ )
+ }
+}
+
+@MainActor
+@Test("A macOS guest that stopped by itself is not counted as running")
+func guestStoppedVMIsNotCountedAsRunning() async throws {
+ // The VM lives in a throwaway directory addressed by path, so the test
+ // never reads or changes the user's Lume configuration.
+ let storage = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: storage, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: storage) }
+
+ let home = Home(fileManager: .default)
+ let factory = GuestStopVMFactory()
+ let controller = LumeController(home: home, vmFactory: factory)
+
+ let name = "guest-stop-\(UUID().uuidString.prefix(8).lowercased())"
+ let vmDir = try home.getVMDirectoryFromPath(name, storagePath: storage.path)
+ 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)
+ var config = try VMConfig(
+ os: "macOS", cpuCount: 1, memorySize: 1024, diskSize: 1024, display: "1024x768")
+ config.setMacAddress("00:11:22:33:44:56")
+ try vmDir.saveConfig(config)
+ defer { SharedVM.shared.removeVM(name: name) }
+
+ let run = Task { @MainActor in
+ try await controller.runVM(
+ name: name, noDisplay: true, storage: storage.path, vncPolicy: .disabled)
+ }
+ let clock = ContinuousClock()
+ let deadline = clock.now.advanced(by: .seconds(5))
+ while factory.services.first?.state != .running, clock.now < deadline {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ let service = try #require(factory.services.first)
+ #expect(service.state == .running)
+ #expect(Server.runningMacOSGuestCount(try controller.runningVMs(storage: storage.path)) == 1)
+
+ // The guest powers itself off; nothing calls stop.
+ service.simulateGuestStop()
+ try await run.value
+
+ #expect(try controller.runningVMs(storage: storage.path).isEmpty)
+ #expect(SharedVM.shared.getVM(name: name) == nil)
+}