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): report a VM stopped once its guest stops on its own (#4853)

ddupont3d9879ee54e7
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index 4c6c512e3d..3a4f4da763 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -23,6 +23,25 @@ final class SharedVM {
runningVMs.removeValue(forKey: name)
}
+ /// Removes the entry for `name` only while it still holds `vm`, so a run
+ /// that ends never drops a later run's entry.
+ func removeVM(name: String, ifSame vm: VM) {
+ if runningVMs[name] === vm {
+ runningVMs.removeValue(forKey: name)
+ }
+ }
+
+ /// The cached VM for `name` while its guest still runs in this process.
+ /// An entry for a guest that already stopped is dropped.
+ func liveVM(name: String) -> VM? {
+ guard let vm = runningVMs[name] else { return nil }
+ guard vm.isRunActive else {
+ runningVMs.removeValue(forKey: name)
+ return nil
+ }
+ return vm
+ }
+
/// Drops cached VMs whose guest no longer runs in this process, such as a
/// guest that shut itself down.
func removeStoppedVMs() {
@@ -317,7 +336,7 @@ final class LumeController {
}
// Check if VM is running via SharedVM cache (same-process fast path)
- let runningVM = SharedVM.shared.getVM(name: vmName)
+ let runningVM = SharedVM.shared.liveVM(name: vmName)
var isRunning = runningVM != nil
// Get VNC URL and IP address only if running
@@ -1054,7 +1073,7 @@ final class LumeController {
}
// Stop VM if it's running
- if SharedVM.shared.getVM(name: normalizedName) != nil {
+ if SharedVM.shared.liveVM(name: normalizedName) != nil {
try await stopVM(name: normalizedName)
}
@@ -1216,7 +1235,7 @@ final class LumeController {
// Try to get VM from cache first
let vm: VM
- if let cachedVM = SharedVM.shared.getVM(name: normalizedName) {
+ if let cachedVM = SharedVM.shared.liveVM(name: normalizedName) {
vm = cachedVM
} else {
vm = try get(name: normalizedName, storage: actualLocation)
@@ -1393,7 +1412,10 @@ final class LumeController {
networkMode: networkMode,
clipboard: clipboard,
vncPolicy: vncPolicy)
- Logger.info("VM started successfully", metadata: ["name": normalizedName])
+ // `run` returns once the guest has stopped, including when it shut
+ // itself down, so the VM no longer runs in this process.
+ SharedVM.shared.removeVM(name: normalizedName, ifSame: vm)
+ Logger.info("VM run ended", metadata: ["name": normalizedName])
} catch {
SharedVM.shared.removeVM(name: normalizedName)
Logger.error("Failed to run VM", metadata: ["error": error.localizedDescription])
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 04d6b44e2c..1baee6e95e 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -1136,7 +1136,7 @@ extension Server {
vncPolicy: vncPolicy,
telemetryTransport: .http
)
- Logger.info("VM started successfully in background task", metadata: ["name": name])
+ Logger.info("VM run ended in background task", metadata: ["name": name])
} catch {
Logger.error(
"Failed to start VM in background task",
diff --git a/libs/lume/tests/GuestStopStatusTests.swift b/libs/lume/tests/GuestStopStatusTests.swift
new file mode 100644
index 0000000000..c0cf84a208
--- /dev/null
+++ b/libs/lume/tests/GuestStopStatusTests.swift
@@ -0,0 +1,111 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+@MainActor
+private final class CapturingVMFactory: VMFactory {
+ private(set) var vms: [VM] = []
+ private(set) var services: [MockVMVirtualizationService] = []
+
+ func createVM(vmDirContext: VMDirContext, imageLoader: ImageLoader?) throws -> VM {
+ let vm = MockVM(
+ vmDirContext: vmDirContext,
+ virtualizationServiceFactory: { [unowned self] _ in
+ let service = MockVMVirtualizationService()
+ self.services.append(service)
+ return service
+ },
+ vncServiceFactory: { MockVNCService(vmDirectory: $0) }
+ )
+ vms.append(vm)
+ return vm
+ }
+}
+
+/// A controller and a throwaway storage directory holding one stopped Linux
+/// VM. The tests address the VM by that directory path, so they never read or
+/// change the user's Lume configuration.
+@MainActor
+private func withGuestStopFixture(
+ _ body: (LumeController, CapturingVMFactory, String, String) async throws -> Void
+) async throws {
+ 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 = CapturingVMFactory()
+ 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: "linux", cpuCount: 1, memorySize: 1024, diskSize: 1024, display: "1024x768")
+ config.setMacAddress("00:11:22:33:44:57")
+ try vmDir.saveConfig(config)
+
+ defer { SharedVM.shared.removeVM(name: name) }
+ try await body(controller, factory, name, storage.path)
+}
+
+@MainActor
+@Test("A VM whose guest stops by itself reports stopped and deletes on the first request (#4704)")
+func guestInitiatedStopReportsStopped() async throws {
+ try await withGuestStopFixture { controller, factory, name, storage in
+ // `lume serve` runs the VM the same way: runVM in a task of its own.
+ let run = Task { @MainActor in
+ try await controller.runVM(
+ name: name, noDisplay: true, storage: storage, 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)
+
+ // Control: a running guest is reported running.
+ #expect(try controller.getDetails(name: name, storage: storage).status == "running")
+
+ // The guest powers itself off; nothing calls stop.
+ service.simulateGuestStop()
+ try await run.value
+
+ #expect(try controller.getDetails(name: name, storage: storage).status == "stopped")
+ #expect(try controller.list(storage: storage).first { $0.name == name }?.status == "stopped")
+ #expect(SharedVM.shared.getVM(name: name) == nil)
+
+ try await controller.delete(name: name, storage: storage)
+ #expect(throws: (any Error).self) { try controller.getDetails(name: name, storage: storage) }
+ }
+}
+
+@MainActor
+@Test("A cached VM whose guest is not running is not reported running (#4704)")
+func staleCachedVMIsNotReportedRunning() async throws {
+ try await withGuestStopFixture { controller, factory, name, storage in
+ // A run that ended without its cache entry being cleared.
+ let run = Task { @MainActor in
+ try await controller.runVM(
+ name: name, noDisplay: true, storage: storage, 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)
+ let vm = try #require(factory.vms.first)
+ service.simulateGuestStop()
+ try await run.value
+ SharedVM.shared.setVM(name: name, vm: vm)
+
+ #expect(try controller.getDetails(name: name, storage: storage).status == "stopped")
+ #expect(SharedVM.shared.getVM(name: name) == nil)
+ }
+}