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 force/timeout to stop and fix stuck stop for detached VMs (#4235)
Francesco Bonacci14f66c849217
diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdxindex be6ea3ebab..010b5157b5 100644--- a/docs/content/docs/reference/lume/cli-reference.mdx+++ b/docs/content/docs/reference/lume/cli-reference.mdx@@ -155,6 +155,13 @@ Stop a virtual machine| Name | Type | Default | Description || ---- | ---- | ------- | ----------- || `--storage` | String | - | VM storage location to use |+| `--timeout` | Int | 10 | Seconds to wait for a graceful shutdown before forcing power off |++**Flags:**++| Name | Default | Description |+| ---- | ------- | ----------- |+| `--force` | false | Power off the VM immediately instead of attempting a graceful shutdown first |### lume deletediff --git a/libs/lume/src/Commands/Stop.swift b/libs/lume/src/Commands/Stop.swiftindex a7776ae67e..f55554f697 100644--- a/libs/lume/src/Commands/Stop.swift+++ b/libs/lume/src/Commands/Stop.swift@@ -12,15 +12,32 @@ struct Stop: AsyncParsableCommand {@Option(name: .customLong("storage"), help: "VM storage location to use or direct path to VM location")var storage: String?+ @Flag(+ name: .long,+ help: "Power off the VM immediately instead of attempting a graceful shutdown first")+ var force = false++ @Option(+ name: .long,+ help: "Seconds to wait for a graceful shutdown before forcing power off")+ var timeout: Int = 10+init() {}+ func validate() throws {+ if timeout < 0 {+ throw ValidationError("--timeout must be zero or a positive number of seconds.")+ }+ }+@MainActorfunc run() async throws {// Record telemetryTelemetryClient.shared.record(event: TelemetryEvent.stop)let vmController = LumeController()- try await vmController.stopVM(name: name, storage: storage)+ try await vmController.stopVM(+ name: name, storage: storage, force: force, timeout: TimeInterval(timeout))}}diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swiftindex 30ac2e3f20..08a53c2c75 100644--- a/libs/lume/src/LumeController.swift+++ b/libs/lume/src/LumeController.swift@@ -1032,9 +1032,15 @@ final class LumeController {}@MainActor- public func stopVM(name: String, storage: String? = nil) async throws {+ public func stopVM(+ name: String,+ storage: String? = nil,+ force: Bool = false,+ timeout: TimeInterval = VM.defaultStopTimeout+ ) async throws {let normalizedName = normalizeVMName(name: name)- Logger.info("Stopping VM", metadata: ["name": normalizedName])+ Logger.info(+ "Stopping VM", metadata: ["name": normalizedName, "force": "\(force)"])do {// Find the actual location of the VM@@ -1053,7 +1059,7 @@ final class LumeController {vm = try get(name: normalizedName, storage: actualLocation)}- try await vm.stop()+ try await vm.stop(force: force, timeout: timeout)// Remove VM from cache after stoppingSharedVM.shared.removeVM(name: normalizedName)Logger.info("VM stopped successfully", metadata: ["name": normalizedName])diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swiftindex 0530075978..5e9176ad0e 100644--- a/libs/lume/src/Server/Handlers.swift+++ b/libs/lume/src/Server/Handlers.swift@@ -291,19 +291,28 @@ extension Server {}}- func handleStopVM(name: String, storage: String? = nil) async throws -> HTTPResponse {+ func handleStopVM(+ name: String,+ storage: String? = nil,+ force: Bool = false,+ timeout: TimeInterval = VM.defaultStopTimeout+ ) async throws -> HTTPResponse {// Record telemetryTelemetryClient.shared.record(event: TelemetryEvent.apiVMStop)Logger.info(- "Stopping VM", metadata: ["name": name, "storage": String(describing: storage)])+ "Stopping VM",+ metadata: [+ "name": name, "storage": String(describing: storage), "force": "\(force)",+ ])do {Logger.info("Creating VM controller", metadata: ["name": name])let vmController = LumeController()Logger.info("Calling stopVM on controller", metadata: ["name": name])- try await vmController.stopVM(name: name, storage: storage)+ try await vmController.stopVM(+ name: name, storage: storage, force: force, timeout: timeout)Logger.info("VM stopped, waiting 5 seconds for locks to clear", metadata: ["name": name])diff --git a/libs/lume/src/Server/Server.swift b/libs/lume/src/Server/Server.swiftindex 6a5e8126b1..4baeae4b27 100644--- a/libs/lume/src/Server/Server.swift+++ b/libs/lume/src/Server/Server.swift@@ -270,17 +270,27 @@ final class Server: @unchecked Sendable {"Processing stop VM request",metadata: ["method": request.method, "path": request.path])var storage: String? = nil+ var force = false+ var timeout = VM.defaultStopTimeoutif let bodyData = request.body, !bodyData.isEmpty {do {if let json = try JSONSerialization.jsonObject(with: bodyData)- as? [String: Any],- let bodyStorage = json["storage"] as? String+ as? [String: Any]{- storage = bodyStorage+ if let bodyStorage = json["storage"] as? String {+ storage = bodyStorage+ }+ if let bodyForce = json["force"] as? Bool {+ force = bodyForce+ }+ if let bodyTimeout = json["timeout"] as? NSNumber {+ timeout = max(bodyTimeout.doubleValue, 0)+ }}} catch {}}- return try await self.handleStopVM(name: name, storage: storage)+ return try await self.handleStopVM(+ name: name, storage: storage, force: force, timeout: timeout)}),Route(method: "POST", path: "/lume/vms/:name/setup",diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swiftindex c819bc6ef5..9696d48755 100644--- a/libs/lume/src/Utils/CommandDocExtractor.swift+++ b/libs/lume/src/Utils/CommandDocExtractor.swift@@ -393,8 +393,11 @@ enum CommandDocExtractor {],options: [OptionDoc(name: "storage", shortName: nil, help: "VM storage location to use", type: "String", defaultValue: nil, isOptional: true),+ OptionDoc(name: "timeout", shortName: nil, help: "Seconds to wait for a graceful shutdown before forcing power off", type: "Int", defaultValue: "10", isOptional: false),+ ],+ flags: [+ FlagDoc(name: "force", shortName: nil, help: "Power off the VM immediately instead of attempting a graceful shutdown first", defaultValue: false),],- flags: [],subcommands: [])}diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swiftindex 8997093215..909884656b 100644--- a/libs/lume/src/VM/VM.swift+++ b/libs/lume/src/VM/VM.swift@@ -71,6 +71,15 @@ class VM {// their one-shot lock lookup more time than list/get's latency-bound probe.private let runLockProbe: RunLockProbe = LsofRunLockProbe(timeout: 10)+ /// Default number of seconds a graceful `stop` waits for the owning process+ /// to exit before escalating to a forced power-off.+ nonisolated static let defaultStopTimeout: TimeInterval = 10++ /// Signal handlers that let an external `stop` (SIGTERM) or an interactive+ /// Ctrl-C (SIGINT) shut this run down cleanly. Installed only by the process+ /// that actually owns the running VM.+ private var shutdownSignalSources: [DispatchSourceSignal] = []+// MARK: - Initializationinit(@@ -466,6 +475,11 @@ class VM {"error": error.localizedDescription,])}++ // The AppKit run loop swallows SIGINT, so install explicit+ // handlers that turn an external `stop` (SIGTERM) or an+ // interactive Ctrl-C (SIGINT) into a clean shutdown.+ installShutdownSignalHandlers()}// Write VNC config into VM via SSH (background task).@@ -702,10 +716,53 @@ class VM {])}+ /// Installs SIGTERM/SIGINT handlers that request a clean VM shutdown. Only+ /// the process that owns the running VM calls this. Ignoring the default+ /// disposition first lets the dispatch source observe the signal instead of+ /// the process being terminated (or, for SIGINT under AppKit, ignored).+ @MainActor+ private func installShutdownSignalHandlers() {+ guard shutdownSignalSources.isEmpty else { return }+ for signalNumber in [SIGTERM, SIGINT] {+ signal(signalNumber, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: .main)+ source.setEventHandler { [weak self] in+ Task { @MainActor in+ await self?.requestGracefulShutdown()+ }+ }+ source.resume()+ shutdownSignalSources.append(source)+ }+ }++ @MainActor+ private func removeShutdownSignalHandlers() {+ for source in shutdownSignalSources {+ source.cancel()+ }+ shutdownSignalSources.removeAll()+ }++ /// Stops the running VM in response to a shutdown signal. Returning from the+ /// framework's stop lets `run`'s lifecycle wait complete, which drives the+ /// normal session teardown and process exit.+ @MainActor+ private func requestGracefulShutdown() async {+ Logger.info(+ "Received shutdown signal; stopping VM", metadata: ["name": vmDirContext.name])+ guard let service = virtualizationService else { return }+ if service.state == .running || service.state == .paused {+ try? await service.stop()+ }+ }+private func cleanupSession() async {guard !sessionCleanedUp else { return }sessionCleanedUp = true+ removeShutdownSignalHandlers()+// Detach native display before releasing the framework VM.if nativeAttachRegistered {NativeDisplayAttachService.unregister()@@ -733,13 +790,30 @@ class VM {@MainActorfunc stop() async throws {+ try await stop(force: false, timeout: VM.defaultStopTimeout)+ }++ /// Stops the VM.+ ///+ /// When this process owns the running VM, the framework stops it directly.+ /// Otherwise `stop` resolves the process holding the config-file run lock+ /// (typically a detached `lume run`) and signals it: by default it requests+ /// a graceful shutdown and waits up to `timeout` seconds before escalating to+ /// a forced power-off. `force` skips the graceful phase and powers the VM off+ /// immediately.+ @MainActor+ func stop(force: Bool, timeout: TimeInterval) async throws {guard vmDirContext.initialized else {throw VMError.notInitialized(vmDirContext.name)}- Logger.info("Attempting to stop VM", metadata: ["name": vmDirContext.name])+ Logger.info(+ "Attempting to stop VM",+ metadata: ["name": vmDirContext.name, "force": "\(force)"])- // If we have a virtualization service, try to stop it cleanly first+ // If we own the running VM in this process, stop it directly. The+ // framework's stop is an immediate power-off, so it serves both the+ // graceful and forced requests.if let service = virtualizationService {do {Logger.info(@@ -763,36 +837,24 @@ class VM {}}- // Try to open config file to get file descriptor+ // Cross-process stop: another process owns the VM and holds the+ // config-file run lock. Resolve that owner directly from the lock probe.+ // We intentionally do not open the config file ourselves first: doing so+ // would make this process a second holder and pollute the lsof probe.Logger.info(- "Attempting to access config file lock",+ "Resolving process holding the config-file run lock",metadata: ["path": vmDirContext.dir.configPath.path,"name": vmDirContext.name,])- let fileHandle = try? FileHandle(forReadingFrom: vmDirContext.dir.configPath.url)- guard let fileHandle = fileHandle else {- Logger.info(- "Failed to open config file - VM may not be running",- metadata: ["name": vmDirContext.name])-- // Even though we couldn't open the file, try to force unlock anyway- unlockConfigFile()-- throw VMError.notRunning(vmDirContext.name)- }-- // Get the PID of the process holding the lock- Logger.info(- "Finding process holding lock on config file", metadata: ["name": vmDirContext.name])- guard let pid = runLockProbe.lockOwnerPID(ofFileAt: vmDirContext.dir.configPath.path)+ guard let pid = runLockProbe.lockOwnerPID(ofFileAt: vmDirContext.dir.configPath.path),+ pid > 0, pid != getpid()else {- try? fileHandle.close()Logger.info(- "Failed to find process holding lock - VM may not be running",+ "No live process holds the run lock - VM is not running",metadata: ["name": vmDirContext.name])- // Even though we couldn't find the process, try to force unlock+ // Clear any stale advisory lock so a later run can reacquire it.unlockConfigFile()throw VMError.notRunning(vmDirContext.name)@@ -802,70 +864,90 @@ class VM {"Found process \(pid) holding lock on config file",metadata: ["name": vmDirContext.name])- // First try graceful shutdown with SIGINT- if kill(pid, SIGINT) == 0 {- Logger.info("Sent SIGINT to VM process \(pid)", metadata: ["name": vmDirContext.name])+ if force {+ Logger.info(+ "Force stop requested; powering off process \(pid) immediately",+ metadata: ["name": vmDirContext.name])+ try await forcePowerOff(pid: pid)+ return}- // Wait for process to stop with timeout- var attempts = 0- while attempts < 10 {+ // Graceful first: ask the owner to shut down. SIGTERM is honored by the+ // run process (its handler triggers a clean stop); even without a handler+ // its default disposition terminates the process, so unlike SIGINT — which+ // the AppKit run loop swallows — the VM never lingers.+ if kill(pid, SIGTERM) == 0 {Logger.info(- "Waiting for process \(pid) to terminate (attempt \(attempts + 1)/10)",+ "Sent SIGTERM to VM process \(pid) for graceful shutdown",metadata: ["name": vmDirContext.name])- try await Task.sleep(nanoseconds: 1_000_000_000)-- // Check if process still exists- if kill(pid, 0) != 0 {- // Process is gone, do final cleanup- Logger.info("Process \(pid) has terminated", metadata: ["name": vmDirContext.name])- virtualizationService = nil- vncService.stop()- try? fileHandle.close()-- // Force unlock the config file- unlockConfigFile()+ }- Logger.info(- "VM stopped successfully via process termination",- metadata: ["name": vmDirContext.name])- return- }- attempts += 1+ if await waitForProcessExit(pid: pid, timeout: timeout) {+ Logger.info(+ "Process \(pid) exited after graceful shutdown",+ metadata: ["name": vmDirContext.name])+ finalizeCrossProcessStop()+ Logger.info(+ "VM stopped successfully via process termination",+ metadata: ["name": vmDirContext.name])+ return}- // If graceful shutdown failed, force kill the processLogger.info(- "Graceful shutdown failed, forcing termination of process \(pid)",+ "Graceful shutdown did not complete within \(Int(timeout))s; forcing power-off of process \(pid)",metadata: ["name": vmDirContext.name])- if kill(pid, SIGKILL) == 0 {- Logger.info("Sent SIGKILL to process \(pid)", metadata: ["name": vmDirContext.name])+ try await forcePowerOff(pid: pid)+ }- // Wait a moment for the process to be fully killed- try await Task.sleep(nanoseconds: 2_000_000_000)+ /// Polls until `pid` is no longer signalable or `timeout` elapses.+ /// Returns `true` if the process exited within the budget.+ @MainActor+ private func waitForProcessExit(pid: pid_t, timeout: TimeInterval) async -> Bool {+ let deadline = Date().addingTimeInterval(max(timeout, 0))+ repeat {+ if kill(pid, 0) != 0 {+ return true+ }+ try? await Task.sleep(nanoseconds: 500_000_000)+ } while Date() < deadline+ return kill(pid, 0) != 0+ }- // Do final cleanup- virtualizationService = nil- vncService.stop()- try? fileHandle.close()+ /// SIGKILLs `pid`, confirms it is gone, and releases this VM's local state.+ @MainActor+ private func forcePowerOff(pid: pid_t) async throws {+ if kill(pid, 0) != 0 {+ // The owner already exited between resolving it and now.+ finalizeCrossProcessStop()+ Logger.info(+ "Process \(pid) already terminated", metadata: ["name": vmDirContext.name])+ return+ }- // Force unlock the config file- unlockConfigFile()+ _ = kill(pid, SIGKILL)+ Logger.info("Sent SIGKILL to process \(pid)", metadata: ["name": vmDirContext.name])+ if await waitForProcessExit(pid: pid, timeout: 5) {+ finalizeCrossProcessStop()Logger.info("VM forcefully stopped", metadata: ["name": vmDirContext.name])return}- // If we get here, something went very wrong- try? fileHandle.close()+ // SIGKILL cannot be caught, so surviving it means the process is wedged+ // in the kernel. Release our side anyway so the run lock is not orphaned.+ finalizeCrossProcessStop()Logger.error(- "Failed to stop VM - could not terminate process \(pid)",+ "Failed to stop VM - process \(pid) did not terminate",metadata: ["name": vmDirContext.name])+ throw VMError.internalError("Failed to stop VM process \(pid)")+ }- // As a last resort, try to force unlock+ /// Releases the resources a cross-process stop is responsible for cleaning up.+ @MainActor+ private func finalizeCrossProcessStop() {+ virtualizationService = nil+ vncService.stop()unlockConfigFile()-- throw VMError.internalError("Failed to stop VM process")}// Helper method to forcibly clear any locks on the config filediff --git a/libs/lume/tests/Mocks/MockVM.swift b/libs/lume/tests/Mocks/MockVM.swiftindex 31013b8ea4..207e0f8091 100644--- a/libs/lume/tests/Mocks/MockVM.swift+++ b/libs/lume/tests/Mocks/MockVM.swift@@ -39,8 +39,8 @@ class MockVM: VM {)}- override func stop() async throws {+ override func stop(force: Bool, timeout: TimeInterval) async throws {mockIsRunning = false- try await super.stop()+ try await super.stop(force: force, timeout: timeout)}}diff --git a/libs/lume/tests/StopCommandTests.swift b/libs/lume/tests/StopCommandTests.swiftnew file mode 100644index 0000000000..1bd1809c17--- /dev/null+++ b/libs/lume/tests/StopCommandTests.swift@@ -0,0 +1,33 @@+import ArgumentParser+import Foundation+import Testing++@testable import lume++@Test("Stop defaults to a graceful shutdown with the standard timeout")+func stopCommandDefaults() throws {+ let command = try Stop.parse(["test-vm"])++ #expect(command.name == "test-vm")+ #expect(command.force == false)+ #expect(command.timeout == 10)+ #expect(command.storage == nil)+}++@Test("Stop parses force, timeout, and storage")+func stopCommandParsesForceAndTimeout() throws {+ let command = try Stop.parse([+ "test-vm", "--force", "--timeout", "30", "--storage", "external",+ ])++ #expect(command.force)+ #expect(command.timeout == 30)+ #expect(command.storage == "external")+}++@Test("Stop rejects a negative timeout")+func stopCommandRejectsNegativeTimeout() throws {+ #expect(throws: Error.self) {+ _ = try Stop.parse(["test-vm", "--timeout=-1"])+ }+}