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.

@bkonyi bkonyi added the autosubmit Merge PR when tree becomes green via auto submit App label Oct 2, 2026
@auto-submit
auto-submit Bot added this pull request to the merge queue Oct 2, 2026
Merged via the queue into flutter:master with commit a851a18 Oct 2, 2026
28 checks passed
@flutter-dashboard flutter-dashboard Bot removed the autosubmit Merge PR when tree becomes green via auto submit App label Oct 2, 2026
suryaKommana2662 pushed a commit to suryaKommana2662/flutter that referenced this pull request Oct 29, 2026
… wait for analysis over DTD in widget preview" (flutter#193658)

## Description

Relands flutter#192930 (which was
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_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 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
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