Skip to content

Commit 2a6a8fd

Browse files
committed
test(swift): preserve queued websocket frames
1 parent b8b878e commit 2a6a8fd

1 file changed

Lines changed: 62 additions & 59 deletions

File tree

‎apps/shared/OpenClawKit/Tests/OpenClawKitTests/GatewayNodeSessionTests.swift‎

Lines changed: 62 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -196,13 +196,16 @@ private final class FirstCancelGate: @unchecked Sendable {
196196
}
197197

198198
private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Sendable {
199+
private typealias ReceiveResult = Result<URLSessionWebSocketTask.Message, Error>
200+
199201
private let lock = NSLock()
200202
private let helloAuth: [String: Any]?
201203
private let helloMethods: [String]
202204
private let helloSessionDefaults: [String: Any]?
203205
private let helloDelayNanoseconds: UInt64
204206
private let connectError: [String: Any]?
205207
private let protocolFeaturesError: [String: Any]?
208+
private let protocolFeaturesAutoResponse: Bool
206209
private let protocolFeaturesResponseDelay: Duration
207210
private let protocolFeaturesPostResponseInvoke: Bool
208211
private let cancelGate: FirstCancelGate?
@@ -213,8 +216,8 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
213216
private var sentRequestMethods: [String] = []
214217
private var sentRequestPayloads: [[String: Any]] = []
215218
private var receivePhase = 0
216-
private var pendingReceiveHandler:
217-
(@Sendable (Result<URLSessionWebSocketTask.Message, Error>) -> Void)?
219+
private var pendingReceiveHandler: (@Sendable (ReceiveResult) -> Void)?
220+
private var pendingInboundFrames: [ReceiveResult] = []
218221

219222
init(
220223
helloAuth: [String: Any]? = nil,
@@ -223,6 +226,7 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
223226
helloDelayNanoseconds: UInt64 = 0,
224227
connectError: [String: Any]? = nil,
225228
protocolFeaturesError: [String: Any]? = nil,
229+
protocolFeaturesAutoResponse: Bool = true,
226230
protocolFeaturesResponseDelay: Duration = .zero,
227231
protocolFeaturesPostResponseInvoke: Bool = false,
228232
cancelGate: FirstCancelGate? = nil)
@@ -233,6 +237,7 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
233237
self.helloDelayNanoseconds = helloDelayNanoseconds
234238
self.connectError = connectError
235239
self.protocolFeaturesError = protocolFeaturesError
240+
self.protocolFeaturesAutoResponse = protocolFeaturesAutoResponse
236241
self.protocolFeaturesResponseDelay = protocolFeaturesResponseDelay
237242
self.protocolFeaturesPostResponseInvoke = protocolFeaturesPostResponseInvoke
238243
self.cancelGate = cancelGate
@@ -276,31 +281,22 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
276281
self.sentRequestMethods.append(method)
277282
self.sentRequestPayloads.append(obj)
278283
}
279-
if method == "node.protocolFeatures.update", let id = obj["id"] as? String {
284+
if method == "node.protocolFeatures.update",
285+
self.protocolFeaturesAutoResponse,
286+
let id = obj["id"] as? String
287+
{
280288
Task { [weak self] in
281289
guard let self else { return }
282290
try? await Task.sleep(for: self.protocolFeaturesResponseDelay)
283-
for _ in 0..<100 {
284-
if self.hasPendingReceiveHandler() {
285-
break
286-
}
287-
try? await Task.sleep(for: .milliseconds(1))
288-
}
289291
if let protocolFeaturesError = self.protocolFeaturesError {
290292
self.emitError(id: id, error: protocolFeaturesError)
291293
} else {
292294
self.emitResponse(id: id, payload: ["ok": true])
293295
}
294296
if self.protocolFeaturesPostResponseInvoke {
295-
for _ in 0..<100 {
296-
if self.hasPendingReceiveHandler() {
297-
self.emitInvokeRequest(
298-
id: "post-negotiation",
299-
command: "mcp.tools.call.v1")
300-
break
301-
}
302-
try? await Task.sleep(for: .milliseconds(1))
303-
}
297+
self.emitInvokeRequest(
298+
id: "post-negotiation",
299+
command: "mcp.tools.call.v1")
304300
}
305301
}
306302
}
@@ -381,19 +377,21 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
381377
func receive(
382378
completionHandler: @escaping @Sendable (Result<URLSessionWebSocketTask.Message, Error>) -> Void)
383379
{
384-
self.lock.withLock { self.pendingReceiveHandler = completionHandler }
380+
let queued = self.lock.withLock { () -> ReceiveResult? in
381+
guard !self.pendingInboundFrames.isEmpty else {
382+
self.pendingReceiveHandler = completionHandler
383+
return nil
384+
}
385+
return self.pendingInboundFrames.removeFirst()
386+
}
387+
if let queued {
388+
completionHandler(queued)
389+
}
385390
}
386391

387392
func emitReceiveFailure() {
388-
let handler = self.lock.withLock { () -> (@Sendable (Result<
389-
URLSessionWebSocketTask.Message,
390-
Error,
391-
>) -> Void)? in
392-
self._state = .canceling
393-
defer { self.pendingReceiveHandler = nil }
394-
return self.pendingReceiveHandler
395-
}
396-
handler?(Result<URLSessionWebSocketTask.Message, Error>.failure(URLError(.networkConnectionLost)))
393+
self.lock.withLock { self._state = .canceling }
394+
self.emitInbound(.failure(URLError(.networkConnectionLost)))
397395
}
398396

399397
func emitInvokeRequest(
@@ -405,14 +403,7 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
405403
sessionKey: String? = nil,
406404
timeoutMs: Int? = nil)
407405
{
408-
let handler = self.lock.withLock { () -> (@Sendable (Result<
409-
URLSessionWebSocketTask.Message,
410-
Error,
411-
>) -> Void)? in
412-
defer { self.pendingReceiveHandler = nil }
413-
return self.pendingReceiveHandler
414-
}
415-
handler?(.success(.data(Self.invokeRequestData(
406+
self.emitInbound(.success(.data(Self.invokeRequestData(
416407
id: id,
417408
command: command,
418409
paramsJSON: paramsJSON,
@@ -423,39 +414,39 @@ private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Senda
423414
}
424415

425416
func emitResponse(id: String, payload: [String: Any]) {
426-
let handler = self.lock.withLock { () -> (@Sendable (Result<
427-
URLSessionWebSocketTask.Message,
428-
Error,
429-
>) -> Void)? in
430-
defer { self.pendingReceiveHandler = nil }
431-
return self.pendingReceiveHandler
432-
}
433417
let frame: [String: Any] = [
434418
"type": "res",
435419
"id": id,
436420
"ok": true,
437421
"payload": payload,
438422
]
439423
let data = (try? JSONSerialization.data(withJSONObject: frame)) ?? Data()
440-
handler?(.success(.data(data)))
424+
self.emitInbound(.success(.data(data)))
441425
}
442426

443427
func emitError(id: String, error: [String: Any]) {
444-
let handler = self.lock.withLock { () -> (@Sendable (Result<
445-
URLSessionWebSocketTask.Message,
446-
Error,
447-
>) -> Void)? in
448-
defer { self.pendingReceiveHandler = nil }
449-
return self.pendingReceiveHandler
450-
}
451428
let frame: [String: Any] = [
452429
"type": "res",
453430
"id": id,
454431
"ok": false,
455432
"error": error,
456433
]
457434
let data = (try? JSONSerialization.data(withJSONObject: frame)) ?? Data()
458-
handler?(.success(.data(data)))
435+
self.emitInbound(.success(.data(data)))
436+
}
437+
438+
private func emitInbound(_ result: ReceiveResult) {
439+
let handler = self.lock.withLock { () -> (@Sendable (ReceiveResult) -> Void)? in
440+
guard let handler = self.pendingReceiveHandler else {
441+
// URLSession preserves socket frame order even while the actor is
442+
// processing one callback and has not registered the next receive.
443+
self.pendingInboundFrames.append(result)
444+
return nil
445+
}
446+
self.pendingReceiveHandler = nil
447+
return handler
448+
}
449+
handler?(result)
459450
}
460451

461452
private static func connectChallengeData(nonce: String) -> Data {
@@ -577,6 +568,7 @@ private final class FakeGatewayWebSocketSession: WebSocketSessioning, GatewayTLS
577568
private let helloDelayNanoseconds: UInt64
578569
private let connectError: [String: Any]?
579570
private let protocolFeaturesError: [String: Any]?
571+
private let protocolFeaturesAutoResponse: Bool
580572
private let protocolFeaturesResponseDelay: Duration
581573
private let protocolFeaturesPostResponseInvoke: Bool
582574
private let cancelGate: FirstCancelGate?
@@ -592,6 +584,7 @@ private final class FakeGatewayWebSocketSession: WebSocketSessioning, GatewayTLS
592584
helloDelayNanoseconds: UInt64 = 0,
593585
connectError: [String: Any]? = nil,
594586
protocolFeaturesError: [String: Any]? = nil,
587+
protocolFeaturesAutoResponse: Bool = true,
595588
protocolFeaturesResponseDelay: Duration = .zero,
596589
protocolFeaturesPostResponseInvoke: Bool = false,
597590
cancelGate: FirstCancelGate? = nil,
@@ -603,6 +596,7 @@ private final class FakeGatewayWebSocketSession: WebSocketSessioning, GatewayTLS
603596
self.helloDelayNanoseconds = helloDelayNanoseconds
604597
self.connectError = connectError
605598
self.protocolFeaturesError = protocolFeaturesError
599+
self.protocolFeaturesAutoResponse = protocolFeaturesAutoResponse
606600
self.protocolFeaturesResponseDelay = protocolFeaturesResponseDelay
607601
self.protocolFeaturesPostResponseInvoke = protocolFeaturesPostResponseInvoke
608602
self.cancelGate = cancelGate
@@ -636,6 +630,7 @@ private final class FakeGatewayWebSocketSession: WebSocketSessioning, GatewayTLS
636630
helloDelayNanoseconds: self.helloDelayNanoseconds,
637631
connectError: self.connectError,
638632
protocolFeaturesError: self.protocolFeaturesError,
633+
protocolFeaturesAutoResponse: self.protocolFeaturesAutoResponse,
639634
protocolFeaturesResponseDelay: self.protocolFeaturesResponseDelay,
640635
protocolFeaturesPostResponseInvoke: self.protocolFeaturesPostResponseInvoke,
641636
cancelGate: self.cancelGate)
@@ -920,7 +915,9 @@ struct GatewayNodeSessionTests {
920915

921916
@Test func `canvas surface refresh is shared across callers with different timeouts`() async throws {
922917
let expectedFingerprint = String(repeating: "ab", count: 32)
923-
let session = FakeGatewayWebSocketSession(effectiveTLSFingerprintSHA256: expectedFingerprint)
918+
let session = FakeGatewayWebSocketSession(
919+
protocolFeaturesAutoResponse: false,
920+
effectiveTLSFingerprintSHA256: expectedFingerprint)
924921
let gateway = GatewayNodeSession()
925922
let options = nodeConnectOptions(caps: ["canvas"], clientId: "openclaw-macos", clientDisplayName: "macOS Test")
926923

@@ -929,14 +926,20 @@ struct GatewayNodeSessionTests {
929926
async let first = gateway.refreshCanvasHostUrl(replacing: nil)
930927
async let second = gateway.refreshCanvasHostUrl(timeoutSeconds: 1)
931928
async let third = gateway.refreshPluginSurfaceUrl(surface: "canvas", timeoutSeconds: 2)
932-
try await waitUntil("single surface refresh sent") {
933-
session.latestTask()?.sentRequestCount(method: "node.pluginSurface.refresh") == 1
929+
try await waitUntil("protocol feature and surface refresh sent") {
930+
guard let task = session.latestTask() else { return false }
931+
return task.sentRequestCount(method: "node.protocolFeatures.update") == 1 &&
932+
task.sentRequestCount(method: "node.pluginSurface.refresh") == 1
934933
}
935934
let task = try #require(session.latestTask())
936-
let request = try #require(task.sentRequests(method: "node.pluginSurface.refresh").first)
937-
let requestID = try #require(request["id"] as? String)
938-
task.emitResponse(
939-
id: requestID,
935+
let featureRequest = try #require(task.sentRequests(method: "node.protocolFeatures.update").first)
936+
let surfaceRequest = try #require(task.sentRequests(method: "node.pluginSurface.refresh").first)
937+
938+
try task.emitResponse(
939+
id: #require(featureRequest["id"] as? String),
940+
payload: ["ok": true])
941+
try task.emitResponse(
942+
id: #require(surfaceRequest["id"] as? String),
940943
payload: [
941944
"surface": "canvas",
942945
"pluginSurfaceUrls": [

0 commit comments

Comments
 (0)