Skip to content

Commit bcb21e8

Browse files
authored
[flutter_tools] Fix DTD "Stream already subscribed" error and wait for analysis over DTD in widget preview (flutter#192930)
## Description During widget preview startup or file updates: 1. Concurrent calls to retrieve previews or wait for analysis (e.g., initial command startup racing with file watcher events) could concurrently invoke `_waitForLspService()`, causing duplicate `streamListen` calls to the Dart Tooling Daemon. DTD throws JSON-RPC error 103 (`Stream already subscribed`) when a client attempts to subscribe to a stream it is already listening to. 2. `WidgetPreviewDtdServices` previously considered the `Lsp` service ready as soon as *any* `Lsp` method was registered on DTD (or upon receiving the first `ServiceRegistered` event for `Lsp`). Because the analysis server registers its LSP methods sequentially before posting an `initialized` event on the `Lsp` stream, calls to `Lsp.dart/workspace/analysis/complete` or `Lsp.dart/workspace/getFlutterWidgetPreviews` could race ahead of their registration and fail with `-32601 (method not found)`. 3. When connecting to a pre-existing analysis server over DTD (`--dtd-url`), `LspPreviewDetector.analysisServer` is `null`, causing `analysisServer?.waitForAnalysis()` calls during startup and file updates to be no-ops. This change: - Deduplicates in-flight calls to `_waitForLspService()` using a shared future (`_waitForLspServiceFuture`) so concurrent callers await the same LSP registration check instead of issuing duplicate DTD requests. - Separates `lspServiceAvailable` (whether an analysis server has begun registering `Lsp` services on DTD) from `_allLspServicesRegistered` (whether all required widget preview LSP methods in `kRequiredLspServices` are registered), and updates `_waitForLspServiceHelper()` to listen for the `initialized` event on the `Lsp` stream before checking `getRegisteredServices()`. - Consolidates LSP DTD calls into `_callLspService()` and removes the `kMethodNotFound` polling loop now that `_waitForLspService()` ensures all required LSP methods are registered. - Safely catches and ignores `RpcErrorCodes.kStreamAlreadySubscribed` on `streamListen` calls in `WidgetPreviewDtdServices` (`safeStreamListen`). - Adds `WidgetPreviewDtdServices.waitForAnalysis()` (invoking `Lsp.dart/workspace/analysis/complete` over DTD), unifies `LspPreviewDetector.waitForAnalysis()` so widget preview waits for analysis completion on both tool-managed and pre-existing analysis servers, and moves the startup `waitForAnalysis()` call inside the DTD error-handling `try / catch` block in `WidgetPreviewStartCommand`. - Adds hermetic regression tests covering concurrent/pre-subscribed DTD streams, partial vs. full LSP service registration (`Lsp.initialized`), and waiting for analysis over DTD. Fixes flutter#192424 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 63768f5 commit bcb21e8

7 files changed

Lines changed: 521 additions & 98 deletions

File tree

‎packages/flutter_tools/lib/src/commands/widget_preview.dart‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -394,19 +394,19 @@ final class WidgetPreviewStartCommand extends WidgetPreviewSubCommandBase with C
394394

395395
await _lspPreviewDetector.initialize();
396396

397-
// Wait for the initial analysis to complete to ensure the analysis server
398-
// has registered the widget preview RPC methods.
399-
await _lspPreviewDetector.analysisServer?.waitForAnalysis();
400-
401-
_previewCodeGenerator.populateDtdConnectionInfo(
402-
dtdUri: _dtdService.dtdUri!,
403-
widgetPreviewServiceName: _dtdService.widgetPreviewService,
404-
widgetPreviewScaffoldStreamName: _dtdService.widgetPreviewScaffoldStream,
405-
projectRootPath: rootProject.directory.absolute.path,
406-
);
407-
408397
final FlutterWidgetPreviews originalPreviews;
409398
try {
399+
// Wait for the initial analysis to complete to ensure the analysis server
400+
// has registered the widget preview RPC methods.
401+
await _lspPreviewDetector.waitForAnalysis();
402+
403+
_previewCodeGenerator.populateDtdConnectionInfo(
404+
dtdUri: _dtdService.dtdUri!,
405+
widgetPreviewServiceName: _dtdService.widgetPreviewService,
406+
widgetPreviewScaffoldStreamName: _dtdService.widgetPreviewScaffoldStream,
407+
projectRootPath: rootProject.directory.absolute.path,
408+
);
409+
410410
originalPreviews = await _dtdService.getFlutterWidgetPreviews();
411411
} on Exception catch (e) {
412412
throwToolExit(

‎packages/flutter_tools/lib/src/widget_preview/dtd_services.dart‎

Lines changed: 102 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,15 @@ typedef DtdService = (String, DTDServiceCallback);
3333
/// Provides services, streams, and RPC invocations to interact with the Widget Preview Scaffold.
3434
class WidgetPreviewDtdServices {
3535
WidgetPreviewDtdServices({
36-
required this.previewAnalytics,
36+
required this.addUuidToServiceName,
37+
required this.dtdLauncher,
3738
required this.fs,
3839
required this.logger,
39-
required this.shutdownHooks,
40-
required this.dtdLauncher,
4140
required this.onHotRestartPreviewerRequest,
41+
required this.previewAnalytics,
4242
required this.project,
43-
required this.addUuidToServiceName,
43+
required this.shutdownHooks,
44+
@visibleForTesting this._dtd,
4445
}) {
4546
shutdownHooks.addShutdownHook(() async {
4647
await _dtd?.close();
@@ -75,6 +76,28 @@ class WidgetPreviewDtdServices {
7576
/// The name of the language server protocol stream written to by the analysis server.
7677
static const kLspStream = 'Lsp';
7778

79+
/// The event kind posted to [kLspStream] once all LSP services have been registered with DTD.
80+
@visibleForTesting
81+
static const kLspInitializedEvent = 'initialized';
82+
83+
@visibleForTesting
84+
static const kGetFlutterWidgetPreviewsMethod = 'dart/workspace/getFlutterWidgetPreviews';
85+
86+
@visibleForTesting
87+
static const kGetFlutterWidgetPreviewsForFileMethod =
88+
'dart/textDocument/getFlutterWidgetPreviews';
89+
90+
@visibleForTesting
91+
static const kWorkspaceAnalysisCompleteMethod = 'dart/workspace/analysis/complete';
92+
93+
/// The set of LSP service methods required by the widget previewer.
94+
@visibleForTesting
95+
static const kRequiredLspServices = <String>{
96+
kGetFlutterWidgetPreviewsMethod,
97+
kGetFlutterWidgetPreviewsForFileMethod,
98+
kWorkspaceAnalysisCompleteMethod,
99+
};
100+
78101
/// The name of the event sent from the analysis server for widget preview updates.
79102
static const kLspWidgetPreviewEventKind = 'dart/textDocument/publishFlutterWidgetPreviews';
80103

@@ -138,9 +161,7 @@ class WidgetPreviewDtdServices {
138161
Uri? get dtdUri => _dtdUri;
139162
Uri? _dtdUri;
140163

141-
/// Returns true if the LSP service is registered with the connected DTD instance.
142-
bool get lspServiceAvailable => _lspServiceAvailable;
143-
bool _lspServiceAvailable = false;
164+
bool _allLspServicesRegistered = false;
144165

145166
/// Starts DTD in a child process before invoking [connect] with a [Uri] pointing to the new
146167
/// DTD instance.
@@ -158,99 +179,99 @@ class WidgetPreviewDtdServices {
158179
_dtdUri = dtdWsUri;
159180
_dtd = await DartToolingDaemon.connect(dtdWsUri);
160181

161-
_lspServiceAvailable = false;
182+
_allLspServicesRegistered = false;
162183
final RegisteredServicesResponse registeredServices = await _dtd!.getRegisteredServices();
163-
_lspServiceAvailable =
164-
registeredServices.dtdServices.contains(kLspStream) ||
165-
registeredServices.clientServices.any((service) => service.name == kLspStream);
184+
_allLspServicesRegistered = _areRequiredLspServicesRegistered(registeredServices);
166185

167186
await _registerServices();
168187
logger.printTrace('Connected to DTD and registered services.');
169188
}
170189

171190
Future<FlutterWidgetPreviews> getFlutterWidgetPreviews() async {
172-
await _waitForLspService();
173-
const maxAttempts = 50;
174-
for (var attempts = 0; attempts < maxAttempts; attempts++) {
175-
try {
176-
final DTDResponse result = await _dtd!.call(
177-
'Lsp',
178-
'dart/workspace/getFlutterWidgetPreviews',
179-
);
180-
return FlutterWidgetPreviews.fromJson(result.result['result']! as Map<String, Object?>);
181-
} on RpcException catch (e) {
182-
if (e.code == -32601 && attempts < maxAttempts - 1) {
183-
// Method not found
184-
await Future<void>.delayed(const Duration(milliseconds: 200));
185-
continue;
186-
}
187-
rethrow;
188-
}
189-
}
190-
throw StateError('Failed to call getFlutterWidgetPreviews after $maxAttempts attempts.');
191+
final DTDResponse result = await _callLspService(kGetFlutterWidgetPreviewsMethod);
192+
return FlutterWidgetPreviews.fromJson(result.result['result']! as Map<String, Object?>);
191193
}
192194

193195
Future<FlutterWidgetPreviews> getFlutterWidgetPreviewsForFile({required String filePath}) async {
196+
final DTDResponse result = await _callLspService(
197+
kGetFlutterWidgetPreviewsForFileMethod,
198+
params: <String, Object?>{'uri': Uri.file(filePath).toString()},
199+
);
200+
return FlutterWidgetPreviews.fromJson(result.result['result']! as Map<String, Object?>);
201+
}
202+
203+
/// Returns a [Future] that completes when the analysis server connected to DTD
204+
/// has completed any in-progress initialization or analysis.
205+
///
206+
/// This method will wait for [delay] before calling the server. If not
207+
/// provided, defaults to 100ms.
208+
Future<void> waitForAnalysis({Duration delay = const Duration(milliseconds: 100)}) async {
194209
await _waitForLspService();
195-
const maxAttempts = 50;
196-
for (var attempts = 0; attempts < maxAttempts; attempts++) {
197-
try {
198-
final DTDResponse result = await _dtd!.call(
199-
'Lsp',
200-
'dart/textDocument/getFlutterWidgetPreviews',
201-
params: {'uri': Uri.file(filePath).toString()},
202-
);
203-
return FlutterWidgetPreviews.fromJson(result.result['result']! as Map<String, Object?>);
204-
} on RpcException catch (e) {
205-
if (e.code == -32601 && attempts < maxAttempts - 1) {
206-
// Method not found
207-
await Future<void>.delayed(const Duration(milliseconds: 200));
208-
continue;
209-
}
210-
rethrow;
211-
}
212-
}
213-
throw StateError('Failed to call getFlutterWidgetPreviewsForFile after $maxAttempts attempts.');
210+
await Future<void>.delayed(delay);
211+
await _callLspService(kWorkspaceAnalysisCompleteMethod);
214212
}
215213

214+
Future<DTDResponse> _callLspService(String methodName, {Map<String, Object?>? params}) async {
215+
await _waitForLspService();
216+
return _dtd!.call(kLspStream, methodName, params: params);
217+
}
218+
219+
Future<void>? _waitForLspServiceFuture;
220+
216221
Future<void> _waitForLspService() async {
217-
if (_lspServiceAvailable) {
222+
if (_allLspServicesRegistered) {
218223
return;
219224
}
225+
final Future<void>? future = _waitForLspServiceFuture;
226+
if (future != null) {
227+
return future;
228+
}
229+
_waitForLspServiceFuture = _waitForLspServiceHelper();
230+
try {
231+
await _waitForLspServiceFuture;
232+
} finally {
233+
_waitForLspServiceFuture = null;
234+
}
235+
}
236+
237+
bool _areRequiredLspServicesRegistered(RegisteredServicesResponse registeredServices) {
238+
return registeredServices.clientServices.any(
239+
(service) =>
240+
service.name == kLspStream && kRequiredLspServices.every(service.methods.containsKey),
241+
);
242+
}
220243

221-
final lspRegisteredCompleter = Completer<void>();
244+
Future<void> _waitForLspServiceHelper() async {
245+
final lspInitializedCompleter = Completer<void>();
222246

223-
const kServiceStream = 'Service';
224-
await _dtd!.streamListen(kServiceStream);
225-
final StreamSubscription<DTDEvent> serviceSubscription = _dtd!.onEvent(kServiceStream).listen((
247+
final StreamSubscription<DTDEvent> lspSubscription = _dtd!.onEvent(kLspStream).listen((
226248
DTDEvent event,
227249
) {
228-
if (lspRegisteredCompleter.isCompleted) {
250+
if (lspInitializedCompleter.isCompleted) {
229251
return;
230252
}
231-
if (event case DTDEvent(kind: 'ServiceRegistered', data: {'service': kLspStream})) {
232-
_lspServiceAvailable = true;
233-
lspRegisteredCompleter.complete();
253+
if (event.kind == kLspInitializedEvent) {
254+
_allLspServicesRegistered = true;
255+
lspInitializedCompleter.complete();
234256
}
235257
});
236-
237258
try {
259+
await _dtd!.safeStreamListen(kLspStream);
238260
final RegisteredServicesResponse registeredServices = await _dtd!.getRegisteredServices();
239-
final bool alreadyRegistered =
240-
registeredServices.dtdServices.contains(kLspStream) ||
241-
registeredServices.clientServices.any((service) => service.name == kLspStream);
242-
if (alreadyRegistered) {
243-
_lspServiceAvailable = true;
244-
lspRegisteredCompleter.complete();
261+
if (_areRequiredLspServicesRegistered(registeredServices)) {
262+
_allLspServicesRegistered = true;
263+
if (!lspInitializedCompleter.isCompleted) {
264+
lspInitializedCompleter.complete();
265+
}
245266
} else {
246267
logger.printStatus('Waiting for analysis server to register Lsp service with DTD...');
247-
await lspRegisteredCompleter.future.timeout(const Duration(seconds: 30));
268+
await lspInitializedCompleter.future.timeout(const Duration(seconds: 30));
248269
}
249270
} on TimeoutException {
250271
logger.printWarning('Timed out waiting for the Lsp service to be registered with DTD.');
251272
rethrow;
252273
} finally {
253-
await serviceSubscription.cancel();
274+
await lspSubscription.cancel();
254275
}
255276
}
256277

@@ -287,7 +308,7 @@ class WidgetPreviewDtdServices {
287308
}
288309
});
289310
await Future.wait(<Future<void>>[
290-
dtd.streamListen(widgetPreviewScaffoldStream),
311+
dtd.safeStreamListen(widgetPreviewScaffoldStream),
291312
for (final (String method, DTDServiceCallback callback) in services)
292313
dtd
293314
.registerService(widgetPreviewService, method, callback)
@@ -379,3 +400,16 @@ class DtdLauncher {
379400

380401
Process? _dtdProcess;
381402
}
403+
404+
extension on DartToolingDaemon {
405+
/// A [streamListen] implementation that ignores already subscribed exceptions.
406+
Future<void> safeStreamListen(String streamId) async {
407+
try {
408+
await streamListen(streamId);
409+
} on RpcException catch (e) {
410+
if (e.code != RpcErrorCodes.kStreamAlreadySubscribed) {
411+
rethrow;
412+
}
413+
}
414+
}
415+
}

‎packages/flutter_tools/lib/src/widget_preview/lsp_preview_detector.dart‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -117,20 +117,15 @@ class LspPreviewDetector {
117117
// file watcher finished initializing.
118118
project.reloadManifest(logger: logger, fs: fs);
119119

120-
if (!dtd.lspServiceAvailable) {
120+
if (dtd.dtdUri == null) {
121121
logger.printStatus('Launching analysis server...');
122122
_analysisServer = analysisServerFactory != null
123123
? await analysisServerFactory!()
124124
: await launchAnalysisServer();
125125
await _analysisServer!.start();
126126

127-
final Uri? dtdUri = dtd.dtdUri;
128-
if (dtdUri != null) {
129-
await _analysisServer!.connectToDtd(dtdUri: dtdUri);
130-
} else {
131-
logger.printTrace('Launching a fresh DTD instance...');
132-
await dtd.launchAndConnect(analysisServer: _analysisServer!);
133-
}
127+
logger.printTrace('Launching a fresh DTD instance...');
128+
await dtd.launchAndConnect(analysisServer: _analysisServer!);
134129
}
135130
});
136131
}
@@ -185,6 +180,16 @@ class LspPreviewDetector {
185180
});
186181
}
187182

183+
/// Returns a [Future] that completes when the analysis server has completed
184+
/// any in-progress initialization or analysis.
185+
Future<void> waitForAnalysis() async {
186+
if (_analysisServer != null) {
187+
await _analysisServer!.waitForAnalysis();
188+
} else {
189+
await dtd.waitForAnalysis();
190+
}
191+
}
192+
188193
Future<void> _fileAddedOrUpdated({required String filePath}) async {
189194
if (filePath.isPubspec) {
190195
onPubspecChangeDetected(filePath);
@@ -196,7 +201,7 @@ class LspPreviewDetector {
196201
previewAnalytics.startPreviewReloadStopwatch();
197202
FlutterWidgetPreviews? result;
198203
try {
199-
await _analysisServer?.waitForAnalysis();
204+
await waitForAnalysis();
200205
var retries = 5;
201206
while (retries > 0) {
202207
if (_disposed || shutdownHooks.isShuttingDown) {

0 commit comments

Comments
 (0)