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): stop a VM in lume serve without ending the server (#4662)

Francesco Bonacci25f63eea951c
diff --git a/libs/lume/src/Utils/LumeServeProcess.swift b/libs/lume/src/Utils/LumeServeProcess.swift
new file mode 100644
index 0000000000..cc72de4375
--- /dev/null
+++ b/libs/lume/src/Utils/LumeServeProcess.swift
@@ -0,0 +1,76 @@
+import Darwin
+import Foundation
+
+/// Recognizes a `lume serve` process, which can host many VMs at once.
+///
+/// `lume stop` signals the process holding a VM's run lock. When that process
+/// is a `lume serve` (the API server Cua and other clients start VMs through),
+/// a signal would end the server and every VM it hosts, so `stop` asks the
+/// server to stop the one VM instead.
+enum LumeServeProcess {
+ static let defaultPort: UInt16 = 7777
+
+ /// The port `pid` serves the Lume API on, or nil when `pid` is not a
+ /// `lume serve` process (a detached `lume run`, say) or cannot be read.
+ static func apiPort(ofProcess pid: pid_t) -> UInt16? {
+ guard let arguments = arguments(ofProcess: pid) else { return nil }
+ return apiPort(fromArguments: arguments)
+ }
+
+ /// The API port in a `lume serve` command line (`argv`, program first),
+ /// or nil when the command is not `serve`.
+ static func apiPort(fromArguments arguments: [String]) -> UInt16? {
+ guard arguments.count >= 2, arguments[1] == "serve" else { return nil }
+ var port = defaultPort
+ var index = 2
+ while index < arguments.count {
+ let argument = arguments[index]
+ if argument == "--mcp" { return nil } // stdio transport: no HTTP API
+ if argument == "--port", index + 1 < arguments.count {
+ guard let value = UInt16(arguments[index + 1]) else { return nil }
+ port = value
+ index += 2
+ continue
+ }
+ if argument.hasPrefix("--port=") {
+ guard let value = UInt16(argument.dropFirst("--port=".count)) else { return nil }
+ port = value
+ }
+ index += 1
+ }
+ return port
+ }
+
+ /// `pid`'s command line from `KERN_PROCARGS2`.
+ static func arguments(ofProcess pid: pid_t) -> [String]? {
+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
+ var size = 0
+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > MemoryLayout<Int32>.size else {
+ return nil
+ }
+ var buffer = [UInt8](repeating: 0, count: size)
+ guard sysctl(&mib, 3, &buffer, &size, nil, 0) == 0 else { return nil }
+ return parseProcArgs(Array(buffer.prefix(size)))
+ }
+
+ /// Splits a `KERN_PROCARGS2` buffer: `argc`, the executable path, padding
+ /// NULs, then `argc` NUL-terminated arguments.
+ static func parseProcArgs(_ buffer: [UInt8]) -> [String]? {
+ let countSize = MemoryLayout<Int32>.size
+ guard buffer.count > countSize else { return nil }
+ let argc = buffer.prefix(countSize).withUnsafeBytes { Int($0.loadUnaligned(as: Int32.self)) }
+ guard argc > 0 else { return nil }
+ var index = countSize
+ // Skip the executable path and the NULs after it.
+ while index < buffer.count, buffer[index] != 0 { index += 1 }
+ while index < buffer.count, buffer[index] == 0 { index += 1 }
+ var arguments: [String] = []
+ while arguments.count < argc, index < buffer.count {
+ let start = index
+ while index < buffer.count, buffer[index] != 0 { index += 1 }
+ arguments.append(String(decoding: buffer[start..<index], as: UTF8.self))
+ index += 1
+ }
+ return arguments.count == argc ? arguments : nil
+ }
+}
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index e7d6f77a85..352b0e1e81 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -866,6 +866,13 @@ class VM {
"Found process \(pid) holding lock on config file",
metadata: ["name": vmDirContext.name])
+ // A `lume serve` may host other VMs too: a signal would end the server
+ // and all of them. Ask it to stop this one.
+ if let port = LumeServeProcess.apiPort(ofProcess: pid) {
+ try await stopThroughServer(pid: pid, port: port, force: force, timeout: timeout)
+ return
+ }
+
if force {
Logger.info(
"Force stop requested; powering off process \(pid) immediately",
@@ -901,6 +908,49 @@ class VM {
try await forcePowerOff(pid: pid)
}
+ /// Stops this VM through the `lume serve` (process `pid`, API on `port`)
+ /// that runs it, leaving the server and its other VMs running.
+ @MainActor
+ private func stopThroughServer(
+ pid: pid_t, port: UInt16, force: Bool, timeout: TimeInterval
+ ) async throws {
+ Logger.info(
+ "VM runs in lume serve; asking the server to stop it",
+ metadata: ["name": vmDirContext.name, "pid": "\(pid)", "port": "\(port)"])
+ let name =
+ vmDirContext.name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
+ ?? vmDirContext.name
+ guard let url = URL(string: "http://127.0.0.1:\(port)/lume/vms/\(name)/stop") else {
+ throw VMError.internalError("Invalid lume serve URL for port \(port)")
+ }
+ var body: [String: Any] = ["force": force, "timeout": timeout]
+ if let storage = vmDirContext.storage { body["storage"] = storage }
+ var request = URLRequest(url: url, timeoutInterval: max(timeout, 0) + 30)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+ let data: Data
+ let response: URLResponse
+ do {
+ (data, response) = try await URLSession.shared.data(for: request)
+ } catch {
+ // Never fall back to signalling the server: that is what ends
+ // every VM it hosts.
+ throw VMError.internalError(
+ "VM '\(vmDirContext.name)' runs in lume serve (process \(pid)), which did not answer on port \(port): \(error.localizedDescription)"
+ )
+ }
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard (200..<300).contains(status) else {
+ let detail = String(decoding: data, as: UTF8.self)
+ throw VMError.internalError(
+ "lume serve (process \(pid)) could not stop VM '\(vmDirContext.name)' (HTTP \(status)): \(detail)"
+ )
+ }
+ finalizeCrossProcessStop()
+ Logger.info("VM stopped through lume serve", metadata: ["name": vmDirContext.name])
+ }
+
/// Polls until `pid` is no longer signalable or `timeout` elapses.
/// Returns `true` if the process exited within the budget.
@MainActor
diff --git a/libs/lume/tests/LumeServeProcessTests.swift b/libs/lume/tests/LumeServeProcessTests.swift
new file mode 100644
index 0000000000..a088fd573a
--- /dev/null
+++ b/libs/lume/tests/LumeServeProcessTests.swift
@@ -0,0 +1,43 @@
+import Darwin
+import Foundation
+import Testing
+
+@testable import lume
+
+@Test("A lume serve command line yields its API port")
+func serveCommandLinesYieldThePort() {
+ #expect(LumeServeProcess.apiPort(fromArguments: ["/usr/local/bin/lume", "serve"]) == 7777)
+ #expect(
+ LumeServeProcess.apiPort(fromArguments: ["lume", "serve", "--port", "7778"]) == 7778)
+ #expect(LumeServeProcess.apiPort(fromArguments: ["lume", "serve", "--port=9000"]) == 9000)
+}
+
+@Test("Other lume commands are not a server")
+func otherCommandsAreNotAServer() {
+ #expect(
+ LumeServeProcess.apiPort(fromArguments: ["lume", "run", "vm", "--no-display"]) == nil)
+ #expect(LumeServeProcess.apiPort(fromArguments: ["lume"]) == nil)
+ // The MCP server talks over stdio and has no HTTP API to call.
+ #expect(LumeServeProcess.apiPort(fromArguments: ["lume", "serve", "--mcp"]) == nil)
+ #expect(LumeServeProcess.apiPort(fromArguments: ["lume", "serve", "--port", "x"]) == nil)
+}
+
+@Test("KERN_PROCARGS2 buffers split into arguments")
+func procArgsBuffersSplit() {
+ var argc = Int32(4)
+ var buffer = withUnsafeBytes(of: &argc) { Array($0) }
+ buffer += Array("/opt/lume/lume".utf8) + [0, 0, 0, 0]
+ for argument in ["lume", "serve", "--port", "7777"] {
+ buffer += Array(argument.utf8) + [0]
+ }
+ buffer += Array("HOME=/Users/x".utf8) + [0]
+ #expect(
+ LumeServeProcess.parseProcArgs(buffer) == ["lume", "serve", "--port", "7777"])
+}
+
+@Test("This test process's own command line is readable and not a server")
+func ownCommandLineIsReadable() {
+ let arguments = LumeServeProcess.arguments(ofProcess: getpid())
+ #expect(arguments?.isEmpty == false)
+ #expect(LumeServeProcess.apiPort(ofProcess: getpid()) == nil)
+}