From 95f6b12918c99c0e6e4898e59ac441b78770a984 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 28 Jul 2026 17:02:10 -0700 Subject: [PATCH] fix(mobile): invalidate the iOS websocket URLSession on teardown URLSession retains its delegate until invalidated, so cancelAll() left the connections object and its session alive on every module destroy/recreate cycle. Teardown now invalidates and clears the session; the next open() builds a fresh one. Verified on the simulator: environment connects, holds a single socket for 60s, and reconnects cleanly after a full app teardown and relaunch. Co-Authored-By: Claude Fable 5 --- .../t3-websocket/ios/T3WebSocketModule.swift | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift b/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift index cb975a665c..bdbf3fe85c 100644 --- a/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift +++ b/apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift @@ -58,15 +58,23 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat private var idsByTaskIdentifier: [Int: Int] = [:] private var emittersById: [Int: T3WebSocketEmitter] = [:] - private lazy var session: URLSession = { + // Held so teardown can invalidate it: URLSession retains its delegate (self) + // until invalidated, so skipping that leaks this object and the session on + // every module destroy/recreate cycle. Only touched from `queue`. + private var activeSession: URLSession? + + private var session: URLSession { + if let activeSession { return activeSession } let configuration = URLSessionConfiguration.default // Dev clients (and network debuggers) register custom URLProtocol classes // that intercept URLSession traffic. They do not understand the WebSocket // upgrade and drop the connection right after the 101 (NSURLErrorDomain // -1005). WebSocket traffic has no reason to go through them. configuration.protocolClasses = [] - return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) - }() + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + activeSession = session + return session + } func open(id: Int, url: URL, protocols: [String], emitter: @escaping T3WebSocketEmitter) { queue.async { @@ -110,6 +118,10 @@ private final class T3WebSocketConnections: NSObject, URLSessionWebSocketDelegat self.tasksById.removeAll() self.idsByTaskIdentifier.removeAll() self.emittersById.removeAll() + // Releases the session's reference to this delegate. A later `open` call + // builds a fresh session rather than using an invalidated one. + self.activeSession?.invalidateAndCancel() + self.activeSession = nil } }