@@ -17,19 +17,33 @@ typedef ExtensionEntryPoint = void Function(SendPort sendPort);
1717/// Represents an active host-side connection to a running tool extension isolate.
1818class ExtensionConnection {
1919 ExtensionConnection ._({
20- required Isolate this ._isolate,
21- required this ._peer,
2220 required this .capabilities,
2321 required this .extensionName,
22+ required this ._errorPort,
23+ required this ._exitPort,
24+ required Isolate this ._isolate,
2425 required this ._logger,
26+ required this ._peer,
27+ required this ._receivePort,
2528 });
2629
2730 /// Fallback extension name used when an extension does not report one in its capabilities.
2831 static const defaultExtensionName = 'unknown_extension' ;
2932
3033 Isolate ? _isolate;
31- final json_rpc.Peer _peer;
34+
35+ /// Port receiving uncaught async errors (`[String error, String? stackTrace]` )
36+ /// from the extension isolate.
37+ final ReceivePort _errorPort;
38+
39+ /// Port notified when the extension isolate terminates so the host can close
40+ /// [_receivePort] and fail any in-flight RPCs instead of hanging.
41+ final ReceivePort _exitPort;
42+
3243 final Logger _logger;
44+ final json_rpc.Peer _peer;
45+ final ReceivePort _receivePort;
46+ final _notificationControllers = < String , StreamController <Map <String , Object ?>>> {};
3347
3448 /// The capabilities and supported service namespaces of the extension.
3549 final ToolExtensionCapabilities capabilities;
@@ -39,6 +53,64 @@ class ExtensionConnection {
3953
4054 bool _isDisposed = false ;
4155
56+ /// Handles uncaught async errors from the extension isolate after handshake.
57+ ///
58+ /// Per [Isolate.addErrorListener] , `dart:isolate` delivers uncaught errors on
59+ /// the `onError` port as a two-element `List<Object?>` containing
60+ /// `[String errorDescription, String? stackTrace]` . Logging them here surfaces
61+ /// uncaught extension isolate errors that occur outside an active JSON-RPC
62+ /// request handler.
63+ void _handleIsolateError (Object ? error) {
64+ if (error case [final Object ? errorDescription, final Object ? stackTrace]) {
65+ _logger.printError ('Extension isolate "$extensionName " unhandled error: $errorDescription ' );
66+ if (stackTrace != null ) {
67+ _logger.printTrace ('$stackTrace ' );
68+ }
69+ } else {
70+ _logger.printError ('Extension isolate "$extensionName " unhandled error: $error ' );
71+ }
72+ }
73+
74+ /// Handles unexpected extension isolate termination after handshake.
75+ ///
76+ /// `IsolateChannel` (backed by a `ReceivePort` /`SendPort` pair) does not
77+ /// automatically close when the remote isolate exits. Closing [_receivePort]
78+ /// when the `onExit` port fires causes the JSON-RPC [json_rpc.Peer] to close
79+ /// immediately, failing any in-flight [sendRequest] calls (such as
80+ /// long-running `timeout: null` build requests) with a [StateError] and
81+ /// closing active notification streams instead of hanging indefinitely.
82+ void _handleIsolateExit () {
83+ _logger.printTrace ('Extension isolate "$extensionName " exited unexpectedly.' );
84+ unawaited (dispose ());
85+ }
86+
87+ /// Returns a broadcast stream of JSON-RPC 2.0 notifications sent by the
88+ /// extension isolate for [method] .
89+ Stream <Map <String , Object ?>> onNotification (String method) {
90+ if (_isDisposed) {
91+ throw StateError ('ExtensionConnection has been disposed.' );
92+ }
93+ final StreamController <Map <String , Object ?>>
94+ controller = _notificationControllers.putIfAbsent (method, () {
95+ final newController = StreamController <Map <String , Object ?>>.broadcast ();
96+ _peer.registerMethod (method, (json_rpc.Parameters params) {
97+ if (newController.isClosed) {
98+ return ;
99+ }
100+ final Object ? rawValue = params.value;
101+ if (rawValue is ! Map <String , Object ?>) {
102+ _logger.printWarning (
103+ 'Extension "$extensionName " sent malformed notification for "$method ": expected Map<String, Object?>.' ,
104+ );
105+ return ;
106+ }
107+ newController.add (rawValue);
108+ });
109+ return newController;
110+ });
111+ return controller.stream;
112+ }
113+
42114 /// Sends an RPC request to the extension isolate.
43115 Future <Object ?> sendRequest (
44116 String method, {
@@ -68,27 +140,38 @@ class ExtensionConnection {
68140 }) async {
69141 logger.printTrace ('ExtensionConnection spawning extension isolate...' );
70142 final receivePort = ReceivePort ();
71- final errorPort = RawReceivePort ();
72- final exitPort = RawReceivePort ();
143+ final errorPort = ReceivePort ();
144+ final exitPort = ReceivePort ();
73145 final errorCompleter = Completer <Never >();
146+ ExtensionConnection ? connection;
74147
75- errorPort.handler = (Object ? error) {
148+ // Isolate.spawn delivers uncaught isolate errors as a two-element list:
149+ // `[String errorDescription, String? stackTrace]`.
150+ errorPort.listen ((Object ? error) {
151+ if (connection case final ExtensionConnection activeConnection) {
152+ activeConnection._handleIsolateError (error);
153+ return ;
154+ }
76155 if (! errorCompleter.isCompleted) {
77- if (error is List && error.isNotEmpty ) {
78- errorCompleter. completeError ( StateError ( 'Extension isolate error: ${ error [ 0 ]}' ));
79- } else {
80- errorCompleter. completeError ( StateError ( 'Extension isolate error: $ error ' )) ;
81- }
156+ final Object ? errorDescription = switch ( error) {
157+ [ final Object ? description, _] => description,
158+ _ => error,
159+ } ;
160+ errorCompleter. completeError ( StateError ( 'Extension isolate error: $ errorDescription ' ));
82161 }
83- };
162+ }) ;
84163
85- exitPort.handler = (Object ? _) {
164+ exitPort.listen ((Object ? _) {
165+ if (connection case final ExtensionConnection activeConnection) {
166+ activeConnection._handleIsolateExit ();
167+ return ;
168+ }
86169 if (! errorCompleter.isCompleted) {
87170 errorCompleter.completeError (
88171 StateError ('Extension isolate exited unexpectedly before handshake completed.' ),
89172 );
90173 }
91- };
174+ }) ;
92175
93176 Isolate ? isolate;
94177
@@ -120,26 +203,30 @@ class ExtensionConnection {
120203 'ExtensionConnection handshake complete. Capabilities: ${capabilities .services }' ,
121204 );
122205
123- return ExtensionConnection ._(
124- isolate: isolate,
125- peer: peer,
206+ return connection = ExtensionConnection ._(
126207 capabilities: capabilities,
127208 extensionName: capabilities.extensionName ?? defaultExtensionName,
209+ errorPort: errorPort,
210+ exitPort: exitPort,
211+ isolate: isolate,
128212 logger: logger,
213+ peer: peer,
214+ receivePort: receivePort,
129215 );
130216 } on TimeoutException {
131217 logger.printTrace ('ExtensionConnection handshake timed out.' );
132218 receivePort.close ();
219+ errorPort.close ();
220+ exitPort.close ();
133221 isolate? .kill (priority: Isolate .immediate);
134222 throw TimeoutException ('Handshake with tool extension isolate timed out.' );
135223 } on Object catch (error) {
136224 logger.printTrace ('ExtensionConnection spawn failed with error: $error ' );
137225 receivePort.close ();
138- isolate? .kill (priority: Isolate .immediate);
139- rethrow ;
140- } finally {
141226 errorPort.close ();
142227 exitPort.close ();
228+ isolate? .kill (priority: Isolate .immediate);
229+ rethrow ;
143230 }
144231 }
145232
@@ -150,6 +237,14 @@ class ExtensionConnection {
150237 }
151238 _isDisposed = true ;
152239 _logger.printTrace ('ExtensionConnection disposing isolate connection.' );
240+ _errorPort.close ();
241+ _exitPort.close ();
242+ _receivePort.close ();
243+ for (final StreamController <Map <String , Object ?>> controller
244+ in _notificationControllers.values) {
245+ await controller.close ();
246+ }
247+ _notificationControllers.clear ();
153248 try {
154249 await _peer.close ();
155250 } on Object catch (error) {
@@ -166,7 +261,7 @@ class ExtensionDiscovery {
166261 /// Creates an [ExtensionDiscovery] instance with required [_logger] .
167262 ExtensionDiscovery ({required this ._logger});
168263
169- final List < ExtensionConnection > _connections = < ExtensionConnection > [];
264+ final _connections = < ExtensionConnection > [];
170265 final Logger _logger;
171266
172267 /// Active extension connections.
0 commit comments