Skip to content

Commit 962c369

Browse files
authored
fix: hold delegate reference to keep it from being deallocated (#26)
The problem we were having before was being caused by the system extension delegate being deallocated before the request responses came back. I didn't initially realize this, but the [OSSystemRequest.delegate](https://developer.apple.com/documentation/systemextensions/ossystemextensionrequest/delegate) is a weak reference (you have to click down to the individual field view in the docs to learn this). So, we keep a strong reference from the VPNService around while we are waiting for the extension to install.
1 parent 2f7f8f8 commit 962c369

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

Coder Desktop/Coder Desktop/SystemExtension.swift

+6
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ protocol SystemExtensionAsyncRecorder: Sendable {
2929
extension CoderVPNService: SystemExtensionAsyncRecorder {
3030
func recordSystemExtensionState(_ state: SystemExtensionState) async {
3131
sysExtnState = state
32+
if state == .installed {
33+
// system extension was successfully installed, so we don't need the delegate any more
34+
systemExtnDelegate = nil
35+
}
3236
}
3337

3438
var extensionBundle: Bundle {
@@ -71,6 +75,7 @@ extension CoderVPNService: SystemExtensionAsyncRecorder {
7175
queue: .main
7276
)
7377
let delegate = SystemExtensionDelegate(asyncDelegate: self)
78+
systemExtnDelegate = delegate
7479
request.delegate = delegate
7580
OSSystemExtensionManager.shared.submitRequest(request)
7681
logger.info("submitted SystemExtension request with bundleID: \(bundleID)")
@@ -87,6 +92,7 @@ class SystemExtensionDelegate<AsyncDelegate: SystemExtensionAsyncRecorder>:
8792

8893
init(asyncDelegate: AsyncDelegate) {
8994
self.asyncDelegate = asyncDelegate
95+
super.init()
9096
logger.info("SystemExtensionDelegate initialized")
9197
}
9298

Coder Desktop/Coder Desktop/VPNService.swift

+5
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ final class CoderVPNService: NSObject, VPNService {
5858

5959
@Published var agents: [Agent] = []
6060

61+
// systemExtnDelegate holds a reference to the SystemExtensionDelegate so that it doesn't get
62+
// garbage collected while the OSSystemExtensionRequest is in flight, since the OS framework
63+
// only stores a weak reference to the delegate.
64+
var systemExtnDelegate: SystemExtensionDelegate<CoderVPNService>?
65+
6166
override init() {
6267
super.init()
6368
installSystemExtension()

0 commit comments

Comments
 (0)