From 629194015d511ee1121c403381e4aaae9e110580 Mon Sep 17 00:00:00 2001 From: PJ Date: Sun, 7 Jun 2026 15:59:15 +0530 Subject: [PATCH] refactor(companion): tidy snapshot serialization --- companion/Sources/Server.swift | 20 +++++++++++++------- companion/Sources/Snapshot.swift | 5 +---- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/companion/Sources/Server.swift b/companion/Sources/Server.swift index d623f28..0291e6f 100644 --- a/companion/Sources/Server.swift +++ b/companion/Sources/Server.swift @@ -10,6 +10,9 @@ final class Server { private let port: NWEndpoint.Port private let listener: NWListener private let queue = DispatchQueue(label: "dev.sanderling.companion.server") + // Requests are handled off the network queue so blocking automation work + // (snapshot, gesture synthesis) never stalls accept and receive. + private let work = DispatchQueue(label: "dev.sanderling.companion.work") // The bundle identifier of the most recently snapshotted app, used as the // default target for typeText when no explicit bundleId is supplied. @@ -58,13 +61,16 @@ final class Server { private func handleLine(_ lineData: Data, on connection: NWConnection) { guard !lineData.isEmpty else { return } - let requestId = (try? JSONSerialization.jsonObject(with: lineData)) - .flatMap { ($0 as? [String: Any])?["id"] as? Int } ?? 0 - do { - let response = try dispatch(lineData) - send(response, on: connection) - } catch { - send(["id": requestId, "error": "\(error)"], on: connection) + work.async { [weak self] in + guard let self = self else { return } + let requestId = (try? JSONSerialization.jsonObject(with: lineData)) + .flatMap { ($0 as? [String: Any])?["id"] as? Int } ?? 0 + do { + let response = try self.dispatch(lineData) + self.send(response, on: connection) + } catch { + self.send(["id": requestId, "error": "\(error)"], on: connection) + } } } diff --git a/companion/Sources/Snapshot.swift b/companion/Sources/Snapshot.swift index fc43dbf..f8fbf9c 100644 --- a/companion/Sources/Snapshot.swift +++ b/companion/Sources/Snapshot.swift @@ -31,7 +31,7 @@ enum Snapshot { private static func serialize(_ node: XCUIElementSnapshot) -> [String: Any] { let frame = node.frame - var element: [String: Any] = [ + return [ "type": elementTypeName(node.elementType), "frame": [ "x": Double(frame.origin.x), @@ -44,9 +44,6 @@ enum Snapshot { "AXValue": nullableString(stringifyValue(node.value)), "AXUniqueId": nullableString(node.identifier), ] - // Keep the dictionary keys deterministic for readers; values stay as set. - _ = element - return element } private static func nullableString(_ value: String?) -> Any {