Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Tests/TerminalTests/ConnectionTests.swift10// Module : TerminalTests11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteAPI89import ClaudeRemoteModels90import ClaudeRemoteTerminal91import ClaudeRemoteTestSupport92import Foundation93import Testing9495/// Records what the connection feeds, in order.96final class RecordingSink: TerminalOutputSink, @unchecked Sendable {97 enum Entry: Equatable { case reset, bytes(String) }98 private let lock = NSLock()99 private var _log: [Entry] = []100 private var _byteCount = 0101 private var _largestFeed = 0102 func reset() { lock.withLock { _log.append(.reset) } }103 func feed(_ bytes: ArraySlice<UInt8>) {104 lock.withLock {105 _byteCount += bytes.count106 _largestFeed = max(_largestFeed, bytes.count)107 if bytes.count <= 4096 { _log.append(.bytes(String(decoding: bytes, as: UTF8.self))) }108 }109 }110 var log: [Entry] { lock.withLock { _log } }111 var resets: Int { log.filter { $0 == .reset }.count }112 var byteCount: Int { lock.withLock { _byteCount } }113 var largestFeed: Int { lock.withLock { _largestFeed } }114}115116let sessionID = "0b0e7a50-1111-4222-8333-444455556666"117118func sessionJSON(state: String, exitCode: Int? = nil) -> String {119 """120 {"id":"\(sessionID)","projectId":null,"projectName":null,"kind":"shell","title":"zsh","state":"\(state)","cwd":"",121 "pid":4242,"claudeConversationId":null,"pinned":false,"archived":false,"attachedClients":0,122 "exitCode":\(exitCode.map(String.init) ?? "null"),"createdAt":"2026-11-20T02:25:00.000Z","lastActivityAt":null,"endedAt":null,"waitingReason":null}123 """124}125126/// A real `APIClient` on a stub HTTP server and a scripted WebSocket transport.127struct Rig {128 let server = StubServer()129 let sockets = FakeWebSocketTransport()130 let sleeper = ManualSleeper()131 let sink = RecordingSink()132 let client: APIClient133 let connection: TerminalConnection134135 init(autoPong: Bool = false, probeState: String = "RUNNING") async throws {136 client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration, webSocketTransport: sockets)137 await client.setCredential(token: "crn_test", expiresAt: .distantFuture)138 server.on("GET", "/api/v1/sessions/\(sessionID)") { _ in .json(sessionJSON(state: probeState)) }139 if autoPong {140 sockets.onAccept = { ws in141 ws.onClientMessage = { message, ws in142 if case .text(let t) = message, case .ping(let n)? = try? JSONDecoder().decode(TermClientMessage.self, from: Data(t.utf8)) {143 ws.serverSend(text: #"{"t":"pong","n":\#(n)}"#)144 }145 }146 }147 }148 connection = TerminalConnection(client: client, sessionId: sessionID, sink: sink,149 policy: ReconnectPolicy(random: { 0.5 }), sleeper: sleeper)150 }151152 /// Starts and returns the first accepted socket once the connection is open.153 func open(cols: Int = 100, rows: Int = 30) async throws -> FakeWebSocket {154 await connection.start(cols: cols, rows: rows)155 let ws = try #require(await sockets.waitForConnection(count: 1))156 #expect(await waitFor { await connection.state == .open })157 return ws158 }159160 func waitFor(timeout: TimeInterval = 2, _ condition: @Sendable () async -> Bool) async -> Bool {161 let deadline = Date().addingTimeInterval(timeout)162 while Date() < deadline {163 if await condition() { return true }164 try? await Task.sleep(for: .milliseconds(5))165 }166 return await condition()167 }168169 func waitForState(_ state: TerminalConnectionState) async -> Bool {170 await waitFor { await connection.state == state }171 }172173 /// Retry delays requested so far (everything that is not a ping, wake probe or resize debounce).174 var retryDelays: [TimeInterval] {175 sleeper.requested.filter { ![TerminalConnection.pingInterval, TerminalConnection.wakeProbeTimeout, TerminalConnection.resizeDebounce].contains($0) }176 }177178 func waitForRetryDelays(_ count: Int) async -> Bool {179 await waitFor { retryDelays.count >= count }180 }181182 /// Lets already-scheduled work run, to assert that nothing else happens.183 func settle() async { try? await Task.sleep(for: .milliseconds(80)) }184}185186func controls(_ ws: FakeWebSocket) -> [TermClientMessage] {187 ws.sentTexts.compactMap { try? JSONDecoder().decode(TermClientMessage.self, from: Data($0.utf8)) }188}189190func isReconnecting(_ state: TerminalConnectionState, attempt: Int? = nil) -> Bool {191 if case .reconnecting(let a, _) = state { return attempt == nil || a == attempt }192 return false193}194195@Suite("TerminalConnection")196struct ConnectionTests {197 // MARK: Attach198199 @Test func attachRequestCarriesSizeBearerAndClientHeader() async throws {200 let rig = try await Rig()201 _ = try await rig.open(cols: 100, rows: 30)202 let request = try #require(rig.sockets.requests.first)203 let url = try #require(request.url)204 let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))205 #expect(components.scheme == "wss")206 #expect(components.path == "/api/v1/sessions/\(sessionID)/stream")207 #expect(Set(components.queryItems ?? []) == [URLQueryItem(name: "cols", value: "100"), URLQueryItem(name: "rows", value: "30")])208 #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer crn_test")209 #expect(request.value(forHTTPHeaderField: "X-CR-Client") == "native/macos/1.0-test")210 #expect(request.value(forHTTPHeaderField: "Origin") == nil)211 await rig.connection.stop()212 }213214 @Test func attachSizeIsClampedToServerLimits() async throws {215 let rig = try await Rig()216 let ws = try await rig.open(cols: 5, rows: 1000)217 let url = try #require(rig.sockets.requests.first?.url?.absoluteString)218 #expect(url.contains("cols=20") && url.contains("rows=200"))219 #expect(await ws.waitForSent { _ in controls(ws).contains(.resize(cols: 20, rows: 200)) })220 await rig.connection.stop()221 }222223 @Test func openResetsTheSinkThenSendsResizeThenPings() async throws {224 let rig = try await Rig()225 let ws = try await rig.open()226 #expect(rig.sink.log == [.reset])227 #expect(await ws.waitForSent { $0.count >= 2 })228 #expect(controls(ws) == [.resize(cols: 100, rows: 30), .ping(n: 1)])229 #expect(await rig.connection.state == .open)230 #expect(await rig.connection.reconnectCount == 0)231 await rig.connection.stop()232 }233234 @Test func startIsIdempotent() async throws {235 let rig = try await Rig()236 _ = try await rig.open()237 await rig.connection.start(cols: 100, rows: 30)238 await rig.settle()239 #expect(rig.sockets.requests.count == 1)240 await rig.connection.stop()241 }242243 // MARK: Framing244245 @Test func binaryFramesAreFedInOrderAfterTheReset() async throws {246 let rig = try await Rig()247 let ws = try await rig.open()248 ws.serverSend(bytes: "history line\r\n")249 ws.serverSend(.data(Data([0x1B, 0x5B, 0x33, 0x31, 0x6D]))) // ESC[31m250 ws.serverSend(bytes: "é😀")251 #expect(await rig.waitFor { rig.sink.log.count == 4 })252 #expect(rig.sink.log == [.reset, .bytes("history line\r\n"), .bytes("\u{1B}[31m"), .bytes("é😀")])253 await rig.connection.stop()254 }255256 @Test func largeFramesAreFedInBoundedChunks() async throws {257 let rig = try await Rig()258 let ws = try await rig.open()259 ws.serverSend(.data(Data(repeating: 0x41, count: 300_000)))260 #expect(await rig.waitFor { rig.sink.byteCount == 300_000 })261 #expect(rig.sink.largestFeed == TerminalConnection.feedChunkBytes)262 await rig.connection.stop()263 }264265 @Test func inputIsBinaryUTF8ChunkedAt64KiB() async throws {266 let rig = try await Rig()267 let ws = try await rig.open()268 rig.connection.send(text: "ls -la é\r")269 let big = Data(repeating: 0x61, count: 150_000)270 rig.connection.send(big)271 #expect(await ws.waitForSent { _ in ws.sentData.count == 150_000 + 10 })272 let frames = ws.sent.compactMap { if case .data(let d) = $0 { d } else { nil } }273 #expect(frames.first == Data("ls -la é\r".utf8))274 #expect(frames.dropFirst().map(\.count) == [65_536, 65_536, 18_928])275 #expect(ws.sentData == Data("ls -la é\r".utf8) + big)276 await rig.connection.stop()277 }278279 @Test func inputOrderIsPreservedAcrossManyCalls() async throws {280 let rig = try await Rig()281 let ws = try await rig.open()282 for i in 0..<500 { rig.connection.send(text: "\(i),") }283 let expected = (0..<500).map { "\($0)," }.joined()284 #expect(await ws.waitForSent { _ in ws.sentData.count == expected.utf8.count })285 #expect(String(decoding: ws.sentData, as: UTF8.self) == expected)286 await rig.connection.stop()287 }288289 @Test func inputIsDroppedWhileDisconnected() async throws {290 let rig = try await Rig()291 rig.connection.send(text: "before start")292 let first = try await rig.open()293 first.serverClose(code: 1006)294 #expect(await rig.waitFor { isReconnecting(await rig.connection.state) })295 rig.connection.send(text: "typed while offline")296 #expect(await rig.waitForRetryDelays(1))297 rig.sleeper.advance(by: 0.5)298 let second = try #require(await rig.sockets.waitForConnection(count: 2))299 #expect(await rig.waitForState(.open))300 rig.connection.send(text: "after")301 #expect(await second.waitForSent { _ in second.sentData.count == 5 })302 #expect(first.sentData.isEmpty)303 #expect(String(decoding: second.sentData, as: UTF8.self) == "after")304 await rig.connection.stop()305 }306307 // MARK: Resize308309 @Test func resizeIsDebouncedCoalescedAndClamped() async throws {310 let rig = try await Rig()311 let ws = try await rig.open()312 rig.connection.resize(cols: 200, rows: 50)313 rig.connection.resize(cols: 201, rows: 51)314 rig.connection.resize(cols: 1000, rows: 2)315 #expect(await rig.waitFor { rig.sleeper.requested.filter { $0 == TerminalConnection.resizeDebounce }.count == 3 })316 await rig.settle()317 #expect(controls(ws).filter { if case .resize = $0 { true } else { false } }.count == 1, "nothing is sent before the debounce elapses")318 rig.sleeper.advance(by: TerminalConnection.resizeDebounce)319 #expect(await ws.waitForSent { _ in controls(ws).contains(.resize(cols: 500, rows: 5)) })320 await rig.settle()321 #expect(controls(ws).filter { if case .resize = $0 { true } else { false } } == [.resize(cols: 100, rows: 30), .resize(cols: 500, rows: 5)])322 #expect(await rig.connection.cols == 500)323 #expect(await rig.connection.rows == 5)324 await rig.connection.stop()325 }326327 @Test func sizeRequestedWhileDisconnectedIsUsedForTheNextAttach() async throws {328 let rig = try await Rig()329 let first = try await rig.open()330 first.serverClose(code: 1006)331 #expect(await rig.waitForRetryDelays(1))332 rig.connection.resize(cols: 132, rows: 43)333 #expect(await rig.waitFor { rig.sleeper.requested.contains(TerminalConnection.resizeDebounce) })334 rig.sleeper.advance(by: 0.5)335 let second = try #require(await rig.sockets.waitForConnection(count: 2))336 let url = try #require(rig.sockets.requests.last?.url?.absoluteString)337 #expect(url.contains("cols=132") && url.contains("rows=43"))338 #expect(await second.waitForSent { _ in controls(second).contains(.resize(cols: 132, rows: 43)) })339 await rig.connection.stop()340 }341342 // MARK: Ping343344 @Test func pongMeasuresLatency() async throws {345 let rig = try await Rig()346 let ws = try await rig.open()347 #expect(await ws.waitForSent { _ in controls(ws).contains(.ping(n: 1)) })348 rig.sleeper.advance(by: 0.042)349 ws.serverSend(text: #"{"t":"pong","n":1}"#)350 #expect(await rig.waitFor { await rig.connection.latencyMs == 42 })351 await rig.connection.stop()352 #expect(await rig.connection.latencyMs == nil)353 }354355 @Test func pingsEveryFiveSeconds() async throws {356 let rig = try await Rig(autoPong: true)357 let ws = try await rig.open()358 for n in 2...4 {359 #expect(await rig.waitFor { rig.sleeper.pendingCount == 1 })360 rig.sleeper.advance(by: TerminalConnection.pingInterval)361 #expect(await ws.waitForSent { _ in controls(ws).contains(.ping(n: n)) })362 }363 #expect(await rig.connection.state == .open)364 #expect(rig.sockets.requests.count == 1)365 await rig.connection.stop()366 }367368 @Test func missingPongsDropTheSocketAndReconnect() async throws {369 let rig = try await Rig()370 let first = try await rig.open()371 // t = 5, 10, 15: still within the 16 s tolerance, pings go out; t = 20: reconnect.372 for n in 2...4 {373 #expect(await rig.waitFor { rig.sleeper.pendingCount == 1 })374 rig.sleeper.advance(by: TerminalConnection.pingInterval)375 #expect(await first.waitForSent { _ in controls(first).contains(.ping(n: n)) })376 }377 #expect(rig.sockets.requests.count == 1)378 #expect(await rig.waitFor { rig.sleeper.pendingCount == 1 })379 rig.sleeper.advance(by: TerminalConnection.pingInterval)380 let second = try #require(await rig.sockets.waitForConnection(count: 2))381 #expect(await rig.waitForState(.open))382 #expect(first.clientClose?.code == 1000)383 #expect(rig.sink.resets == 2)384 #expect(await rig.connection.reconnectCount == 1)385 #expect(await second.waitForSent { _ in controls(second).first == .resize(cols: 100, rows: 30) })386 await rig.connection.stop()387 }388389 // MARK: Control messages390391 @Test func exitErrorAndReadyMessages() async throws {392 let rig = try await Rig()393 let collector = Task { () -> [TerminalConnectionEvent] in394 var seen: [TerminalConnectionEvent] = []395 for await event in rig.connection.events {396 seen.append(event)397 if event == .state(.ended(exitCode: 3)) { break }398 }399 return seen400 }401 let ws = try await rig.open()402 ws.serverSend(text: #"{"t":"ready","sessionId":"\#(sessionID)","cols":100,"rows":30}"#)403 ws.serverSend(text: #"{"t":"error","code":"runtime_error","message":"pane is gone"}"#)404 ws.serverSend(text: #"{"t":"future-message","x":1}"#)405 ws.serverSend(text: "not json")406 ws.serverSend(text: #"{"t":"exit","code":3}"#)407 #expect(await rig.waitFor { await rig.connection.exitCode == 3 })408 #expect(await rig.connection.detail == "pane is gone")409 #expect(await rig.connection.state == .open, "unknown and malformed control frames are ignored")410 ws.serverClose(code: 4410)411 #expect(await rig.waitForState(.ended(exitCode: 3)))412 let events = await collector.value413 #expect(events.contains(.state(.connecting)) && events.contains(.state(.open)))414 #expect(events.contains(.ready(cols: 100, rows: 30)))415 #expect(events.contains(.exit(code: 3)))416 #expect(events.contains(.detail("pane is gone")))417 await rig.settle()418 #expect(rig.sockets.requests.count == 1, "an ended session is never retried")419 }420421 // MARK: Close codes422423 @Test(arguments: [424 (4401, TerminalConnectionState.unauthorized),425 (4410, TerminalConnectionState.ended(exitCode: nil)),426 (4404, TerminalConnectionState.notFound),427 (4403, TerminalConnectionState.forbidden),428 ])429 func finalCloseCodes(code: Int, expected: TerminalConnectionState) async throws {430 let rig = try await Rig()431 let ws = try await rig.open()432 ws.serverClose(code: code)433 #expect(await rig.waitForState(expected))434 #expect(expected.isFinal)435 await rig.settle()436 #expect(rig.sockets.requests.count == 1, "no retry after \(code)")437 #expect(rig.retryDelays.isEmpty)438 #expect(rig.server.requests.isEmpty, "no HTTP call at all")439 #expect(await rig.connection.latencyMs == nil)440 }441442 @Test(arguments: [1000, 1001, 1006, 1011, 4000])443 func otherClosesRetryWithBackoffWithoutProbing(code: Int) async throws {444 let rig = try await Rig()445 let ws = try await rig.open()446 ws.serverClose(code: code)447 #expect(await rig.waitForRetryDelays(1))448 #expect(rig.retryDelays == [0.5])449 #expect(isReconnecting(await rig.connection.state, attempt: 1))450 if case .reconnecting(_, let retryAt) = await rig.connection.state { #expect(retryAt != nil) }451 #expect(rig.server.requests.isEmpty)452 rig.sleeper.advance(by: 0.5)453 #expect(await rig.sockets.waitForConnection(count: 2) != nil)454 #expect(await rig.waitForState(.open))455 await rig.connection.stop()456 }457458 @Test func backpressureCloseExplainsThenRetries() async throws {459 let rig = try await Rig()460 let ws = try await rig.open()461 ws.serverClose(code: 4429)462 #expect(await rig.waitForRetryDelays(1))463 #expect(await rig.connection.detail == "Connection too slow for the output rate")464 #expect(rig.server.requests.isEmpty)465 rig.sleeper.advance(by: 0.5)466 #expect(await rig.waitForState(.open))467 #expect(await rig.connection.detail == nil, "detail is cleared once open again")468 await rig.connection.stop()469 }470471 @Test(arguments: [472 ("RUNNING", nil as Int?, nil as TerminalConnectionState?),473 ("STOPPED", 7, TerminalConnectionState.ended(exitCode: 7)),474 ("FAILED", nil, TerminalConnectionState.ended(exitCode: nil)),475 ("RECOVERABLE", nil, TerminalConnectionState.recoverable),476 ])477 func runtimeUnavailableProbesTheSession(state: String, exitCode: Int?, expected: TerminalConnectionState?) async throws {478 let rig = try await Rig()479 rig.server.on("GET", "/api/v1/sessions/\(sessionID)") { _ in .json(sessionJSON(state: state, exitCode: exitCode)) }480 let ws = try await rig.open()481 ws.serverClose(code: 4503)482 if let expected {483 #expect(await rig.waitForState(expected))484 await rig.settle()485 #expect(rig.retryDelays.isEmpty && rig.sockets.requests.count == 1)486 if case .ended(let code) = expected { #expect(await rig.connection.exitCode == code) }487 } else {488 #expect(await rig.waitForRetryDelays(1))489 #expect(isReconnecting(await rig.connection.state))490 }491 #expect(await rig.connection.detail == "Runtime unavailable")492 #expect(rig.server.count("GET", "/api/v1/sessions/\(sessionID)") == 1)493 await rig.connection.stop()494 }495496 @Test func runtimeUnavailableProbeNotFoundAndUnauthorized() async throws {497 let gone = try await Rig()498 gone.server.on("GET", "/api/v1/sessions/\(sessionID)") { _ in .error(404, "not_found") }499 try await gone.open().serverClose(code: 4503)500 #expect(await gone.waitForState(.notFound))501502 let revoked = try await Rig()503 revoked.server.on("GET", "/api/v1/sessions/\(sessionID)") { _ in .error(401, "unauthenticated") }504 try await revoked.open().serverClose(code: 4503)505 #expect(await revoked.waitForState(.unauthorized))506 await revoked.settle()507 #expect(revoked.sockets.requests.count == 1)508 }509510 // MARK: Refused upgrades511512 @Test(arguments: [513 (401, TerminalConnectionState.unauthorized),514 (403, TerminalConnectionState.forbidden),515 (404, TerminalConnectionState.notFound),516 (410, TerminalConnectionState.ended(exitCode: nil)),517 ])518 func refusedUpgradeIsFinal(status: Int, expected: TerminalConnectionState) async throws {519 let rig = try await Rig()520 rig.sockets.enqueue(.refuse(status: status))521 await rig.connection.start(cols: 100, rows: 30)522 #expect(await rig.waitForState(expected))523 await rig.settle()524 #expect(rig.sockets.requests.count == 1)525 #expect(rig.retryDelays.isEmpty)526 #expect(rig.sink.log.isEmpty, "nothing is reset or fed when the socket never opened")527 }528529 @Test func refused503ProbesThenRetries() async throws {530 let rig = try await Rig()531 rig.sockets.enqueue(.refuse(status: 503))532 await rig.connection.start(cols: 100, rows: 30)533 #expect(await rig.waitForRetryDelays(1))534 #expect(rig.server.count("GET", "/api/v1/sessions/\(sessionID)") == 1)535 #expect(await rig.connection.detail == "Runtime unavailable")536 rig.sleeper.advance(by: 0.5)537 #expect(await rig.waitForState(.open))538 #expect(await rig.connection.reconnectCount == 0, "the first successful attach is not a reconnect")539 }540541 @Test func refused503OnAStoppedSessionEnds() async throws {542 let rig = try await Rig(probeState: "STOPPED")543 rig.sockets.enqueue(.unreachable)544 await rig.connection.start(cols: 100, rows: 30)545 #expect(await rig.waitForState(.ended(exitCode: nil)))546 }547548 // MARK: Backoff549550 @Test func backoffGrowsAndResetsOnceOpen() async throws {551 let rig = try await Rig()552 let first = try await rig.open()553 rig.sockets.enqueue(.unreachable, .refuse(status: 503), .unreachable, .unreachable, .unreachable, .unreachable, .accept)554 first.serverClose(code: 1006)555 let expected: [TimeInterval] = [0.5, 1, 2, 4, 8, 10, 10]556 for (i, delay) in expected.enumerated() {557 #expect(await rig.waitForRetryDelays(i + 1))558 #expect(rig.retryDelays.last == delay)559 #expect(isReconnecting(await rig.connection.state, attempt: i + 1))560 rig.sleeper.advance(by: delay)561 }562 let reopened = try #require(await rig.sockets.waitForConnection(count: 2))563 #expect(await rig.waitForState(.open))564 #expect(rig.sink.resets == 2)565 reopened.serverClose(code: 1006)566 #expect(await rig.waitForRetryDelays(expected.count + 1))567 #expect(rig.retryDelays.last == 0.5, "the attempt counter restarts after a successful attach")568 #expect(rig.server.requests.allSatisfy { $0.method == "GET" }, "reconnecting only probes; it never creates or restarts anything")569 #expect(rig.server.requests.allSatisfy { $0.path == "/api/v1/sessions/\(sessionID)" })570 await rig.connection.stop()571 }572573 @Test func jitterSpansTheConfiguredRange() {574 #expect(ReconnectPolicy(random: { 0 }).delay(attempt: 0) == 0.375)575 #expect(ReconnectPolicy(random: { 1 }).delay(attempt: 0) == 0.625)576 #expect(ReconnectPolicy(random: { 1 }).delay(attempt: 20) == 12.5)577 }578579 // MARK: Reconnect semantics580581 @Test func reconnectResetsBeforeFeedingTheNewStream() async throws {582 let rig = try await Rig()583 let first = try await rig.open()584 first.serverSend(bytes: "first attach")585 #expect(await rig.waitFor { rig.sink.log.count == 2 })586 first.serverClose(code: 1006)587 #expect(await rig.waitForRetryDelays(1))588 rig.sleeper.advance(by: 0.5)589 let second = try #require(await rig.sockets.waitForConnection(count: 2))590 second.serverSend(bytes: "replayed history")591 second.serverSend(bytes: "live screen")592 #expect(await rig.waitFor { rig.sink.log.count == 5 })593 #expect(rig.sink.log == [.reset, .bytes("first attach"), .reset, .bytes("replayed history"), .bytes("live screen")])594 #expect(await rig.connection.reconnectCount == 1)595 #expect(rig.sockets.requests.count == 2)596 #expect(rig.server.requests.isEmpty, "a reconnect is a new attach only: no session is created or restarted")597 await rig.connection.stop()598 }599600 @Test func wakeRetriesImmediatelyWhileReconnecting() async throws {601 let rig = try await Rig()602 let first = try await rig.open()603 first.serverClose(code: 1006)604 #expect(await rig.waitForRetryDelays(1))605 await rig.connection.wake()606 #expect(await rig.sockets.waitForConnection(count: 2) != nil)607 #expect(await rig.waitForState(.open))608 rig.sleeper.advance(by: 0.5)609 await rig.settle()610 #expect(rig.sockets.requests.count == 2, "the cancelled timer does not fire a second attach")611 await rig.connection.stop()612 }613614 @Test func wakeChecksThatAnOpenSocketIsAlive() async throws {615 let dead = try await Rig()616 let first = try await dead.open()617 await dead.connection.wake()618 #expect(await first.waitForSent { _ in controls(first).contains(.ping(n: 2)) })619 #expect(await dead.waitFor { dead.sleeper.requested.contains(TerminalConnection.wakeProbeTimeout) })620 dead.sleeper.advance(by: TerminalConnection.wakeProbeTimeout)621 #expect(await dead.sockets.waitForConnection(count: 2) != nil, "no pong within 2.5 s: reconnect")622 await dead.connection.stop()623624 let alive = try await Rig(autoPong: true)625 _ = try await alive.open()626 await alive.connection.wake()627 #expect(await alive.waitFor { alive.sleeper.requested.contains(TerminalConnection.wakeProbeTimeout) })628 #expect(await alive.waitFor { await alive.connection.latencyMs != nil })629 alive.sleeper.advance(by: TerminalConnection.wakeProbeTimeout)630 await alive.settle()631 #expect(alive.sockets.requests.count == 1)632 #expect(await alive.connection.state == .open)633 await alive.connection.stop()634 }635636 @Test func offlineIsShownAndWakeRecovers() async throws {637 let rig = try await Rig()638 let first = try await rig.open()639 first.serverClose(code: 1006)640 #expect(await rig.waitForRetryDelays(1))641 await rig.connection.networkBecameUnavailable()642 #expect(await rig.connection.state == .offline)643 #expect(TerminalConnectionState.offline.isReconnecting && !TerminalConnectionState.offline.isFinal)644 await rig.connection.wake()645 #expect(await rig.waitForState(.open))646 await rig.connection.stop()647 }648649 @Test func reconnectNowReattachesAnEndedOrOpenSession() async throws {650 let rig = try await Rig()651 let first = try await rig.open()652 first.serverClose(code: 4410)653 #expect(await rig.waitForState(.ended(exitCode: nil)))654 await rig.connection.reconnectNow() // after POST /sessions/:id/reconnect {restart:true} by the UI655 let second = try #require(await rig.sockets.waitForConnection(count: 2))656 #expect(await rig.waitForState(.open))657 await rig.connection.reconnectNow()658 #expect(await rig.sockets.waitForConnection(count: 3) != nil)659 #expect(await rig.waitForState(.open))660 #expect(second.clientClose?.code == 1000)661 #expect(rig.sink.resets == 3)662 #expect(rig.server.requests.isEmpty)663 await rig.connection.stop()664 }665666 @Test func stopClosesNormallyAndNeverRetries() async throws {667 let rig = try await Rig()668 let ws = try await rig.open()669 await rig.connection.stop()670 #expect(ws.clientClose?.code == 1000)671 #expect(await rig.connection.state == .idle)672 ws.serverClose(code: 1006)673 rig.sleeper.advance(by: 60)674 await rig.settle()675 #expect(rig.sockets.requests.count == 1)676 #expect(rig.retryDelays.isEmpty)677 rig.connection.send(text: "ignored")678 await rig.settle()679 #expect(ws.sentData.isEmpty)680 // A stopped connection can be started again.681 await rig.connection.start(cols: 80, rows: 24)682 #expect(await rig.sockets.waitForConnection(count: 2) != nil)683 await rig.connection.stop()684 }685686 @Test func stopDuringBackoffCancelsTheRetry() async throws {687 let rig = try await Rig()688 let ws = try await rig.open()689 ws.serverClose(code: 1006)690 #expect(await rig.waitForRetryDelays(1))691 await rig.connection.stop()692 rig.sleeper.advance(by: 60)693 await rig.settle()694 #expect(rig.sockets.requests.count == 1)695 #expect(await rig.connection.state == .idle)696 }697}698