Gateway: discriminated protocol schema + CLI updates
This commit is contained in:
@@ -23,9 +23,9 @@ actor AgentRPC {
|
||||
}
|
||||
|
||||
func start() async throws {
|
||||
if configured { return }
|
||||
await gateway.configure(url: gatewayURL, token: gatewayToken)
|
||||
configured = true
|
||||
if self.configured { return }
|
||||
await self.gateway.configure(url: self.gatewayURL, token: self.gatewayToken)
|
||||
self.configured = true
|
||||
}
|
||||
|
||||
func shutdown() async {
|
||||
@@ -34,10 +34,12 @@ actor AgentRPC {
|
||||
|
||||
func setHeartbeatsEnabled(_ enabled: Bool) async -> Bool {
|
||||
do {
|
||||
_ = try await controlRequest(method: "set-heartbeats", params: ControlRequestParams(raw: ["enabled": AnyHashable(enabled)]))
|
||||
_ = try await self.controlRequest(
|
||||
method: "set-heartbeats",
|
||||
params: ControlRequestParams(raw: ["enabled": AnyHashable(enabled)]))
|
||||
return true
|
||||
} catch {
|
||||
logger.error("setHeartbeatsEnabled failed \(error.localizedDescription, privacy: .public)")
|
||||
self.logger.error("setHeartbeatsEnabled failed \(error.localizedDescription, privacy: .public)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -46,7 +48,8 @@ actor AgentRPC {
|
||||
do {
|
||||
let data = try await controlRequest(method: "status")
|
||||
if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
(obj["ok"] as? Bool) ?? true {
|
||||
(obj["ok"] as? Bool) ?? true
|
||||
{
|
||||
return (true, nil)
|
||||
}
|
||||
return (false, "status error")
|
||||
@@ -71,7 +74,7 @@ actor AgentRPC {
|
||||
"to": AnyHashable(to ?? ""),
|
||||
"idempotencyKey": AnyHashable(UUID().uuidString),
|
||||
]
|
||||
_ = try await controlRequest(method: "agent", params: ControlRequestParams(raw: params))
|
||||
_ = try await self.controlRequest(method: "agent", params: ControlRequestParams(raw: params))
|
||||
return (true, nil, nil)
|
||||
} catch {
|
||||
return (false, nil, error.localizedDescription)
|
||||
@@ -79,8 +82,8 @@ actor AgentRPC {
|
||||
}
|
||||
|
||||
func controlRequest(method: String, params: ControlRequestParams? = nil) async throws -> Data {
|
||||
try await start()
|
||||
let rawParams = params?.raw.reduce(into: [String: Any]()) { $0[$1.key] = $1.value }
|
||||
return try await gateway.request(method: method, params: rawParams)
|
||||
try await self.start()
|
||||
let rawParams = params?.raw.reduce(into: [String: AnyCodable]()) { $0[$1.key] = AnyCodable($1.value) }
|
||||
return try await self.gateway.request(method: method, params: rawParams)
|
||||
}
|
||||
}
|
||||
|
||||
41
apps/macos/Sources/Clawdis/AnyCodable.swift
Normal file
41
apps/macos/Sources/Clawdis/AnyCodable.swift
Normal file
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
|
||||
/// Lightweight `Codable` wrapper that round-trips heterogeneous JSON payloads.
|
||||
/// Marked `@unchecked Sendable` because it can hold reference types.
|
||||
struct AnyCodable: Codable, @unchecked Sendable {
|
||||
let value: Any
|
||||
|
||||
init(_ value: Any) { self.value = value }
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let intVal = try? container.decode(Int.self) { self.value = intVal; return }
|
||||
if let doubleVal = try? container.decode(Double.self) { self.value = doubleVal; return }
|
||||
if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
|
||||
if let stringVal = try? container.decode(String.self) { self.value = stringVal; return }
|
||||
if container.decodeNil() { self.value = NSNull(); return }
|
||||
if let dict = try? container.decode([String: AnyCodable].self) { self.value = dict; return }
|
||||
if let array = try? container.decode([AnyCodable].self) { self.value = array; return }
|
||||
throw DecodingError.dataCorruptedError(
|
||||
in: container,
|
||||
debugDescription: "Unsupported type")
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch self.value {
|
||||
case let intVal as Int: try container.encode(intVal)
|
||||
case let doubleVal as Double: try container.encode(doubleVal)
|
||||
case let boolVal as Bool: try container.encode(boolVal)
|
||||
case let stringVal as String: try container.encode(stringVal)
|
||||
case is NSNull: try container.encodeNil()
|
||||
case let dict as [String: AnyCodable]: try container.encode(dict)
|
||||
case let array as [AnyCodable]: try container.encode(array)
|
||||
default:
|
||||
let context = EncodingError.Context(
|
||||
codingPath: encoder.codingPath,
|
||||
debugDescription: "Unsupported type")
|
||||
throw EncodingError.invalidValue(self.value, context)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,40 +20,6 @@ struct ControlAgentEvent: Codable, Sendable {
|
||||
let data: [String: AnyCodable]
|
||||
}
|
||||
|
||||
struct AnyCodable: Codable, @unchecked Sendable {
|
||||
let value: Any
|
||||
|
||||
init(_ value: Any) { self.value = value }
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let intVal = try? container.decode(Int.self) { self.value = intVal; return }
|
||||
if let doubleVal = try? container.decode(Double.self) { self.value = doubleVal; return }
|
||||
if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
|
||||
if let stringVal = try? container.decode(String.self) { self.value = stringVal; return }
|
||||
if container.decodeNil() { self.value = NSNull(); return }
|
||||
if let dict = try? container.decode([String: AnyCodable].self) { self.value = dict; return }
|
||||
if let array = try? container.decode([AnyCodable].self) { self.value = array; return }
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type")
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch self.value {
|
||||
case let intVal as Int: try container.encode(intVal)
|
||||
case let doubleVal as Double: try container.encode(doubleVal)
|
||||
case let boolVal as Bool: try container.encode(boolVal)
|
||||
case let stringVal as String: try container.encode(stringVal)
|
||||
case is NSNull: try container.encodeNil()
|
||||
case let dict as [String: AnyCodable]: try container.encode(dict)
|
||||
case let array as [AnyCodable]: try container.encode(array)
|
||||
default:
|
||||
let context = EncodingError.Context(codingPath: encoder.codingPath, debugDescription: "Unsupported type")
|
||||
throw EncodingError.invalidValue(self.value, context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ControlChannelError: Error, LocalizedError {
|
||||
case disconnected
|
||||
case badResponse(String)
|
||||
@@ -70,6 +36,11 @@ enum ControlChannelError: Error, LocalizedError {
|
||||
final class ControlChannel: ObservableObject {
|
||||
static let shared = ControlChannel()
|
||||
|
||||
enum Mode {
|
||||
case local
|
||||
case remote(target: String, identity: String)
|
||||
}
|
||||
|
||||
enum ConnectionState: Equatable {
|
||||
case disconnected
|
||||
case connecting
|
||||
@@ -87,29 +58,36 @@ final class ControlChannel: ObservableObject {
|
||||
let effectivePort = port > 0 ? port : 18789
|
||||
return URL(string: "ws://127.0.0.1:\(effectivePort)")!
|
||||
}
|
||||
|
||||
private var gatewayToken: String? {
|
||||
ProcessInfo.processInfo.environment["CLAWDIS_GATEWAY_TOKEN"]
|
||||
}
|
||||
|
||||
private var eventTokens: [NSObjectProtocol] = []
|
||||
|
||||
func configure() async {
|
||||
do {
|
||||
self.state = .connecting
|
||||
await gateway.configure(url: gatewayURL, token: gatewayToken)
|
||||
self.startEventStream()
|
||||
self.state = .connected
|
||||
PresenceReporter.shared.sendImmediate(reason: "connect")
|
||||
} catch {
|
||||
self.state = .degraded(error.localizedDescription)
|
||||
}
|
||||
self.state = .connecting
|
||||
await self.gateway.configure(url: self.gatewayURL, token: self.gatewayToken)
|
||||
self.startEventStream()
|
||||
self.state = .connected
|
||||
PresenceReporter.shared.sendImmediate(reason: "connect")
|
||||
}
|
||||
|
||||
func configure(mode _: Any? = nil) async throws { await self.configure() }
|
||||
func configure(mode: Mode = .local) async throws {
|
||||
switch mode {
|
||||
case .local:
|
||||
await self.configure()
|
||||
case let .remote(target, identity):
|
||||
// Remote mode assumed to have an existing tunnel; placeholders retained for future use.
|
||||
_ = (target, identity)
|
||||
await self.configure()
|
||||
}
|
||||
}
|
||||
|
||||
func health(timeout: TimeInterval? = nil) async throws -> Data {
|
||||
do {
|
||||
let start = Date()
|
||||
var params: [String: AnyHashable]? = nil
|
||||
var params: [String: AnyHashable]?
|
||||
if let timeout {
|
||||
params = ["timeout": AnyHashable(Int(timeout * 1000))]
|
||||
}
|
||||
@@ -126,13 +104,13 @@ final class ControlChannel: ObservableObject {
|
||||
|
||||
func lastHeartbeat() async throws -> ControlHeartbeatEvent? {
|
||||
// Heartbeat removed in new protocol
|
||||
return nil
|
||||
nil
|
||||
}
|
||||
|
||||
func request(method: String, params: [String: AnyHashable]? = nil) async throws -> Data {
|
||||
do {
|
||||
let rawParams = params?.reduce(into: [String: Any]()) { $0[$1.key] = $1.value }
|
||||
let data = try await gateway.request(method: method, params: rawParams)
|
||||
let rawParams = params?.reduce(into: [String: AnyCodable]()) { $0[$1.key] = AnyCodable($1.value) }
|
||||
let data = try await self.gateway.request(method: method, params: rawParams)
|
||||
self.state = .connected
|
||||
return data
|
||||
} catch {
|
||||
@@ -146,14 +124,17 @@ final class ControlChannel: ObservableObject {
|
||||
}
|
||||
|
||||
private func startEventStream() {
|
||||
for tok in eventTokens { NotificationCenter.default.removeObserver(tok) }
|
||||
eventTokens.removeAll()
|
||||
for tok in self.eventTokens {
|
||||
NotificationCenter.default.removeObserver(tok)
|
||||
}
|
||||
self.eventTokens.removeAll()
|
||||
let ev = NotificationCenter.default.addObserver(
|
||||
forName: .gatewayEvent,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { note in
|
||||
guard let obj = note.userInfo as? [String: Any],
|
||||
queue: .main)
|
||||
{ [weak self] @MainActor note in
|
||||
guard let self,
|
||||
let obj = note.userInfo as? [String: Any],
|
||||
let event = obj["event"] as? String else { return }
|
||||
switch event {
|
||||
case "agent":
|
||||
@@ -165,7 +146,12 @@ final class ControlChannel: ObservableObject {
|
||||
let dataDict = payload["data"] as? [String: Any]
|
||||
{
|
||||
let wrapped = dataDict.mapValues { AnyCodable($0) }
|
||||
AgentEventStore.shared.append(ControlAgentEvent(runId: runId, seq: seq, stream: stream, ts: ts, data: wrapped))
|
||||
AgentEventStore.shared.append(ControlAgentEvent(
|
||||
runId: runId,
|
||||
seq: seq,
|
||||
stream: stream,
|
||||
ts: ts,
|
||||
data: wrapped))
|
||||
}
|
||||
case "presence":
|
||||
// InstancesStore listens separately via notification
|
||||
@@ -179,11 +165,11 @@ final class ControlChannel: ObservableObject {
|
||||
let tick = NotificationCenter.default.addObserver(
|
||||
forName: .gatewaySnapshot,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { _ in
|
||||
self.state = .connected
|
||||
queue: .main)
|
||||
{ [weak self] @MainActor _ in
|
||||
self?.state = .connected
|
||||
}
|
||||
eventTokens = [ev, tick]
|
||||
self.eventTokens = [ev, tick]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,15 +32,15 @@ private actor GatewayChannelActor {
|
||||
}
|
||||
|
||||
func connect() async throws {
|
||||
if connected, task?.state == .running { return }
|
||||
task?.cancel(with: .goingAway, reason: nil)
|
||||
task = session.webSocketTask(with: url)
|
||||
task?.resume()
|
||||
try await sendHello()
|
||||
listen()
|
||||
connected = true
|
||||
backoffMs = 500
|
||||
lastSeq = nil
|
||||
if self.connected, self.task?.state == .running { return }
|
||||
self.task?.cancel(with: .goingAway, reason: nil)
|
||||
self.task = self.session.webSocketTask(with: self.url)
|
||||
self.task?.resume()
|
||||
try await self.sendHello()
|
||||
self.listen()
|
||||
self.connected = true
|
||||
self.backoffMs = 500
|
||||
self.lastSeq = nil
|
||||
}
|
||||
|
||||
private func sendHello() async throws {
|
||||
@@ -56,23 +56,22 @@ private actor GatewayChannelActor {
|
||||
"instanceId": Host.current().localizedName ?? UUID().uuidString,
|
||||
],
|
||||
"caps": [],
|
||||
"auth": token != nil ? ["token": token!] : [:],
|
||||
"auth": self.token != nil ? ["token": self.token!] : [:],
|
||||
]
|
||||
let data = try JSONSerialization.data(withJSONObject: hello)
|
||||
try await task?.send(.data(data))
|
||||
try await self.task?.send(.data(data))
|
||||
// wait for hello-ok
|
||||
if let msg = try await task?.receive() {
|
||||
if try await handleHelloResponse(msg) { return }
|
||||
if try await self.handleHelloResponse(msg) { return }
|
||||
}
|
||||
throw NSError(domain: "Gateway", code: 1, userInfo: [NSLocalizedDescriptionKey: "hello failed"])
|
||||
}
|
||||
|
||||
private func handleHelloResponse(_ msg: URLSessionWebSocketTask.Message) async throws -> Bool {
|
||||
let data: Data?
|
||||
switch msg {
|
||||
case .data(let d): data = d
|
||||
case .string(let s): data = s.data(using: .utf8)
|
||||
@unknown default: data = nil
|
||||
let data: Data? = switch msg {
|
||||
case let .data(d): d
|
||||
case let .string(s): s.data(using: .utf8)
|
||||
@unknown default: nil
|
||||
}
|
||||
guard let data else { return false }
|
||||
guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
@@ -85,26 +84,29 @@ private actor GatewayChannelActor {
|
||||
}
|
||||
|
||||
private func listen() {
|
||||
task?.receive { [weak self] result in
|
||||
self.task?.receive { [weak self] result in
|
||||
guard let self else { return }
|
||||
switch result {
|
||||
case .failure(let err):
|
||||
self.logger.error("gateway ws receive failed \(err.localizedDescription, privacy: .public)")
|
||||
self.connected = false
|
||||
self.scheduleReconnect()
|
||||
case .success(let msg):
|
||||
case let .failure(err):
|
||||
Task { await self.handleReceiveFailure(err) }
|
||||
case let .success(msg):
|
||||
Task { await self.handle(msg) }
|
||||
self.listen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleReceiveFailure(_ err: Error) async {
|
||||
self.logger.error("gateway ws receive failed \(err.localizedDescription, privacy: .public)")
|
||||
self.connected = false
|
||||
await self.scheduleReconnect()
|
||||
}
|
||||
|
||||
private func handle(_ msg: URLSessionWebSocketTask.Message) async {
|
||||
let data: Data?
|
||||
switch msg {
|
||||
case .data(let d): data = d
|
||||
case .string(let s): data = s.data(using: .utf8)
|
||||
@unknown default: data = nil
|
||||
let data: Data? = switch msg {
|
||||
case let .data(d): d
|
||||
case let .string(s): s.data(using: .utf8)
|
||||
@unknown default: nil
|
||||
}
|
||||
guard let data else { return }
|
||||
guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
@@ -120,10 +122,9 @@ private actor GatewayChannelActor {
|
||||
NotificationCenter.default.post(
|
||||
name: .gatewaySeqGap,
|
||||
object: nil,
|
||||
userInfo: ["expected": last + 1, "received": seq]
|
||||
)
|
||||
userInfo: ["expected": last + 1, "received": seq])
|
||||
}
|
||||
lastSeq = seq
|
||||
self.lastSeq = seq
|
||||
}
|
||||
NotificationCenter.default.post(name: .gatewayEvent, object: nil, userInfo: obj)
|
||||
case "hello-ok":
|
||||
@@ -133,39 +134,39 @@ private actor GatewayChannelActor {
|
||||
}
|
||||
}
|
||||
|
||||
private func scheduleReconnect() {
|
||||
guard shouldReconnect else { return }
|
||||
let delay = backoffMs / 1000
|
||||
backoffMs = min(backoffMs * 2, 30_000)
|
||||
Task.detached { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
|
||||
guard let self else { return }
|
||||
do {
|
||||
try await self.connect()
|
||||
} catch {
|
||||
self.logger.error("gateway reconnect failed \(error.localizedDescription, privacy: .public)")
|
||||
self.scheduleReconnect()
|
||||
}
|
||||
private func scheduleReconnect() async {
|
||||
guard self.shouldReconnect else { return }
|
||||
let delay = self.backoffMs / 1000
|
||||
self.backoffMs = min(self.backoffMs * 2, 30000)
|
||||
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
|
||||
do {
|
||||
try await self.connect()
|
||||
} catch {
|
||||
self.logger.error("gateway reconnect failed \(error.localizedDescription, privacy: .public)")
|
||||
await self.scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
func request(method: String, params: [String: Any]?) async throws -> Data {
|
||||
try await connect()
|
||||
func request(method: String, params: [String: AnyCodable]?) async throws -> Data {
|
||||
try await self.connect()
|
||||
let id = UUID().uuidString
|
||||
let paramsObject = params?.reduce(into: [String: Any]()) { dict, entry in
|
||||
dict[entry.key] = entry.value.value
|
||||
} ?? [:]
|
||||
let frame: [String: Any] = [
|
||||
"type": "req",
|
||||
"id": id,
|
||||
"method": method,
|
||||
"params": params ?? [:],
|
||||
"params": paramsObject,
|
||||
]
|
||||
let data = try JSONSerialization.data(withJSONObject: frame)
|
||||
let response = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Data, Error>) in
|
||||
pending[id] = cont
|
||||
self.pending[id] = cont
|
||||
Task {
|
||||
do {
|
||||
try await task?.send(.data(data))
|
||||
try await self.task?.send(.data(data))
|
||||
} catch {
|
||||
pending.removeValue(forKey: id)
|
||||
self.pending.removeValue(forKey: id)
|
||||
cont.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
@@ -178,7 +179,7 @@ actor GatewayChannel {
|
||||
private var inner: GatewayChannelActor?
|
||||
|
||||
func configure(url: URL, token: String?) {
|
||||
inner = GatewayChannelActor(url: url, token: token)
|
||||
self.inner = GatewayChannelActor(url: url, token: token)
|
||||
}
|
||||
|
||||
func request(method: String, params: [String: Any]?) async throws -> Data {
|
||||
@@ -188,34 +189,3 @@ actor GatewayChannel {
|
||||
return try await inner.request(method: method, params: params)
|
||||
}
|
||||
}
|
||||
|
||||
struct AnyCodable: Codable {
|
||||
let value: Any
|
||||
init(_ value: Any) { self.value = value }
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if let intVal = try? container.decode(Int.self) { self.value = intVal; return }
|
||||
if let doubleVal = try? container.decode(Double.self) { self.value = doubleVal; return }
|
||||
if let boolVal = try? container.decode(Bool.self) { self.value = boolVal; return }
|
||||
if let stringVal = try? container.decode(String.self) { self.value = stringVal; return }
|
||||
if container.decodeNil() { self.value = NSNull(); return }
|
||||
if let dict = try? container.decode([String: AnyCodable].self) { self.value = dict; return }
|
||||
if let array = try? container.decode([AnyCodable].self) { self.value = array; return }
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type")
|
||||
}
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
switch self.value {
|
||||
case let intVal as Int: try container.encode(intVal)
|
||||
case let doubleVal as Double: try container.encode(doubleVal)
|
||||
case let boolVal as Bool: try container.encode(boolVal)
|
||||
case let stringVal as String: try container.encode(stringVal)
|
||||
case is NSNull: try container.encodeNil()
|
||||
case let dict as [String: AnyCodable]: try container.encode(dict)
|
||||
case let array as [AnyCodable]: try container.encode(array)
|
||||
default:
|
||||
let ctx = EncodingError.Context(codingPath: encoder.codingPath, debugDescription: "Unsupported type")
|
||||
throw EncodingError.invalidValue(self.value, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,18 +54,18 @@ final class InstancesStore: ObservableObject {
|
||||
func stop() {
|
||||
self.task?.cancel()
|
||||
self.task = nil
|
||||
for token in observers {
|
||||
for token in self.observers {
|
||||
NotificationCenter.default.removeObserver(token)
|
||||
}
|
||||
observers.removeAll()
|
||||
self.observers.removeAll()
|
||||
}
|
||||
|
||||
private func observeGatewayEvents() {
|
||||
let ev = NotificationCenter.default.addObserver(
|
||||
forName: .gatewayEvent,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] note in
|
||||
queue: .main)
|
||||
{ [weak self] @MainActor note in
|
||||
guard let self,
|
||||
let obj = note.userInfo as? [String: Any],
|
||||
let event = obj["event"] as? String else { return }
|
||||
@@ -76,23 +76,23 @@ final class InstancesStore: ObservableObject {
|
||||
let gap = NotificationCenter.default.addObserver(
|
||||
forName: .gatewaySeqGap,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
queue: .main)
|
||||
{ [weak self] _ in
|
||||
guard let self else { return }
|
||||
Task { await self.refresh() }
|
||||
}
|
||||
let snap = NotificationCenter.default.addObserver(
|
||||
forName: .gatewaySnapshot,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] note in
|
||||
queue: .main)
|
||||
{ [weak self] @MainActor note in
|
||||
guard let self,
|
||||
let obj = note.userInfo as? [String: Any],
|
||||
let snapshot = obj["snapshot"] as? [String: Any],
|
||||
let presence = snapshot["presence"] else { return }
|
||||
self.decodeAndApplyPresence(presence: presence)
|
||||
}
|
||||
observers = [ev, snap, gap]
|
||||
self.observers = [ev, snap, gap]
|
||||
}
|
||||
|
||||
func refresh() async {
|
||||
@@ -246,11 +246,13 @@ final class InstancesStore: ObservableObject {
|
||||
self.instances.insert(entry, at: 0)
|
||||
}
|
||||
self.lastError = nil
|
||||
self.statusMessage = "Presence unavailable (\(reason ?? "refresh")); showing health probe + local fallback."
|
||||
self.statusMessage =
|
||||
"Presence unavailable (\(reason ?? "refresh")); showing health probe + local fallback."
|
||||
} catch {
|
||||
self.logger.error("instances health probe failed: \(error.localizedDescription, privacy: .public)")
|
||||
if let reason {
|
||||
self.statusMessage = "Presence unavailable (\(reason)), health probe failed: \(error.localizedDescription)"
|
||||
self.statusMessage =
|
||||
"Presence unavailable (\(reason)), health probe failed: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSXPCListenerDelegate
|
||||
RelayProcessManager.shared.setActive(!state.isPaused)
|
||||
}
|
||||
Task {
|
||||
try? await ControlChannel.shared.configure()
|
||||
await ControlChannel.shared.configure()
|
||||
PresenceReporter.shared.start()
|
||||
}
|
||||
Task { await HealthStore.shared.refresh(onDemand: true) }
|
||||
|
||||
@@ -86,19 +86,19 @@ enum RuntimeLocator {
|
||||
static func describeFailure(_ error: RuntimeResolutionError) -> String {
|
||||
switch error {
|
||||
case let .notFound(searchPaths):
|
||||
return [
|
||||
[
|
||||
"clawdis needs Node >=22.0.0 but found no runtime.",
|
||||
"PATH searched: \(searchPaths.joined(separator: ":"))",
|
||||
"Install Node: https://nodejs.org/en/download",
|
||||
].joined(separator: "\n")
|
||||
case let .unsupported(kind, found, required, path, searchPaths):
|
||||
return [
|
||||
[
|
||||
"Found \(kind.rawValue) \(found) at \(path) but need >= \(required).",
|
||||
"PATH searched: \(searchPaths.joined(separator: ":"))",
|
||||
"Upgrade Node and rerun clawdis.",
|
||||
].joined(separator: "\n")
|
||||
case let .versionParse(kind, raw, path, searchPaths):
|
||||
return [
|
||||
[
|
||||
"Could not parse \(kind.rawValue) version output \"\(raw)\" from \(path).",
|
||||
"PATH searched: \(searchPaths.joined(separator: ":"))",
|
||||
"Try reinstalling or pinning a supported version (Node >=22.0.0).",
|
||||
|
||||
@@ -29,8 +29,8 @@ final class VoiceSessionCoordinator: ObservableObject {
|
||||
source: Source,
|
||||
text: String,
|
||||
attributed: NSAttributedString? = nil,
|
||||
forwardEnabled: Bool = false
|
||||
) -> UUID {
|
||||
forwardEnabled: Bool = false) -> UUID
|
||||
{
|
||||
// If a send is in-flight, ignore new sessions to avoid token churn.
|
||||
if VoiceWakeOverlayController.shared.model.isSending {
|
||||
self.logger.info("coordinator drop start while sending")
|
||||
@@ -73,7 +73,9 @@ final class VoiceSessionCoordinator: ObservableObject {
|
||||
autoSendAfter: TimeInterval?)
|
||||
{
|
||||
guard let session, session.token == token else { return }
|
||||
self.logger.info("coordinator finalize token=\(token.uuidString) len=\(text.count) autoSendAfter=\(autoSendAfter ?? -1)")
|
||||
self.logger
|
||||
.info(
|
||||
"coordinator finalize token=\(token.uuidString) len=\(text.count) autoSendAfter=\(autoSendAfter ?? -1)")
|
||||
self.autoSendTask?.cancel(); self.autoSendTask = nil
|
||||
self.session?.text = text
|
||||
self.session?.isFinal = true
|
||||
@@ -108,11 +110,17 @@ final class VoiceSessionCoordinator: ObservableObject {
|
||||
}
|
||||
VoiceWakeOverlayController.shared.sendNow(token: token, sendChime: session.sendChime)
|
||||
Task.detached {
|
||||
_ = await VoiceWakeForwarder.forward(transcript: VoiceWakeForwarder.prefixedTranscript(text), config: forward)
|
||||
_ = await VoiceWakeForwarder.forward(
|
||||
transcript: VoiceWakeForwarder.prefixedTranscript(text),
|
||||
config: forward)
|
||||
}
|
||||
}
|
||||
|
||||
func dismiss(token: UUID, reason: VoiceWakeOverlayController.DismissReason, outcome: VoiceWakeOverlayController.SendOutcome) {
|
||||
func dismiss(
|
||||
token: UUID,
|
||||
reason: VoiceWakeOverlayController.DismissReason,
|
||||
outcome: VoiceWakeOverlayController.SendOutcome)
|
||||
{
|
||||
guard let session, session.token == token else { return }
|
||||
VoiceWakeOverlayController.shared.dismiss(token: token, reason: reason, outcome: outcome)
|
||||
self.clearSession()
|
||||
|
||||
@@ -201,7 +201,9 @@ final class VoiceWakeOverlayController: ObservableObject {
|
||||
await VoiceWakeForwarder.forward(transcript: payload, config: forwardConfig)
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.28) {
|
||||
self.logger.log(level: .info, "overlay sendNow dismiss ticking token=\(self.activeToken?.uuidString ?? "nil")")
|
||||
self.logger.log(
|
||||
level: .info,
|
||||
"overlay sendNow dismiss ticking token=\(self.activeToken?.uuidString ?? "nil")")
|
||||
self.dismiss(token: token, reason: .explicit, outcome: .sent)
|
||||
}
|
||||
}
|
||||
@@ -262,7 +264,13 @@ final class VoiceWakeOverlayController: ObservableObject {
|
||||
return false
|
||||
}
|
||||
if let token, token != active {
|
||||
self.logger.log(level: .info, "overlay drop \(context, privacy: .public) token_mismatch active=\(active.uuidString, privacy: .public) got=\(token.uuidString, privacy: .public)")
|
||||
self.logger.log(
|
||||
level: .info,
|
||||
"""
|
||||
overlay drop \(context, privacy: .public) token_mismatch \
|
||||
active=\(active.uuidString, privacy: .public) \
|
||||
got=\(token.uuidString, privacy: .public)
|
||||
""")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Handshake, request/response, and event frames for the Gateway WebSocket.
|
||||
// MARK: - ClawdisGateway
|
||||
/// Handshake, request/response, and event frames for the Gateway WebSocket.
|
||||
struct ClawdisGateway: Codable {
|
||||
let auth: Auth?
|
||||
let caps: [String]?
|
||||
@@ -33,7 +33,8 @@ struct ClawdisGateway: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case auth, caps, client, locale, maxProtocol, minProtocol, type, userAgent, features, policy
|
||||
case clawdisGatewayProtocol = "protocol"
|
||||
case server, snapshot, expectedProtocol, minClient, reason, id, method, params, error, ok, payload, event, seq, stateVersion
|
||||
case server, snapshot, expectedProtocol, minClient, reason, id, method, params, error, ok, payload, event, seq,
|
||||
stateVersion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,25 +658,29 @@ func newJSONEncoder() -> JSONEncoder {
|
||||
class JSONNull: Codable, Hashable {
|
||||
|
||||
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
|
||||
return true
|
||||
true
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return 0
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(0)
|
||||
}
|
||||
|
||||
public init() {}
|
||||
|
||||
public required init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if !container.decodeNil() {
|
||||
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
|
||||
}
|
||||
let container = try decoder.singleValueContainer()
|
||||
if !container.decodeNil() {
|
||||
throw DecodingError.typeMismatch(
|
||||
JSONNull.self,
|
||||
DecodingError.Context(
|
||||
codingPath: decoder.codingPath,
|
||||
debugDescription: "Wrong type for JSONNull"))
|
||||
}
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encodeNil()
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encodeNil()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -759,7 +764,9 @@ class JSONAny: Codable {
|
||||
throw decodingError(forCodingPath: container.codingPath)
|
||||
}
|
||||
|
||||
static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any {
|
||||
static func decode(
|
||||
from container: inout KeyedDecodingContainer<JSONCodingKey>,
|
||||
forKey key: JSONCodingKey) throws -> Any {
|
||||
if let value = try? container.decode(Bool.self, forKey: key) {
|
||||
return value
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user