Skip to content

Commit 16bf22f

Browse files
Revert: [flutter_tools] Fix DTD "Stream already subscribed" error and wait for analysis over DTD in widget preview (flutter#193637)
Reverts: [[flutter_tools] Fix DTD "Stream already subscribed" error and wait for analysis over DTD in widget preview](flutter#192930) Initiated by: @jtmcdole Reason for reverting: ``` Original PR Author: @bkonyi Reviewed By: @DanTup The original PR description is provided below: ## 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 4e5a092 commit 16bf22f

7 files changed

Lines changed: 98 additions & 521 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+
397408
final FlutterWidgetPreviews originalPreviews;
398409
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: 68 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,14 @@ 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.addUuidToServiceName,
37-
required this.dtdLauncher,
36+
required this.previewAnalytics,
3837
required this.fs,
3938
required this.logger,
39+
required this.shutdownHooks,
40+
required this.dtdLauncher,
4041
required this.onHotRestartPreviewerRequest,
41-
required this.previewAnalytics,
4242
required this.project,
43-
required this.shutdownHooks,
44-
@visibleForTesting this._dtd,
43+
required this.addUuidToServiceName,
4544
}) {
4645
shutdownHooks.addShutdownHook(() async {
4746
await _dtd?.close();
@@ -76,28 +75,6 @@ class WidgetPreviewDtdServices {
7675
/// The name of the language server protocol stream written to by the analysis server.
7776
static const kLspStream = 'Lsp';
7877

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-
10178
/// The name of the event sent from the analysis server for widget preview updates.
10279
static const kLspWidgetPreviewEventKind = 'dart/textDocument/publishFlutterWidgetPreviews';
10380

@@ -161,7 +138,9 @@ class WidgetPreviewDtdServices {
161138
Uri? get dtdUri => _dtdUri;
162139
Uri? _dtdUri;
163140

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

166145
/// Starts DTD in a child process before invoking [connect] with a [Uri] pointing to the new
167146
/// DTD instance.
@@ -179,99 +158,99 @@ class WidgetPreviewDtdServices {
179158
_dtdUri = dtdWsUri;
180159
_dtd = await DartToolingDaemon.connect(dtdWsUri);
181160

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

186167
await _registerServices();
187168
logger.printTrace('Connected to DTD and registered services.');
188169
}
189170

190171
Future<FlutterWidgetPreviews> getFlutterWidgetPreviews() async {
191-
final DTDResponse result = await _callLspService(kGetFlutterWidgetPreviewsMethod);
192-
return FlutterWidgetPreviews.fromJson(result.result['result']! as Map<String, Object?>);
193-
}
194-
195-
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 {
209172
await _waitForLspService();
210-
await Future<void>.delayed(delay);
211-
await _callLspService(kWorkspaceAnalysisCompleteMethod);
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.');
212191
}
213192

214-
Future<DTDResponse> _callLspService(String methodName, {Map<String, Object?>? params}) async {
193+
Future<FlutterWidgetPreviews> getFlutterWidgetPreviewsForFile({required String filePath}) async {
215194
await _waitForLspService();
216-
return _dtd!.call(kLspStream, methodName, params: params);
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.');
217214
}
218215

219-
Future<void>? _waitForLspServiceFuture;
220-
221216
Future<void> _waitForLspService() async {
222-
if (_allLspServicesRegistered) {
217+
if (_lspServiceAvailable) {
223218
return;
224219
}
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-
}
243220

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

247-
final StreamSubscription<DTDEvent> lspSubscription = _dtd!.onEvent(kLspStream).listen((
223+
const kServiceStream = 'Service';
224+
await _dtd!.streamListen(kServiceStream);
225+
final StreamSubscription<DTDEvent> serviceSubscription = _dtd!.onEvent(kServiceStream).listen((
248226
DTDEvent event,
249227
) {
250-
if (lspInitializedCompleter.isCompleted) {
228+
if (lspRegisteredCompleter.isCompleted) {
251229
return;
252230
}
253-
if (event.kind == kLspInitializedEvent) {
254-
_allLspServicesRegistered = true;
255-
lspInitializedCompleter.complete();
231+
if (event case DTDEvent(kind: 'ServiceRegistered', data: {'service': kLspStream})) {
232+
_lspServiceAvailable = true;
233+
lspRegisteredCompleter.complete();
256234
}
257235
});
236+
258237
try {
259-
await _dtd!.safeStreamListen(kLspStream);
260238
final RegisteredServicesResponse registeredServices = await _dtd!.getRegisteredServices();
261-
if (_areRequiredLspServicesRegistered(registeredServices)) {
262-
_allLspServicesRegistered = true;
263-
if (!lspInitializedCompleter.isCompleted) {
264-
lspInitializedCompleter.complete();
265-
}
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();
266245
} else {
267246
logger.printStatus('Waiting for analysis server to register Lsp service with DTD...');
268-
await lspInitializedCompleter.future.timeout(const Duration(seconds: 30));
247+
await lspRegisteredCompleter.future.timeout(const Duration(seconds: 30));
269248
}
270249
} on TimeoutException {
271250
logger.printWarning('Timed out waiting for the Lsp service to be registered with DTD.');
272251
rethrow;
273252
} finally {
274-
await lspSubscription.cancel();
253+
await serviceSubscription.cancel();
275254
}
276255
}
277256

@@ -308,7 +287,7 @@ class WidgetPreviewDtdServices {
308287
}
309288
});
310289
await Future.wait(<Future<void>>[
311-
dtd.safeStreamListen(widgetPreviewScaffoldStream),
290+
dtd.streamListen(widgetPreviewScaffoldStream),
312291
for (final (String method, DTDServiceCallback callback) in services)
313292
dtd
314293
.registerService(widgetPreviewService, method, callback)
@@ -400,16 +379,3 @@ class DtdLauncher {
400379

401380
Process? _dtdProcess;
402381
}
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: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,20 @@ class LspPreviewDetector {
117117
// file watcher finished initializing.
118118
project.reloadManifest(logger: logger, fs: fs);
119119

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

127-
logger.printTrace('Launching a fresh DTD instance...');
128-
await dtd.launchAndConnect(analysisServer: _analysisServer!);
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+
}
129134
}
130135
});
131136
}
@@ -180,16 +185,6 @@ class LspPreviewDetector {
180185
});
181186
}
182187

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-
193188
Future<void> _fileAddedOrUpdated({required String filePath}) async {
194189
if (filePath.isPubspec) {
195190
onPubspecChangeDetected(filePath);
@@ -201,7 +196,7 @@ class LspPreviewDetector {
201196
previewAnalytics.startPreviewReloadStopwatch();
202197
FlutterWidgetPreviews? result;
203198
try {
204-
await waitForAnalysis();
199+
await _analysisServer?.waitForAnalysis();
205200
var retries = 5;
206201
while (retries > 0) {
207202
if (_disposed || shutdownHooks.isShuttingDown) {

0 commit comments

Comments
 (0)