Skip to content

Use Flutter's bin/dart --version to initialize Flutter SDK - #6486

Open
DanTupBot wants to merge 2 commits into
Dart-Code:masterfrom
DanTupBot:issue6455_bens_proposal
Open

DanTupBot wants to merge 2 commits into
Dart-Code:masterfrom
DanTupBot:issue6455_bens_proposal

Conversation

@DanTupBot

@DanTupBot DanTupBot commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #6455.
Part of #6454.

Summary

Updates ensureFlutterInitialized() to run <flutter>/bin/dart --version (bin/dart.bat --version on Windows) instead of flutter --suppress-analytics --help on the warm path:

  • Both bin/dart and bin/flutter run Flutter's bin/internal/shared.{sh,bat} lock and update_dart_sdk check before executing Dart, ensuring bin/cache/dart-sdk is up to date before spawning the analysis server without relying on brittle stamp-file parsing in Dart-Code.
  • Skipping flutter_tools.snapshot (~81 MB) on every startup cuts initialization time significantly.
  • Version metadata guard: Because shared.{sh,bat} delete version and bin/cache/flutter.version.json on cache invalidation while bin/dart --version never launches flutter_tools to regenerate flutter.version.json, we check getSdkVersion() (with nullLogger) before and after bin/dart --version and fall back to flutter --suppress-analytics --help when no valid Flutter version can be read.
  • Spawn errors, signals, and cancellation: runFlutterInitCommand() handles process "error" events and non-zero/signal exits (code !== 0) using a guarded settled failure path so spawn failures (e.g. EACCES) or signals cannot hang activation or register as success, disposes the cancellation listener when each command settles, and rejects before spawning if cancellation was already requested.

Exact Command Scenarios

Scenario Commands Executed Notes
Normal startup / reload (warm SDK with valid bin/cache/flutter.version.json or version) bin/dart --version (or bin/dart.bat --version) Single fast invocation; skips loading flutter_tools.snapshot.
After flutter upgrade bin/dart --version (or bin/dart.bat --version) flutter upgrade already regenerated flutter.version.json and flutter_tools.snapshot, so no fallback runs.
Corrupted flutter.version.json with a valid legacy version file bin/dart --version (or bin/dart.bat --version) getSdkVersion() falls back to the legacy version file, keeping the fast path without regenerating JSON.
Fresh git clone, missing version files, or corrupted flutter.version.json with no legacy version file flutter --suppress-analytics --help hasFlutterVersion() returns false upfront, so bin/dart --version is skipped and flutter runs once to update dart-sdk and generate flutter.version.json.
Manual git pull / git checkout without running flutter first (stale version file still on disk) 1. bin/dart --version (or bin/dart.bat --version)
2. flutter --suppress-analytics --help
bin/dart --version updates bin/cache/dart-sdk and shared.{sh,bat} deletes version and bin/cache/flutter.version.json; detecting the missing version file immediately triggers flutter --suppress-analytics --help to regenerate flutter.version.json before scanWorkspace() reads FlutterCapabilities.
Custom package-manager sdkInitScript (e.g. Snap / Hermit before SDK folder exists) <initScript> --suppress-analytics --help Uses initScript directly.
Legacy / custom Flutter SDK without bin/dart / bin/dart.bat flutter --suppress-analytics --help Falls back when bin/dart is not on disk.
Failure, spawn error, signal termination, or cancellation during bin/dart --version Runs initial command only (no fallback) Settles and rejects on "error", non-zero exit, signal termination (code === null), or 5s progress cancel; logs error, shows notification with Show Log, does not spawn fallback flutter --help, and allows workspace scanning to continue.

Benchmarks

Windows (run 1 + 10 interleaved warm runs mirroring Dart-Code's .bat spawning):

  • bin\flutter.bat --suppress-analytics --help: run 1 1405.4 ms, warm median 1236.4 ms
  • bin\dart.bat --version: run 1 559.0 ms, warm median 551.4 ms (~685 ms / 55.4% saved on warm runs, ~846 ms saved on run 1)
  • Baseline bin\cache\dart-sdk\bin\dart.exe --version (no shared.bat): warm median 8.4 ms

Linux (isolated clone of Flutter 3.50.1, 5 warm runs):

  • bin/flutter --suppress-analytics --help: median 136.8 ms
  • bin/dart --version: median 47.9 ms

Verification

  • Verified against an isolated local clone of Flutter 3.50.1 that with a missing/stale bin/cache/dart-sdk, bin/dart --version downloads and restores dart-sdk, and a subsequent flutter --suppress-analytics --help leaves the restored dart-sdk directory/binary inodes untouched.
  • Ran npm run lint, npm run build, npm run build-tests.
  • Ran BOT=dart npm run test src/test/dart/utils/sdk.test.ts (59 passing, covering warm JSON/legacy version files, corrupted JSON with and without legacy version, missing version files, cache invalidation fallback, missing bin/dart, non-zero exit / spawn error / signal termination without fallback, cancellation listener disposal across fallback, and skipping fallback spawn if already cancelled).
  • Ran BOT=flutter npm run test src/test/flutter/flutter_daemon.test.ts (11 passing, activating against the real local Flutter SDK).

@DanTupBot DanTupBot added is enhancement An enhancement or improvement that should be listed in release notes but is not a bug fix. in flutter Relates to running Flutter apps is performance labels Nov 24, 2026
@DanTupBot
DanTupBot requested a review from DanTup November 24, 2026 20:06
@DanTupBot DanTupBot added this to the v3.150.0 milestone Nov 24, 2026
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.75510% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.94%. Comparing base (4a22006) to head (70b5060).

Files with missing lines Patch % Lines
src/extension/sdk/flutter.ts 88.37% 4 Missing and 1 partial ⚠️
src/shared/constants.ts 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6486      +/-   ##
==========================================
- Coverage   81.97%   81.94%   -0.03%     
==========================================
  Files         173      173              
  Lines       14034    14069      +35     
  Branches     2879     2889      +10     
==========================================
+ Hits        11504    11529      +25     
- Misses       2064     2072       +8     
- Partials      466      468       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@DanTupBot
DanTupBot force-pushed the issue6455_bens_proposal branch 2 times, most recently from cdb2288 to ae661b2 Compare November 25, 2026 16:15
@DanTupBot
DanTupBot force-pushed the issue6455_bens_proposal branch from ae661b2 to b3c6149 Compare November 25, 2026 17:39

@DanTupBot DanTupBot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Overall this is a clean, well-tested implementation of the bin/dart --version approach agreed in #6455, with clear handling of version-file invalidation, spawn errors, and signal termination.

This needs work for two small edge cases in src/extension/sdk/flutter.ts (a Windows bin\mingit\cmd regression in dart.bat, and disposing/checking the shared cancellationToken across the fallback call), plus one minor test-helper deduplication suggestion.


const dartScript = path.join(target.flutterSdkPath, flutterDartPath);
const flutterScript = path.join(target.flutterSdkPath, flutterPath);
if (existsAndIsFileSync(dartScript) && hasFlutterVersion(target.flutterSdkPath)) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

On Windows, bin/flutter.bat adds Flutter's bundled mingit (%FLUTTER_ROOT%\bin\mingit\cmd) to PATH before calling bin/internal/shared.bat, whereas bin/dart.bat omits that block.

If a Windows user relies on bundled mingit without git on their system PATH, bin/dart.bat --version will fail inside shared.bat -> update_engine_version.ps1 (git -C ... ls-files) with exit code 1, showing a Flutter initialization error notification and never falling back to flutter.bat --suppress-analytics --help.

Skipping the bin/dart.bat fast-path when bin/mingit/cmd exists on Windows (e.g., !(isWin && existsAndIsDirectorySync(path.join(target.flutterSdkPath, "bin", "mingit", "cmd")))) would avoid regressing those setups.

@DanTupBot DanTupBot Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Intentionally not adding a workaround for bin/mingit/cmd here — the missing PATH entry in bin/dart.bat is being fixed upstream in Flutter, and very few users rely on the bundled MinGit archive without Git installed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is being fixed in Flutter at flutter/flutter#197390. We don't need to add workarounds for older SDK versions, as the number of users using the archive, on Windows, with no Git is likely very small.

*/
function runFlutterHelp(logger: Logger, flutterScript: string, cancellationToken: CancellationToken): Promise<void> {
const proc = safeToolSpawn(undefined, flutterScript, ["--suppress-analytics", "--help"]);
function runFlutterInitCommand(logger: Logger, script: string, args: string[], cancellationToken: CancellationToken): Promise<void> {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Now that initializeFlutter can call runFlutterInitCommand twice with the same cancellationToken (when falling back from dart --version to flutter --suppress-analytics --help), two cancellation edge cases apply:

  1. The cancellationToken.onCancellationRequested(...) subscription registered below isn't disposed when the first command finishes, so cancelling during the fallback command will invoke both listeners (logging User canceled! twice and calling proc.kill() on the already-exited first process). Disposing the subscription when the promise settles avoids keeping stale listeners around.
  2. If cancellation is requested right as dart --version completes (before the fallback starts), runFlutterInitCommand will still spawn the fallback process before cancellation triggers. Checking if (cancellationToken.isCancellationRequested) up front (or before the fallback call in initializeFlutter) avoids spawning a second process after cancellation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch — addressed both edge cases in commit 70b506060:

  1. Disposed the cancellationToken.onCancellationRequested(...) subscription synchronously when runFlutterInitCommand settles (both on success and failure).
  2. Checked cancellationToken.isCancellationRequested at the start of runFlutterInitCommand before spawning (and skipped the fallback info log in initializeFlutter if already cancelled).

Also added unit tests in src/test/dart/utils/sdk.test.ts covering both cases.

Comment thread src/test/dart/utils/sdk.test.ts Outdated
});

describe("Flutter initialization", () => {
function isolatePathEnv(): void {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Nit: isolatePathEnv() duplicates useIsolatedSdkSearch() in the sibling describe("Dart SDK search precedence") block above (and similar inline setup in the preceding tests). Lifting useIsolatedSdkSearch() up to describe("scanWorkspace") would let all of them share one helper.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Lifted useIsolatedSdkSearch() up to describe("scanWorkspace") in commit 70b506060 and removed isolatePathEnv() in favor of reusing it (leaving unrelated pre-existing tests untouched to keep the PR diff focused).

@DanTupBot DanTupBot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

All feedback has been addressed in 70b506060 (disposing the cancellation listener on settlement, guarding against spawning the fallback after cancellation, adding targeted tests for both cases, and reusing useIsolatedSdkSearch()), and skipping a bin/mingit/cmd workaround makes sense given the upstream fix in flutter/flutter#197390.

LGTM!

This branch has not been deployed

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

Labels

in flutter Relates to running Flutter apps is enhancement An enhancement or improvement that should be listed in release notes but is not a bug fix. is performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fast-path ensureFlutterInitialized() using Flutter stamp files to avoid spawning flutter --help on every startup

2 participants