Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Pass vphoned's whole error object through vphone.sock

Jacky80f4951385ad
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
index 4ffa0a9b..36118734 100644
--- a/Documents/Guides/launchpad-cli.md
+++ b/Documents/Guides/launchpad-cli.md
@@ -120,7 +120,7 @@ version while a machine is bound to it; rebind or delete those machines first.
| `cfw update-environment <name>` | Redeploy the machine's own bundle's guest resources (vphoned, hook dylibs) into it while stopped, through the helper; nothing else changes |
| `cfw update-kernel <name>` | Re-patch the kernelcache from the machine's current selection and swap it into Preboot, keeping the data (VM off); the data-preserving way to change a kernel patch on an installed VM, no restore tree needed |
| `guest send <name> <json>` | One raw `vphone.sock` request (tap, swipe, key, screenshot) |
-| `guest rpc <name> <method> [params]` | Any vphoned method, see `Research/vphoned_http_api.md` |
+| `guest rpc <name> <method> [params]` | Any vphoned method, see `Research/vphoned_http_api.md`. When vphoned refuses it, the last stderr line is its error object as JSON (`code`, `message`, `results`, `reason` …) |
| `guest unlock <name> [--passcode <code>] [--timeout <seconds>]` | Turn the screen on and unlock the guest, whatever state it was in (vphoned `screen.unlock`). `--passcode` is needed only when the guest has one |
| `exec [--bundle <version>] <vphone-cli arguments>` | Run the default bundle's `vphone-cli`, or that version's, streaming its output. `--bundle` must come first |
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index bbec8705..bec4e035 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -247,6 +247,14 @@ correlate them by `id`. The socket also sends
receive pong frames. JSON WebSocket frames are limited to 1 MiB after
fragment reassembly.
+A command that fails can add fields to the error object (`command_failed`
+from `apps.remove_system` carries `results`; `apfs.snapshot.delete` carries
+`reason`, `errno` and `retryable`). The machine's `vphone.sock` passes them on:
+its `rpc` verb answers `{"ok":true,"result":{…}}`, or `{"ok":false,
+"error":"<message>","guest_error":{…}}` with vphoned's error object
+unchanged in `guest_error`; `error` stays the message string. `vphone-launchpad-cli
+guest rpc` prints that object as JSON on the last stderr line.
+
SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.7.0
owns general device operations. Each HTTP or WebSocket request runs independently
on a concurrent worker queue, so a stalled system service does not block HID,
diff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.md
index 293a0abb..f84ed1ab 100644
--- a/Skills/vphone-guest-control/references/rpc-methods.md
+++ b/Skills/vphone-guest-control/references/rpc-methods.md
@@ -4,8 +4,10 @@
daemon, through the machine's `vphone.sock`. Params are one JSON object (omit
for none). The reply is `{"ok":true,"result":{…}}`. On `ok:false` the CLI exits 1 with
"The machine refused the request. Try again." and puts the guest's own error
-(for example `guest not connected` or `Unknown method: …`) on stderr;
-add `--screen` to also get the small grayscale screen image.
+(for example `guest not connected` or `Unknown method: …`) on stderr. When
+vphoned itself refused, the last stderr line is its whole error object as JSON
+(`code`, `message` and fields such as `results`, `reason`, `errno`,
+`retryable`); `vphone.sock` carries the same object as `guest_error`. Add `--screen` to also get the small grayscale screen image.
The complete catalog, with REST routes and result details, is
`Research/vphoned_http_api.md` ("Method catalog"). This file is the working
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index ae536ee4..be67fb45 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -31,6 +31,15 @@ final class VPhoneGuestControl {
}
}
+ /// vphoned refused an `/v1/rpc` call. `body` is its error object as sent;
+ /// it came from JSON, so it serializes back unchanged.
+ struct GuestRPCFailure: Error, CustomStringConvertible, @unchecked Sendable {
+ let body: [String: Any]
+
+ var message: String { body["message"] as? String ?? "Guest operation failed" }
+ var description: String { message }
+ }
+
struct ClipboardContent {
let text: String?
let types: [String]
@@ -338,6 +347,14 @@ final class VPhoneGuestControl {
return try await call(method, params: params)
}
+ /// `callAfterQueuedInput`, but a refusal from vphoned is thrown as
+ /// `GuestRPCFailure` with its whole error object, for a caller that passes
+ /// it on (`vphone.sock`'s `rpc`).
+ func rpcAfterQueuedInput(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {
+ await orderedInput?.value
+ return try await rpc(method, params: params)
+ }
+
func isDeveloperModeEnabled() async throws -> Bool {
try await call("developer_mode.status")["enabled"] as? Bool ?? false
}
@@ -416,20 +433,30 @@ final class VPhoneGuestControl {
/// Calls one named vphoned operation over `/v1/rpc` and returns its result object.
func call(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {
+ do {
+ return try await rpc(method, params: params)
+ } catch let failure as GuestRPCFailure {
+ if failure.body["code"] as? String == "bootstrap_already_installed" {
+ throw ControlError.bootstrapAlreadyInstalled(failure.message)
+ }
+ if failure.body["code"] as? String == "location_services_off" {
+ throw ControlError.locationServicesOff(failure.message)
+ }
+ throw ControlError.guestError(failure.message)
+ }
+ }
+
+ /// `call`, with vphoned's refusal kept whole as `GuestRPCFailure`: `code`,
+ /// `message` and whatever the command adds (`results`, `reason`, `errno`,
+ /// `retryable` …).
+ private func rpc(_ method: String, params: [String: Any]) async throws -> [String: Any] {
let object: [String: Any] = ["id": UUID().uuidString, "method": method, "params": params]
let body = try JSONSerialization.data(withJSONObject: object)
let response = try await http(method: "POST", path: "/v1/rpc", body: body)
guard let envelope = try JSONSerialization.jsonObject(with: response.body) as? [String: Any]
else { throw ControlError.protocolError("invalid JSON response") }
if let error = envelope["error"] as? [String: Any] {
- let message = error["message"] as? String ?? "Guest operation failed"
- if error["code"] as? String == "bootstrap_already_installed" {
- throw ControlError.bootstrapAlreadyInstalled(message)
- }
- if error["code"] as? String == "location_services_off" {
- throw ControlError.locationServicesOff(message)
- }
- throw ControlError.guestError(message)
+ throw GuestRPCFailure(body: error)
}
guard response.status == 200, let result = envelope["result"] as? [String: Any]
else { throw ControlError.protocolError("missing result (HTTP \(response.status))") }
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
index fa8c81a4..3f86a5d0 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift
@@ -33,7 +33,10 @@ import ImageIO
/// {"t":"type","text":"Hello"} → set guest clipboard
/// {"t":"ping"} → vphoned request/response
/// {"t":"rpc","method":"input.type","params":{"text":"ls\n"}}
-/// → any vphoned method; its result is in `"result"`
+/// → any vphoned method; its result is in `"result"`.
+/// When vphoned refuses it, `"error"` is the message
+/// and `"guest_error"` vphoned's whole error object
+/// (`code`, `message`, `results`, `reason`, `errno` …)
/// {"t":"network"} → the NIC's state, in `"result"`
/// {"t":"network","link":"down"} → unplug (`up` replugs); not saved
///
@@ -241,7 +244,13 @@ class VPhoneHostAutomationServer {
guard let params = (json["params"] ?? [String: Any]()) as? [String: Any] else {
return Self.reply(ok: false, error: "rpc params must be an object")
}
- let result = try await connectedControl().callAfterQueuedInput(method, params: params)
+ let result: [String: Any]
+ do {
+ result = try await connectedControl().rpcAfterQueuedInput(method, params: params)
+ } catch let failure as VPhoneGuestControl.GuestRPCFailure {
+ // `error` stays the message older clients read.
+ return Self.reply(ok: false, error: failure.message, guestError: failure.body)
+ }
let wantRPCScreen = json["screen"] as? Bool ?? false
let image = wantRPCScreen ? await settledCompactScreenshot(delayMs: screenDelay) : nil
return Self.reply(ok: true, image: image, result: result)
@@ -496,11 +505,15 @@ class VPhoneHostAutomationServer {
error: String? = nil,
image: String? = nil,
result: [String: Any]? = nil,
+ guestError: [String: Any]? = nil,
) -> Data {
var dict: [String: Any] = ["ok": ok]
if let result {
dict["result"] = result
}
+ if let guestError {
+ dict["guest_error"] = guestError
+ }
if let path {
dict["path"] = path
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index 9556698f..f926ea7b 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -867,7 +867,14 @@ nonisolated enum VPhoneLaunchpadGuestSocket {
throw VPhoneLaunchpadError("The machine sent a reply that could not be read. Try again.", detail: String(decoding: response.prefix(512), as: UTF8.self))
}
if let dictionary = json as? [String: Any], dictionary["ok"] as? Bool == false {
- throw VPhoneLaunchpadError("The machine refused the request. Try again.", detail: dictionary["error"] as? String)
+ // Newer bundles add vphoned's whole error object to a refused
+ // rpc; its last line is that object as JSON, for scripts.
+ let guestError = (dictionary["guest_error"] as? [String: Any]).flatMap {
+ try? JSONSerialization.data(withJSONObject: $0, options: [.sortedKeys, .withoutEscapingSlashes])
+ }
+ let detail = [dictionary["error"] as? String, guestError.map { String(decoding: $0, as: UTF8.self) }]
+ .compactMap(\.self).joined(separator: "\n")
+ throw VPhoneLaunchpadError("The machine refused the request. Try again.", detail: detail.isEmpty ? nil : detail)
}
return json
}