Replace `packageRootUri` with `vmServiceUri` (#10097) * Replace `packageRootUri` with `vmServiceUri` This replaces the `packageRootUri` query parameter with `VmServiceUri` in `api/serveAvailableExtensions`. Before this change, the DevTools app requested the user's package root file path from the VM service, and passed it along to `api/serveAvailableExtensions` using the `packageRootUri` query parameter. This meant that an untrusted caller could pass any directory on the host fileystem to probe directories or serve extensions outside of the active project directory. This deprecates the `packageRootUri` query parameter and replaces it with `vmServiceUri`, which allows the DevTools server to validate `vmServiceUri` and resolve the package root in `VmServiceHandler.detectRootPackageForVmService`. * Update CHANGELOG * Apply batched suggestions from code review Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * Apply suggestion from code review * Fix analyzer warning * Refactor ExtensionService to use named constructors for each situation 1. ExtensionService() – tracks the current app via the global service connection 2. ExtensionService.forVmService()– tracks extensions outside the current VSCode workspace. 3. ExtensionService.forWorkspace - tracks extensions for projects in the user's current VSCode workspace. * Remove unneeded check for mainIsolate.value != null _refresh() no longer queries the main isolate on the client—it just passes serviceConnection.serviceManager.serviceUri to the server. So the mainIsolate.value != null guard was just a leftover from when the client had to inspect mainIsolate to compute _appRoot. * use isNullOrEmpty extension method * Make `_detectExtensions` take two optional parameters * Revert changes to pubspec.lock * Address agent feedback - Record VM service root-detection failures as warnings in `handleServeAvailableExtensions` and still serve static DTD extensions, returning HTTP 500 only when no static extensions are found. - Key `_packageRootsForVmServiceConnections` solely by normalized `vmServiceUri.toString()`, normalize arguments in `setPackageRootForVmServiceForTesting`, and remove cached entries on disconnect. - Extract `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` into `devtools_shared` (`service_utils.dart`) and remove the duplicated logic from `_vm_service.dart`. - Deprecate `ServiceManager.connectedAppPackageRoot` in `devtools_app_shared`, delegate it to `VmService.rootPackageDirectoryForMainIsolate`, add a `TODO(johnpryan)` to remove it in the next breaking release, and clean up unused private helpers and imports. - Await `ws.ready` in `_connectWithWebSocket` to prevent unhandled `WebSocketChannelException` errors when a VM service connection fails. - Add tests for uncached unreachable loopback `vmServiceUri` handling (with and without static extensions) and for cache eviction on VM service disconnect. - Update `CHANGELOG.md` in `devtools_shared` and `devtools_app_shared`. * Simplify ExtensionService constructors * Remove unused path dependency * Update comments * [agent] Address PR review feedback on VM service package root caching and truncated string evaluation. * Evict `_packageRootsForVmServiceConnections` on disconnect in `handleNotifyForVmServiceConnection` before returning early when DTD or its secret is unavailable. * Add a `cacheResult` parameter to `detectRootPackageForVmService` and pass `cacheResult: false` from `handleServeAvailableExtensions` so callers that never send disconnect notifications do not leave stale cache entries, and update the cache doc comment accordingly. * Fetch the full string via `getObject` in `_lookupTestTargetPackageRoot` when `VmService.evaluate` returns a truncated `packageConfigLocation` `InstanceRef`. * Add unit tests covering disconnect cache eviction without DTD, non-caching root detection, and truncated `packageConfigLocation` evaluation results. * Address PR review comments on VM service package root detection This updates ServiceManager.connectedAppPackageRoot, VmServicePackageRootExtension, and VmServiceHandler to preserve prior isolate-handling behavior and remove unreachable cache eviction logic. - Await isolateManager.waitForMainIsolateState() in ServiceManager.connectedAppPackageRoot before querying the VM service so early calls on connect wait for the main isolate. - Remove the unreachable disconnect cache-eviction path when DTD is unavailable in VmServiceHandler.handleNotifyForVmServiceConnection, along with its doc note and unit test. - Return null from VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate when test-target package root lookup fails instead of falling back to a .dart file URI. - Catch SentinelException per isolate in _detectMainIsolate and handle null isolate name values safely, with unit tests covering these cases. * Add comment for `ws.ready` --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 2ba343c..6e153a4 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart
@@ -34,22 +34,21 @@ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - ExtensionService({this.fixedAppRoot, this.ignoreServiceConnection = false}); - - /// The fixed (unchanging) root file:// URI for the application this - /// [ExtensionService] will manage DevTools extensions for. + /// Detects runtime and static DevTools extensions. /// - /// When null, [_appRoot] will be calculated from the - /// `serviceConnection.serviceManager`'s currently connected app. - final Uri? fixedAppRoot; + /// When [fixedVmServiceUri] is provided, runtime extensions are detected for + /// that VM service instead of listening to `serviceConnection.serviceManager`. + ExtensionService({String? fixedVmServiceUri}) + : _fixedVmServiceUri = fixedVmServiceUri, + _useGlobalServiceConnection = fixedVmServiceUri == null; - /// Whether to ignore the VM service connection for the context of this - /// service. - final bool ignoreServiceConnection; + /// Detects static DevTools extensions for the IDE workspace only. + ExtensionService.forWorkspace() + : _fixedVmServiceUri = null, + _useGlobalServiceConnection = false; - /// The root file:// URI for the Dart / Flutter application this - /// [ExtensionService] will manage DevTools extensions for. - Uri? _appRoot; + final String? _fixedVmServiceUri; + final bool _useGlobalServiceConnection; /// A listenable for the current set of DevTools extensions. /// @@ -132,10 +131,7 @@ await _refresh(); cancelListeners(); - // We only need to add VM service manager related listeners when we are - // interacting with the currently connected app (i.e. when - // [fixedAppRootUri] is null). - if (fixedAppRoot == null && !ignoreServiceConnection) { + if (_useGlobalServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, () async { @@ -171,16 +167,12 @@ _log.fine('refreshing the ExtensionService'); _reset(); - _appRoot = null; - if (fixedAppRoot != null) { - _appRoot = fixedAppRoot; - } else if (!ignoreServiceConnection && - serviceConnection.serviceManager.connectedState.value.connected && - serviceConnection.serviceManager.isolateManager.mainIsolate.value != - null) { - _appRoot = await serviceConnection.serviceManager.connectedAppPackageRoot( - dtdManager, - ); + String? vmServiceUri; + if (_fixedVmServiceUri != null) { + vmServiceUri = _fixedVmServiceUri; + } else if (_useGlobalServiceConnection && + serviceConnection.serviceManager.connectedState.value.connected) { + vmServiceUri = serviceConnection.serviceManager.serviceUri; } // TODO(kenz): gracefully handle app connections / disconnects when there @@ -188,7 +180,9 @@ // when connection states change or hot restarts occur. _refreshInProgress.value = true; - final allExtensions = await server.refreshAvailableExtensions(_appRoot); + final allExtensions = await server.refreshAvailableExtensions( + vmServiceUri: vmServiceUri, + ); runtimeExtensions = allExtensions .where((e) => !e.detectedFromStaticContext) .toList(); @@ -336,7 +330,6 @@ void _reset() { _log.fine('resetting the ExtensionService'); - _appRoot = null; runtimeExtensions.clear(); staticExtensions.clear(); _ignoredStaticExtensionsByHashCode.clear();
diff --git a/packages/devtools_app/lib/src/shared/server/_extensions_api.dart b/packages/devtools_app/lib/src/shared/server/_extensions_api.dart index 290abea..b8cc6b9 100644 --- a/packages/devtools_app/lib/src/shared/server/_extensions_api.dart +++ b/packages/devtools_app/lib/src/shared/server/_extensions_api.dart
@@ -7,24 +7,19 @@ /// Makes a request to the server to refresh the list of available extensions, /// serve their assets on the server, and return the list of available /// extensions here. -Future<List<DevToolsExtensionConfig>> refreshAvailableExtensions( - // TODO(https://github.com/flutter/devtools/issues/7944): pass the URI to the - // package config file instead of passing the app root and rebulding the URI - // to the package config file. - Uri? appRoot, -) async { - _log.fine('refreshAvailableExtensions for app root: ${appRoot.toString()}'); +Future<List<DevToolsExtensionConfig>> refreshAvailableExtensions({ + String? vmServiceUri, +}) async { + _log.fine('refreshAvailableExtensions for vmServiceUri: $vmServiceUri'); if (debugDevToolsExtensions) { return debugHandleRefreshAvailableExtensions( - includeRuntime: appRoot != null, + includeRuntime: !vmServiceUri.isNullOrEmpty, ); } if (isDevToolsServerAvailable) { final uri = Uri( path: ExtensionsApi.apiServeAvailableExtensions, - queryParameters: { - ExtensionsApi.packageRootUriPropertyName: appRoot?.toString(), - }, + queryParameters: {ExtensionsApi.vmServiceUriPropertyName: vmServiceUri}, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) {
diff --git a/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart b/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart index 1dc6e7e..b43cbf4 100644 --- a/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart +++ b/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart
@@ -133,17 +133,22 @@ ); } - // Pass a null project root URI to initialize the set of extensions - // available for the entire workspace. - await _detectExtensions(null); + // Initialize extensions available for the entire workspace. + await _detectExtensions(); } Future<void> _initExtensionsForDebugSessions() async { for (final debugSession in _debugSessions.values) { final fileUri = debugSession.projectRootFileUri; - if (fileUri != null && !_searchedProjectRoots.contains(fileUri)) { + final vmServiceUri = debugSession.vmServiceUri; + if (fileUri != null && + vmServiceUri != null && + !_searchedProjectRoots.contains(fileUri)) { _searchedProjectRoots.add(fileUri); - await _detectExtensions(fileUri); + await _detectExtensions( + projectRootUri: fileUri, + vmServiceUri: vmServiceUri, + ); } } } @@ -162,16 +167,19 @@ // the workspace or for a debug session changes. We will likely need some // watch event from the IDE or analysis server to signal when any // package_config.json file in the workspace changes. - Future<void> _detectExtensions(Uri? projectRootUri) async { - final extensionService = projectRootUri == null - ? - // A null [projectRootUri] indicates that this is an extensions lookup - // for the entire workspace, not a debug session with a fixed root URI. - ExtensionService(ignoreServiceConnection: true) - : ExtensionService( - fixedAppRoot: projectRootUri, - ignoreServiceConnection: true, - ); + Future<void> _detectExtensions({ + Uri? projectRootUri, + String? vmServiceUri, + }) async { + assert( + (projectRootUri == null) == (vmServiceUri == null), + 'projectRootUri ($projectRootUri) and vmServiceUri ($vmServiceUri) ' + 'must either both be null (workspace lookup) or both be non-null ' + '(debug session lookup).', + ); + final extensionService = vmServiceUri == null + ? ExtensionService.forWorkspace() + : ExtensionService(fixedVmServiceUri: vmServiceUri); assert( !_extensionServiceByRootUri.containsKey(projectRootUri), 'The initialization for the ExtensionService for root uri '
diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 1dfdcb6..9bf254d 100644 --- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md +++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
@@ -114,6 +114,10 @@ * Validated DevTools extension version strings and prevented extension identifier collisions when serving extension assets. [#10090](https://github.com/flutter/devtools/pull/10090) +* Resolved the connected application's package root on the DevTools server via + the VM service URI when serving DevTools extensions instead of accepting a + package root file URI from the client. + [#10097](https://github.com/flutter/devtools/pull/10097) ## Advanced developer mode updates
diff --git a/packages/devtools_app/test/extensions/extension_screen_test.dart b/packages/devtools_app/test/extensions/extension_screen_test.dart index 036c598..ec26155 100644 --- a/packages/devtools_app/test/extensions/extension_screen_test.dart +++ b/packages/devtools_app/test/extensions/extension_screen_test.dart
@@ -36,9 +36,7 @@ setGlobal( ExtensionService, - ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), - ), + ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4);
diff --git a/packages/devtools_app/test/extensions/extension_service_test.dart b/packages/devtools_app/test/extensions/extension_service_test.dart index fea1cc2..28c0432 100644 --- a/packages/devtools_app/test/extensions/extension_service_test.dart +++ b/packages/devtools_app/test/extensions/extension_service_test.dart
@@ -34,9 +34,9 @@ resetDevToolsExtensionEnabledStates(); }); - test('initialize when connected', () async { + test('initialize with fixedVmServiceUri', () async { final service = ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', ); expect(service.availableExtensions, isEmpty); expect(service.staticExtensions, isEmpty); @@ -61,12 +61,12 @@ expect(ignoredRuntimeExtensions.length, 0); }); - test('initialize with ignoreServiceConnection', () async { + test('initialize with forWorkspace', () async { when( mockServiceManager.connectedState, ).thenReturn(ValueNotifier(const ConnectedState(false))); - final service = ExtensionService(ignoreServiceConnection: true); + final service = ExtensionService.forWorkspace(); expect(service.staticExtensions, isEmpty); expect(service.runtimeExtensions, isEmpty); expect(service.availableExtensions, isEmpty); @@ -87,7 +87,7 @@ test('setExtensionEnabledState', () async { final service = ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', ); await service.initialize(); expect(service.staticExtensions.length, 4);
diff --git a/packages/devtools_app/test/extensions/extension_settings_test.dart b/packages/devtools_app/test/extensions/extension_settings_test.dart index 9e17218..0ed74c1 100644 --- a/packages/devtools_app/test/extensions/extension_settings_test.dart +++ b/packages/devtools_app/test/extensions/extension_settings_test.dart
@@ -36,9 +36,7 @@ setGlobal( ExtensionService, - ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), - ), + ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4);
diff --git a/packages/devtools_app_shared/CHANGELOG.md b/packages/devtools_app_shared/CHANGELOG.md index ee3e124..f12fddc 100644 --- a/packages/devtools_app_shared/CHANGELOG.md +++ b/packages/devtools_app_shared/CHANGELOG.md
@@ -19,6 +19,8 @@ such as the `file:` URI of a Dart CLI app started with `dart run`. Previously it was the scheme of the URI, such as `file:`, which is not a package. * Updates `devtools_shared` constraint to `^14.0.1`. +* Deprecate `ServiceManager.connectedAppPackageRoot` in favor of + `VmService.rootPackageDirectoryForMainIsolate` from `devtools_shared`. ## 0.5.1 * Add DevTools-styled text field `DevToolsTextField`.
diff --git a/packages/devtools_app_shared/lib/src/service/service_manager.dart b/packages/devtools_app_shared/lib/src/service/service_manager.dart index da70413..7aa4b02 100644 --- a/packages/devtools_app_shared/lib/src/service/service_manager.dart +++ b/packages/devtools_app_shared/lib/src/service/service_manager.dart
@@ -5,20 +5,16 @@ import 'dart:async'; import 'dart:core'; -import 'package:collection/collection.dart'; import 'package:dds_service_extensions/dds_service_extensions.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; -import 'package:path/path.dart' as path; import 'package:vm_service/vm_service.dart' hide Error; -import '../utils/auto_dispose.dart'; import '../utils/utils.dart'; import 'connected_app.dart'; import 'dtd_manager.dart'; -import 'eval_on_dart_library.dart' hide SentinelException; import 'flutter_version.dart'; import 'isolate_manager.dart'; import 'isolate_state.dart'; @@ -506,121 +502,21 @@ /// `flutter test`). This is because the main isolate for test targets is /// running the test runner, and not the test library itself, so we have to do /// some extra work to find the package root of the test target. + // TODO(johnpryan): remove this in the next breaking release. + @Deprecated( + 'Use VmService.rootPackageDirectoryForMainIsolate from devtools_shared instead.', + ) Future<Uri?> connectedAppPackageRoot(DTDManager dtdManager) async { - var packageRootUriString = await rootPackageDirectoryForMainIsolate( - dtdManager, - ); - _log.fine( - '[connectedAppPackageRoot] root package directory for main isolate: ' - '$packageRootUriString', - ); - - // If a Dart library URI was returned, this may be a test target (i.e. a - // VM service connection spawned from `dart test` or `flutter test`). - if (packageRootUriString?.endsWith('.dart') ?? false) { - final rootLibrary = await _mainIsolateRootLibrary(); - if (rootLibrary != null) { - packageRootUriString = - (await _lookupPackageRootByEval(rootLibrary)) ?? - // TODO(kenz): remove this fallback once all test bootstrap - // generators include the `packageConfigLocation` constant we - // can evaluate. - await _lookupPackageRootByImportPrefix(rootLibrary, dtdManager); - } - } - _log.fine( - '[connectedAppPackageRoot] package root for test target: ' - '$packageRootUriString', - ); + final mainIsolateState = await isolateManager.waitForMainIsolateState(); + if (mainIsolateState == null) return null; + final packageRootUriString = await service + ?.rootPackageDirectoryForMainIsolate(dtd: dtdManager.connection.value); + _log.fine('[connectedAppPackageRoot] package root: $packageRootUriString'); return packageRootUriString == null ? null : Uri.parse(packageRootUriString); } - Future<String?> _lookupPackageRootByEval(Library rootLibrary) async { - final eval = EvalOnDartLibrary( - rootLibrary.uri!, - service! as VmService, - serviceManager: this, - // Swallow exceptions since this evaluation may be called on an older - // version of package:test where we do not expect the evaluation to - // succeed. - logExceptions: false, - ); - final evalDisposable = Disposable(); - try { - final packageConfig = (await eval.evalInstance( - 'packageConfigLocation', - isAlive: evalDisposable, - )).valueAsString; - - // TODO(https://github.com/flutter/devtools/issues/7944): return the - // unmodified package config location. For this case, be sure to handle - // invalid values like the empty String or 'null'. - final packageConfigIdentifier = path.join( - '.dart_tool', - 'package_config.json', - ); - if (packageConfig?.endsWith(packageConfigIdentifier) ?? false) { - _log.fine( - '[connectedAppPackageRoot] detected test package config from root ' - 'library eval: $packageConfig.', - ); - return packageConfig!.substring( - 0, - // Minus 1 to remove the trailing slash. - packageConfig.length - packageConfigIdentifier.length - 1, - ); - } - } catch (_) { - // Fail gracefully if the evaluation fails. - } finally { - evalDisposable.dispose(); - } - return null; - } - - Future<String?> _lookupPackageRootByImportPrefix( - Library rootLibrary, - DTDManager dtdManager, - ) async { - final testTargetFileUriString = - (rootLibrary.dependencies ?? <LibraryDependency>[]) - .firstWhereOrNull((dep) => dep.prefix == 'test') - ?.target - ?.uri; - if (testTargetFileUriString != null) { - _log.fine( - '[connectedAppPackageRoot] detected test library from root library ' - 'imports: $testTargetFileUriString', - ); - // TODO(https://github.com/flutter/devtools/issues/7944): return the - // unmodified package config location. - return await packageRootFromFileUriString( - testTargetFileUriString, - dtd: dtdManager.connection.value, - ); - } - return null; - } - - Future<Library?> _mainIsolateRootLibrary() async { - final ref = - (await isolateManager.waitForMainIsolateState())?.isolateNow?.rootLib; - if (ref == null) return null; - try { - final library = await service!.getObject( - isolateManager.mainIsolate.value!.id!, - ref.id!, - ); - assert(library is Library); - return library as Library; - } on SentinelException catch (_) { - // Fail gracefully if the request to get the Library object fails. - return null; - } - } - // TODO(kenz): consider caching this value for the duration of the VM service // connection. /// Returns a file URI String for the root library of the connected app's main
diff --git a/packages/devtools_app_shared/pubspec.yaml b/packages/devtools_app_shared/pubspec.yaml index 786defe..5c63122 100644 --- a/packages/devtools_app_shared/pubspec.yaml +++ b/packages/devtools_app_shared/pubspec.yaml
@@ -22,7 +22,6 @@ logging: ^1.1.1 material_ui: ^1.4.0 meta: ^1.9.1 - path: ^1.8.0 pointer_interceptor: ^0.10.1+1 url_launcher: ^6.1.0 vm_service: '>=13.0.0 <16.0.0'
diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 50bc259..3831378 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md
@@ -35,6 +35,12 @@ recursive directory creation when looking up `devtools_options.yaml`. * Restrict `normalizeVmServiceUri` to allowed VM service schemes (`http`, `https`, `ws`, `wss`, `sse`, `sses`) and loopback hosts (`localhost`, `127.0.0.0/8`, `::1`). +* Add `ExtensionsApi.vmServiceUriPropertyName`, deprecate + `ExtensionsApi.packageRootUriPropertyName`, and resolve the connected + application's package root on the server from `vmServiceUri` in + `api/serveAvailableExtensions`. +* Add `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` to + `devtools_shared.dart`. # 14.0.0
diff --git a/packages/devtools_shared/lib/src/devtools_api.dart b/packages/devtools_shared/lib/src/devtools_api.dart index c3d9a7e..f50595d 100644 --- a/packages/devtools_shared/lib/src/devtools_api.dart +++ b/packages/devtools_shared/lib/src/devtools_api.dart
@@ -113,10 +113,17 @@ '${apiPrefix}serveAvailableExtensions'; /// The property name for the query parameter passed along with + /// [apiServeAvailableExtensions] requests to the server that specifies the + /// VM service URI of the connected application whose runtime extensions are + /// being queried. + static const vmServiceUriPropertyName = 'vmServiceUri'; + + /// The property name for the query parameter passed along with /// extension-related requests to the server that describes the package root /// for the app whose extensions are being queried. /// /// This field is a `file://` URI string and NOT a path. + @Deprecated('Use vmServiceUriPropertyName instead.') static const packageRootUriPropertyName = 'packageRootUri'; /// The property name for the query parameter, passed along with
diff --git a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart index af2b3f3..6cfdd7c 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart
@@ -13,7 +13,7 @@ DtdInfo? dtd, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( - [ExtensionsApi.packageRootUriPropertyName], + const [ExtensionsApi.vmServiceUriPropertyName], queryParams: queryParams, api: api, requestName: ExtensionsApi.apiServeAvailableExtensions, @@ -21,31 +21,60 @@ if (missingRequiredParams != null) return missingRequiredParams; final logs = <String>[]; - final rootFileUriString = - queryParams[ExtensionsApi.packageRootUriPropertyName]; - if (rootFileUriString != null && rootFileUriString.isNotEmpty) { - final rootFileUri = Uri.tryParse(rootFileUriString); - if (!rootFileUriString.startsWith('file://') || - rootFileUri == null || - rootFileUri.scheme != 'file' || - rootFileUri.host.isNotEmpty) { + final warnings = <String>[]; + final vmServiceUriString = + queryParams[ExtensionsApi.vmServiceUriPropertyName]; + String? rootFileUriString; + if (vmServiceUriString != null && vmServiceUriString.isNotEmpty) { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString); + if (vmServiceUri == null) { return api.badRequest( - 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a ' - 'file:// URI with an empty host.', + 'Cannot normalize VM service URI: $vmServiceUriString', ); } + + DartToolingDaemon? dartToolingDaemon; + try { + final dtdUri = dtd?.localUri; + if (dtdUri != null) { + dartToolingDaemon = await DartToolingDaemon.connect(dtdUri); + } + final detectRootResponse = + await VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString, + vmServiceUri: vmServiceUri, + connected: true, + dtd: dartToolingDaemon, + cacheResult: false, + ); + if (!detectRootResponse.success) { + warnings.add( + detectRootResponse.message ?? + 'Failed to detect root package for VM service ' + '($vmServiceUriString).', + ); + } else { + rootFileUriString = detectRootResponse.uri?.toString(); + } + } catch (e) { + warnings.add('$e'); + } finally { + await dartToolingDaemon?.close(); + } } + final rootDetectionFailed = warnings.isNotEmpty; final result = <String, Object?>{}; /// Helper to return a success response with all available extensions /// detected by [extensionsManager]. - shelf.Response succeedWithAvailableExtensions({String? warning}) { + shelf.Response succeedWithAvailableExtensions() { final extensions = extensionsManager.devtoolsExtensions .map((p) => p.toJson()) .toList(); result[ExtensionsApi.extensionsResultPropertyName] = extensions; - if (warning != null) { - result[ExtensionsApi.extensionsResultWarningPropertyName] = warning; + if (warnings.isNotEmpty) { + result[ExtensionsApi.extensionsResultWarningPropertyName] = warnings + .join('\n'); } return ServerApi._encodeResponse( ServerApi._wrapWithLogs(result, logs), @@ -62,14 +91,19 @@ } on ExtensionParsingException catch (e) { // For [ExtensionParsingException]s, we should return a success response // with a warning message. - result[ExtensionsApi.extensionsResultWarningPropertyName] = e.message; + warnings.add(e.message); } catch (e) { + warnings.add('$e'); // If any extensions were successfully detected, return a success response // with a warning. if (extensionsManager.devtoolsExtensions.isNotEmpty) { - return succeedWithAvailableExtensions(warning: '$e'); + return succeedWithAvailableExtensions(); } - return api.serverError('$e', logs); + return api.serverError(warnings.join('\n'), logs); + } + + if (rootDetectionFailed && extensionsManager.devtoolsExtensions.isEmpty) { + return api.serverError(warnings.join('\n'), logs); } return succeedWithAvailableExtensions();
diff --git a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart index 94fd867..e51f13f 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart
@@ -10,14 +10,43 @@ /// Stores the calculated package roots for VM service connections that are /// initiated in [handleNotifyForVmServiceConnection]. /// - /// This map is used to lookup package roots for a particular VM service when + /// Entries are populated when [detectRootPackageForVmService] is called with + /// `connected: true` and `cacheResult: true` (e.g., from + /// [handleNotifyForVmServiceConnection] when DevTools server started DTD). + /// + /// This map is used both to avoid redundant VM service lookups (including + /// from [_ExtensionsApiHandler.handleServeAvailableExtensions], which reads + /// from this cache without populating it since callers like + /// `ExtensionService(fixedVmServiceUri:)` do not send disconnect + /// notifications) and to look up the root to remove when /// [handleNotifyForVmServiceConnection] is called for a VM service disconnect /// in DevTools app. - /// - /// If the Dart Tooling Daemon was not started by DevTools, this map will - /// never be used. static final _packageRootsForVmServiceConnections = <String, Uri>{}; + /// Caches [rootPackageUri] for [vmServiceUriAsString] in tests. + @visibleForTesting + static void setPackageRootForVmServiceForTesting( + String vmServiceUriAsString, + Uri rootPackageUri, + ) { + final normalizedUri = normalizeVmServiceUri(vmServiceUriAsString); + if (normalizedUri == null) { + throw ArgumentError.value( + vmServiceUriAsString, + 'vmServiceUriAsString', + 'Cannot normalize VM service URI', + ); + } + _packageRootsForVmServiceConnections[normalizedUri.toString()] = + rootPackageUri; + } + + /// Clears cached package roots between tests. + @visibleForTesting + static void clearPackageRootsForTesting() { + _packageRootsForVmServiceConnections.clear(); + } + static Future<shelf.Response> handleNotifyForVmServiceConnection( ServerApi api, Map<String, String> queryParams, @@ -110,13 +139,17 @@ required String vmServiceUriAsString, required Uri vmServiceUri, required bool connected, - required DartToolingDaemon dtd, + required DartToolingDaemon? dtd, + bool cacheResult = true, }) async { + final normalizedUriAsString = vmServiceUri.toString(); final Uri rootPackageUri; if (connected) { - // TODO(kenz): should we first try to lookup the root from - // [_packageRootsForVmServiceConnections]? Could the root library of the - // main isolate change during the lifetime of a VM service instance? + final cachedRoot = + _packageRootsForVmServiceConnections[normalizedUriAsString]; + if (cachedRoot != null) { + return (success: true, message: null, uri: cachedRoot); + } VmService? vmService; try { @@ -126,7 +159,9 @@ serviceFactory: VmService.defaultFactory, ); - final root = await vmService.rootPackageDirectoryForMainIsolate(dtd); + final root = await vmService.rootPackageDirectoryForMainIsolate( + dtd: dtd, + ); if (root == null) { return ( success: false, @@ -137,8 +172,10 @@ ); } rootPackageUri = Uri.parse(root); - _packageRootsForVmServiceConnections[vmServiceUriAsString] = - rootPackageUri; + if (cacheResult) { + _packageRootsForVmServiceConnections[normalizedUriAsString] = + rootPackageUri; + } } catch (e) { return ( success: false, @@ -150,8 +187,8 @@ vmService = null; } } else { - final cachedRootForVmService = - _packageRootsForVmServiceConnections[vmServiceUriAsString]; + final cachedRootForVmService = _packageRootsForVmServiceConnections + .remove(normalizedUriAsString); if (cachedRootForVmService == null) { // If there is no root to remove, there is nothing for us to do. return (success: true, message: null, uri: null); @@ -181,61 +218,5 @@ } } -extension on VmService { - Future<String?> rootPackageDirectoryForMainIsolate( - DartToolingDaemon dtd, - ) async { - final fileUriString = await _rootLibraryForMainIsolate; - return fileUriString != null - ? await packageRootFromFileUriString(fileUriString, dtd: dtd) - : null; - } - - Future<String?> get _rootLibraryForMainIsolate async { - final mainIsolate = await _detectMainIsolate; - final rootLib = mainIsolate.rootLib?.uri; - if (rootLib == null) return null; - - final fileUriAsString = (await lookupResolvedPackageUris(mainIsolate.id!, [ - rootLib, - ])).uris?.first; - return fileUriAsString; - } - - /// Uses heuristics to detect the main isolate. - /// - /// Assumes an isolate is the main isolate if it meets any of the criteria in - /// the following order: - /// - /// 1. The isolate is the main Flutter isolate. - /// 2. The isolate has ':main(' in its name. - /// 3. The isolate is the first in the list of isolates on the VM. - Future<Isolate> get _detectMainIsolate async { - final isolateRefs = (await getVM()).isolates!; - final isolateCandidates = await isolateRefs - .map((ref) async => (ref: ref, isolate: await getIsolate(ref.id!))) - .wait; - - Isolate? mainIsolate; - for (final isolate in isolateCandidates) { - final isFlutterIsolate = (isolate.isolate.extensionRPCs ?? []).any( - (ext) => ext.startsWith('ext.flutter'), - ); - if (isFlutterIsolate) { - mainIsolate = isolate.isolate; - break; - } - } - mainIsolate ??= isolateCandidates - .firstWhereOrNull((isolate) => isolate.ref.name!.contains(':main(')) - ?.isolate; - - // Fallback to selecting the first isolate in the list. - mainIsolate ??= isolateCandidates.first.isolate; - - return mainIsolate; - } -} - @visibleForTesting typedef DetectRootPackageResponse = ({bool success, String? message, Uri? uri});
diff --git a/packages/devtools_shared/lib/src/server/server_api.dart b/packages/devtools_shared/lib/src/server/server_api.dart index f284d7f..854eb5b 100644 --- a/packages/devtools_shared/lib/src/server/server_api.dart +++ b/packages/devtools_shared/lib/src/server/server_api.dart
@@ -23,7 +23,6 @@ import '../extensions/extension_manager.dart'; import '../service/service.dart'; import '../service_utils.dart'; -import '../utils/file_utils.dart'; import 'devtools_store.dart'; import 'file_system.dart'; import 'flutter_store.dart';
diff --git a/packages/devtools_shared/lib/src/service/service.dart b/packages/devtools_shared/lib/src/service/service.dart index 00fadb0..538f1ed 100644 --- a/packages/devtools_shared/lib/src/service/service.dart +++ b/packages/devtools_shared/lib/src/service/service.dart
@@ -55,6 +55,9 @@ // the VM service. uri = convertToWebSocketUrl(serviceProtocolUrl: uri); final ws = WebSocketChannel.connect(uri); + // Await `ws.ready` so connection failures surface here rather than escaping + // as an unhandled `WebSocketChannelException` from the unawaited future. + await ws.ready; final stream = ws.stream.handleError(onError); final service = serviceFactory( inStream: stream,
diff --git a/packages/devtools_shared/lib/src/service_utils.dart b/packages/devtools_shared/lib/src/service_utils.dart index 83ddbc1..a148a93 100644 --- a/packages/devtools_shared/lib/src/service_utils.dart +++ b/packages/devtools_shared/lib/src/service_utils.dart
@@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd. +import 'package:collection/collection.dart'; +import 'package:dtd/dtd.dart'; +import 'package:path/path.dart' as p; +import 'package:vm_service/vm_service.dart'; + +import 'utils/file_utils.dart'; + class RegisteredService { const RegisteredService({required this.service, required this.title}); @@ -85,3 +92,161 @@ if (uri.path.endsWith('/')) return uri; return uri.replace(path: uri.path); } + +/// Extension methods on [VmService] for detecting the package root directory of +/// the connected application. +extension VmServicePackageRootExtension on VmService { + /// Returns the package root directory file URI string for the main isolate, + /// or `null` if it cannot be determined. + /// + /// This should be the directory up the tree from the debugging target that + /// contains the `.dart_tool/package_config.json` file. + /// + /// This method contains special logic for detecting the package root for + /// test targets (i.e., a VM service connection spawned from `dart test` or + /// `flutter test`). This is because the main isolate for test targets is + /// running the test runner, and not the test library itself, so extra work + /// is needed to find the package root of the test target. + Future<String?> rootPackageDirectoryForMainIsolate({ + DartToolingDaemon? dtd, + }) async { + final mainIsolate = await _detectMainIsolate; + final rootLib = mainIsolate?.rootLib; + final rootLibUri = rootLib?.uri; + if (mainIsolate == null || rootLibUri == null) return null; + + final fileUriString = (await lookupResolvedPackageUris(mainIsolate.id!, [ + rootLibUri, + ])).uris?.first; + if (fileUriString == null) return null; + + String? packageRootUriString = await packageRootFromFileUriString( + fileUriString, + dtd: dtd, + ); + + // If a Dart library URI was returned, this may be a test target (i.e. a + // VM service connection spawned from `dart test` or `flutter test`). + if (packageRootUriString.endsWith('.dart')) { + final rootLibId = rootLib?.id; + packageRootUriString = rootLibId != null + ? await _lookupTestTargetPackageRoot( + isolateId: mainIsolate.id!, + rootLibraryId: rootLibId, + dtd: dtd, + ) + : null; + } + + return packageRootUriString; + } + + Future<String?> _lookupTestTargetPackageRoot({ + required String isolateId, + required String rootLibraryId, + required DartToolingDaemon? dtd, + }) async { + try { + final obj = await getObject(isolateId, rootLibraryId); + if (obj is! Library) return null; + + try { + final evalResult = await evaluate( + isolateId, + rootLibraryId, + 'packageConfigLocation', + ); + if (evalResult is InstanceRef) { + var packageConfig = evalResult.valueAsString; + if (evalResult.valueAsStringIsTruncated == true && + evalResult.id != null) { + final fullStringObj = await getObject( + isolateId, + evalResult.id!, + offset: 0, + count: evalResult.length, + ); + if (fullStringObj is Instance) { + packageConfig = fullStringObj.valueAsString; + } + } + final packageConfigSuffix = p.posix.join( + '.dart_tool', + 'package_config.json', + ); + if (packageConfig != null && + packageConfig.endsWith(packageConfigSuffix)) { + return p.posix.dirname(p.posix.dirname(packageConfig)); + } + } + } catch (_) { + // Older versions of package:test don't define `packageConfigLocation`; + // fall back to checking the `test` import prefix below. + } + + final testTargetUri = (obj.dependencies ?? <LibraryDependency>[]) + .firstWhereOrNull((dep) => dep.prefix == 'test') + ?.target + ?.uri; + if (testTargetUri != null) { + final resolvedTargetUri = (await lookupResolvedPackageUris(isolateId, [ + testTargetUri, + ])).uris?.first; + if (resolvedTargetUri != null) { + return await packageRootFromFileUriString( + resolvedTargetUri, + dtd: dtd, + ); + } + } + } catch (_) { + // Ignore errors and return null. + } + return null; + } + + /// Uses heuristics to detect the main isolate. + /// + /// Assumes an isolate is the main isolate if it meets any of the criteria in + /// the following order: + /// + /// 1. The isolate is the main Flutter isolate. + /// 2. The isolate has ':main(' in its name. + /// 3. The isolate is the first in the list of isolates on the VM. + Future<Isolate?> get _detectMainIsolate async { + final isolateRefs = (await getVM()).isolates; + if (isolateRefs == null || isolateRefs.isEmpty) return null; + final isolateCandidates = (await isolateRefs.map((ref) async { + final id = ref.id; + if (id == null) return null; + try { + return (ref: ref, isolate: await getIsolate(id)); + } on SentinelException { + // An isolate may exit between `getVM()` and `getIsolate()`. + return null; + } + }).wait).nonNulls.toList(); + if (isolateCandidates.isEmpty) return null; + + Isolate? mainIsolate; + for (final isolate in isolateCandidates) { + final isFlutterIsolate = (isolate.isolate.extensionRPCs ?? []).any( + (ext) => ext.startsWith('ext.flutter'), + ); + if (isFlutterIsolate) { + mainIsolate = isolate.isolate; + break; + } + } + mainIsolate ??= isolateCandidates + .firstWhereOrNull( + (isolate) => isolate.ref.name?.contains(':main(') ?? false, + ) + ?.isolate; + + // Fallback to selecting the first isolate in the list. + mainIsolate ??= isolateCandidates.first.isolate; + + return mainIsolate; + } +}
diff --git a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart index 044d886..d50505e 100644 --- a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart +++ b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart
@@ -33,7 +33,10 @@ testDtdConnection = await DartToolingDaemon.connect(dtd!.info!.localUri); }); + const fakeRuntimeVmServiceUri = 'ws://127.0.0.1:8181/fake-runtime-app=/ws'; + tearDown(() async { + VmServiceHandler.clearPackageRootsForTesting(); await testDtdConnection?.close(); dtd?.process?.kill(); await dtd?.process?.exitCode; @@ -52,6 +55,10 @@ includeBadExtension: includeBadExtension, includeSpoofedExtension: includeSpoofedExtension, ); + VmServiceHandler.setPackageRootForVmServiceForTesting( + fakeRuntimeVmServiceUri, + Uri.parse(extensionTestManager.runtimeAppRoot), + ); await testDtdConnection!.setIDEWorkspaceRoots(dtd!.info!.secret!, [ extensionTestManager.packagesRootUri, ]); @@ -60,7 +67,7 @@ Future<Response> serveExtensions( ExtensionsManager manager, { bool includeRuntimeRoot = true, - String? packageRootUriOverride, + String? vmServiceUriOverride, }) async { final request = Request( 'post', @@ -69,9 +76,9 @@ host: 'localhost', path: ExtensionsApi.apiServeAvailableExtensions, queryParameters: { - ExtensionsApi.packageRootUriPropertyName: - packageRootUriOverride ?? - (includeRuntimeRoot ? extensionTestManager.runtimeAppRoot : null), + ExtensionsApi.vmServiceUriPropertyName: + vmServiceUriOverride ?? + (includeRuntimeRoot ? fakeRuntimeVmServiceUri : null), }, ), headers: const {devToolsRequestHeader: '1'}, @@ -180,18 +187,68 @@ }, ); + test('returns static extensions with a warning for an uncached unreachable ' + 'loopback vmServiceUri', () async { + await initializeTestDirectory(); + const unreachableVmServiceUri = 'ws://127.0.0.1:1/ws'; + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: unreachableVmServiceUri, + ); + expect(response.statusCode, HttpStatus.ok); + _verifyAllExtensions(extensionsManager, includeRuntime: false); + + final parsedResponse = json.decode(await response.readAsString()) as Map; + final warning = + parsedResponse[ExtensionsApi.extensionsResultWarningPropertyName]; + expect( + warning, + contains('Error detecting project roots ($unreachableVmServiceUri)'), + ); + }); + + test('fails with server error for an uncached unreachable loopback ' + 'vmServiceUri when no static extensions exist', () async { + await initializeTestDirectory(includeDependenciesWithExtensions: false); + const unreachableVmServiceUri = 'ws://127.0.0.1:1/ws'; + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: unreachableVmServiceUri, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + + final parsedResponse = json.decode(await response.readAsString()) as Map; + final error = parsedResponse['error']; + expect( + error, + contains('Error detecting project roots ($unreachableVmServiceUri)'), + ); + }); + test( - 'rejects packageRootUri with non-empty host (Windows UNC path)', + 'rejects non-loopback or invalid vmServiceUri and UNC packageRootUri', () async { await initializeTestDirectory(); - const uncUri = 'file://remotehost/share/app'; - final response = await serveExtensions( - extensionsManager, - packageRootUriOverride: uncUri, - ); - expect(response.statusCode, HttpStatus.badRequest); - expect(extensionsManager.devtoolsExtensions, isEmpty); + for (final invalidVmServiceUri in [ + 'file://remotehost/share/app', + 'file:///Users/me/app', + 'ws://evil.host:8181/ws', + 'not_a_uri', + ]) { + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: invalidVmServiceUri, + ); + expect( + response.statusCode, + HttpStatus.badRequest, + reason: 'Expected $invalidVmServiceUri to be rejected', + ); + expect(extensionsManager.devtoolsExtensions, isEmpty); + } + const uncUri = 'file://remotehost/share/app'; await expectLater( extensionsManager.serveAvailableExtensions(uncUri, <String>[], null), throwsArgumentError,
diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index f090230..c2d2aed 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart
@@ -711,11 +711,46 @@ }); tearDown(() async { + server.VmServiceHandler.clearPackageRootsForTesting(); await app?.kill(); app = null; vmServiceUriString = null; }); + test('does not populate cache when cacheResult is false', () async { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); + expect(vmServiceUri, isNotNull); + late server.DetectRootPackageResponse response; + await runWithRetry( + callback: () async { + response = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri!, + connected: true, + dtd: testDtdConnection!, + cacheResult: false, + ); + if (!response.success) throw Exception('VM not ready'); + }, + maxRetries: 20, + retryDelay: const Duration(milliseconds: 500), + ); + expect(response.success, true); + expect(response.message, isNull); + expect(response.uri, isNotNull); + expect(response.uri!.toFilePath(), endsWith(app!.directory.path)); + + final disconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri!, + connected: false, + dtd: testDtdConnection!, + ); + expect(disconnectResponse, (success: true, message: null, uri: null)); + }); + test('succeeds for a connect event', () async { final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); expect(vmServiceUri, isNotNull); @@ -790,6 +825,21 @@ disconnectResponse.uri!.toFilePath(), endsWith(app!.directory.path), ); + + // Disconnecting again should be a no-op since the cache entry was + // already removed. + final secondDisconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(secondDisconnectResponse, ( + success: true, + message: null, + uri: null, + )); }, ); });
diff --git a/packages/devtools_shared/test/service_utils_test.dart b/packages/devtools_shared/test/service_utils_test.dart index 8222163..84f8b81 100644 --- a/packages/devtools_shared/test/service_utils_test.dart +++ b/packages/devtools_shared/test/service_utils_test.dart
@@ -4,6 +4,7 @@ import 'package:devtools_shared/src/service_utils.dart'; import 'package:test/test.dart'; +import 'package:vm_service/vm_service.dart'; void main() { group('normalizeVmServiceUri', () { @@ -124,4 +125,205 @@ expect(normalizeVmServiceUri('ftp://127.0.0.1:8181/'), isNull); }); }); + + group('VmServicePackageRootExtension', () { + test('fetches full string when packageConfigLocation is truncated', () async { + final longPackageRoot = + 'file:///Users/developer/${List.filled(6, 'very_long_directory_name').join('/')}/my_app'; + final fullPackageConfigUri = + '$longPackageRoot/.dart_tool/package_config.json'; + expect(fullPackageConfigUri.length, greaterThan(128)); + + final fakeVmService = _FakeVmServiceForTestTarget( + fullPackageConfigUri: fullPackageConfigUri, + ); + + final rootDir = await fakeVmService.rootPackageDirectoryForMainIsolate(); + expect(rootDir, equals(longPackageRoot)); + expect(fakeVmService.requestedFullStringOffset, equals(0)); + expect( + fakeVmService.requestedFullStringCount, + equals(fullPackageConfigUri.length), + ); + }); + + test('returns null when test target package root lookup fails', () async { + final fakeVmService = _FakeVmServiceForTestTarget( + fullPackageConfigUri: null, + ); + + final rootDir = await fakeVmService.rootPackageDirectoryForMainIsolate(); + expect(rootDir, isNull); + }); + + test( + 'skips isolates that throw SentinelException during getIsolate', + () async { + final fakeVmService = _FakeVmServiceWithIsolates( + isolateRefs: [ + IsolateRef(id: 'isolates/exited', name: 'exited'), + IsolateRef(id: 'isolates/main', name: 'main'), + ], + isolatesById: { + 'isolates/main': Isolate( + id: 'isolates/main', + name: 'main', + rootLib: LibraryRef( + id: 'libraries/1', + uri: 'file:///Users/developer/my_app/lib/main.dart', + ), + ), + }, + ); + + final rootDir = await fakeVmService + .rootPackageDirectoryForMainIsolate(); + expect(rootDir, equals('file:///Users/developer/my_app')); + }, + ); + + test('returns null when all isolates throw SentinelException', () async { + final fakeVmService = _FakeVmServiceWithIsolates( + isolateRefs: [IsolateRef(id: 'isolates/exited', name: 'exited')], + isolatesById: const {}, + ); + + final rootDir = await fakeVmService.rootPackageDirectoryForMainIsolate(); + expect(rootDir, isNull); + }); + + test('handles isolates with null name without throwing', () async { + final fakeVmService = _FakeVmServiceWithIsolates( + isolateRefs: [IsolateRef(id: 'isolates/unnamed')], + isolatesById: { + 'isolates/unnamed': Isolate( + id: 'isolates/unnamed', + rootLib: LibraryRef( + id: 'libraries/1', + uri: 'file:///Users/developer/my_app/lib/main.dart', + ), + ), + }, + ); + + final rootDir = await fakeVmService.rootPackageDirectoryForMainIsolate(); + expect(rootDir, equals('file:///Users/developer/my_app')); + }); + }); +} + +class _FakeVmServiceForTestTarget extends VmService { + _FakeVmServiceForTestTarget({required this.fullPackageConfigUri}) + : super(const Stream.empty(), (_) {}); + + final String? fullPackageConfigUri; + int? requestedFullStringOffset; + int? requestedFullStringCount; + + static const _isolateId = 'isolates/1'; + static const _rootLibId = 'libraries/1'; + static const _packageConfigStringId = 'objects/package_config_string'; + + @override + Future<VM> getVM() async => VM( + isolates: [IsolateRef(id: _isolateId, name: 'main')], + ); + + @override + Future<Isolate> getIsolate(String isolateId) async => Isolate( + id: _isolateId, + name: 'main', + rootLib: LibraryRef( + id: _rootLibId, + uri: 'file:///tmp/test_runner/main.dart', + ), + ); + + @override + Future<UriList> lookupResolvedPackageUris( + String isolateId, + List<String> uris, { + bool? local, + }) async => UriList(uris: uris); + + @override + Future<Response> evaluate( + String isolateId, + String targetId, + String expression, { + Map<String, String>? scope, + bool? disableBreakpoints, + String? idZoneId, + }) async { + expect(expression, equals('packageConfigLocation')); + final uri = fullPackageConfigUri; + if (uri == null) { + throw RPCError('evaluate', 113, 'Expression compilation error'); + } + return InstanceRef( + id: _packageConfigStringId, + kind: InstanceKind.kString, + valueAsString: uri.substring(0, 128), + valueAsStringIsTruncated: true, + length: uri.length, + ); + } + + @override + Future<Obj> getObject( + String isolateId, + String objectId, { + int? offset, + int? count, + String? idZoneId, + }) async { + if (objectId == _rootLibId) { + return Library(id: _rootLibId, dependencies: const []); + } + if (objectId == _packageConfigStringId) { + requestedFullStringOffset = offset; + requestedFullStringCount = count; + return Instance( + id: _packageConfigStringId, + kind: InstanceKind.kString, + valueAsString: fullPackageConfigUri, + valueAsStringIsTruncated: false, + length: fullPackageConfigUri!.length, + ); + } + throw UnimplementedError('Unexpected getObject($objectId)'); + } +} + +class _FakeVmServiceWithIsolates extends VmService { + _FakeVmServiceWithIsolates({ + required this.isolateRefs, + required this.isolatesById, + }) : super(const Stream.empty(), (_) {}); + + final List<IsolateRef> isolateRefs; + final Map<String, Isolate> isolatesById; + + @override + Future<VM> getVM() async => VM(isolates: isolateRefs); + + @override + Future<Isolate> getIsolate(String isolateId) async { + final isolate = isolatesById[isolateId]; + if (isolate == null) { + throw SentinelException.parse('getIsolate', { + 'type': 'Sentinel', + 'kind': SentinelKind.kCollected, + 'valueAsString': '<collected>', + }); + } + return isolate; + } + + @override + Future<UriList> lookupResolvedPackageUris( + String isolateId, + List<String> uris, { + bool? local, + }) async => UriList(uris: uris); }