Skip to content

Reland "[flutter_tools] Fix DTD "Stream already subscribed" error and wait for analysis over DTD in widget preview" - #193658

Merged
auto-submit[bot] merged 1 commit into
flutter:masterfrom
bkonyi:reland_widget_preview_dtd_192930
Oct 2, 2026
Merged

auto-submit[bot] merged 1 commit into
flutter:masterfrom
bkonyi:reland_widget_preview_dtd_192930

Conversation

@bkonyi

@bkonyi bkonyi commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Description

Relands #192930 (which was reverted in #193637).

What changed since the original PR

  • In AnalysisServer, store and cancel the stdout and stderr stream subscriptions in dispose() before closing _analyzingController and _errorsController, and guard _analyzingController.add with !_analyzingController.isClosed in _handleProgress. Previously, $/progress notifications arriving from the language server during or after AnalysisServer.dispose() threw Bad state: Cannot add new events after calling close in widget_preview_scaffold_test.dart.
  • In widget_preview_test_helpers.dart, await analysisServer.onExit after analysisServer.dispose() in addTearDown so the analysis server process has fully exited before temporary directory cleanup on Windows.
  • Added a hermetic unit test in analyze_continuously_test.dart verifying that AnalysisServer does not throw when $/progress notifications arrive during or after dispose().

Original 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 #192424

Pre-launch Checklist

… wait for analysis over DTD in widget preview"

This relands flutter#192930 (reverted in flutter#193637).

What changed since the original PR:
- In `AnalysisServer`, store and cancel the `stdout` and `stderr` stream subscriptions in `dispose()` before closing `_analyzingController` and `_errorsController`, and guard `_analyzingController.add` with `!_analyzingController.isClosed` in `_handleProgress`. Previously, `$/progress` notifications arriving from the language server during or after `AnalysisServer.dispose()` threw `Bad state: Cannot add new events after calling close`.
- In `widget_preview_test_helpers.dart`, await `analysisServer.onExit` after `analysisServer.dispose()` in `addTearDown` so the analysis server process has fully exited before temporary directory cleanup on Windows.
- Added a hermetic unit test in `analyze_continuously_test.dart` verifying that `AnalysisServer` does not throw when `$/progress` notifications arrive during or after `dispose()`.

Original 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
@bkonyi bkonyi added the CICD Run CI/CD label Oct 1, 2026
@github-actions github-actions Bot added the tool Affects the "flutter" command-line tool. See also t: labels. label Oct 1, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the Dart Tooling Daemon (DTD) and LSP preview detection logic in flutter_tools. Key changes include introducing a waitForAnalysis method to wait for analysis completion directly over DTD, preventing concurrent stream subscription issues by caching the wait future, and adding a safeStreamListen helper to ignore already subscribed exceptions. Additionally, AnalysisServer is updated to cancel stdout and stderr stream subscriptions on disposal and to avoid adding events to a closed controller. Comprehensive unit tests have been added to verify these behaviors. There are no review comments to address, and I have no further feedback to provide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CICD Run CI/CD tool Affects the "flutter" command-line tool. See also t: labels.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"Stream already subscribed" in Flutter Widget preview

2 participants