refactor(macos): extract gateway payload decoding

This commit is contained in:
Peter Steinberger
2025-12-12 22:26:48 +00:00
parent 14e3b34a8e
commit c7bd4b5c1d
3 changed files with 19 additions and 9 deletions

View File

@@ -0,0 +1,16 @@
import ClawdisProtocol
import Foundation
enum GatewayPayloadDecoding {
static func decode<T: Decodable>(_ payload: ClawdisProtocol.AnyCodable, as _: T.Type = T.self) throws -> T {
let data = try JSONEncoder().encode(payload)
return try JSONDecoder().decode(T.self, from: data)
}
static func decodeIfPresent<T: Decodable>(_ payload: ClawdisProtocol.AnyCodable?, as _: T.Type = T.self) throws
-> T?
{
guard let payload else { return nil }
return try decode(payload, as: T.self)
}
}

View File

@@ -92,11 +92,7 @@ final class InstancesStore: ObservableObject {
case .seqGap:
Task { await self.refresh() }
case let .snapshot(hello):
if JSONSerialization.isValidJSONObject(hello.snapshot.presence),
let data = try? JSONEncoder().encode(hello.snapshot.presence)
{
self.decodeAndApplyPresenceData(data)
}
self.applyPresence(hello.snapshot.presence)
default:
break
}
@@ -264,8 +260,7 @@ final class InstancesStore: ObservableObject {
func handlePresenceEventPayload(_ payload: ClawdisProtocol.AnyCodable) {
do {
let payloadData = try JSONEncoder().encode(payload)
let wrapper = try JSONDecoder().decode(PresenceEventPayload.self, from: payloadData)
let wrapper = try GatewayPayloadDecoding.decode(payload, as: PresenceEventPayload.self)
self.applyPresence(wrapper.presence)
} catch {
self.logger.error("presence event decode failed: \(error.localizedDescription, privacy: .public)")

View File

@@ -213,8 +213,7 @@ final class WebChatViewModel: ObservableObject {
private func handleGatewayEvent(_ evt: EventFrame) {
guard evt.event == "chat" else { return }
guard let payload = evt.payload else { return }
guard let data = try? JSONEncoder().encode(payload) else { return }
guard let chat = try? JSONDecoder().decode(ChatEventPayload.self, from: data) else { return }
guard let chat = try? GatewayPayloadDecoding.decode(payload, as: ChatEventPayload.self) else { return }
guard chat.sessionKey == nil || chat.sessionKey == self.sessionKey else { return }
if let runId = chat.runId, !self.pendingRuns.contains(runId) {