From 295cd940d0f63132d6db8c894f3dc1f3e7f507f7 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Tue, 17 Nov 2026 13:45:59 -0800 Subject: [PATCH 01/14] 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`. --- .../lib/src/extensions/extension_service.dart | 34 +++-- .../src/shared/server/_extensions_api.dart | 17 +-- .../sidebar_extensions_controller.dart | 14 +- .../release_notes/NEXT_RELEASE_NOTES.md | 4 + .../extensions/extension_screen_test.dart | 4 +- .../extensions/extension_service_test.dart | 4 +- .../extensions/extension_settings_test.dart | 4 +- packages/devtools_shared/CHANGELOG.md | 4 + .../devtools_shared/lib/src/devtools_api.dart | 7 + .../server/handlers/_devtools_extensions.dart | 42 ++++-- .../lib/src/server/handlers/_vm_service.dart | 126 +++++++++++++++--- .../server/devtools_extensions_api_test.dart | 42 ++++-- 12 files changed, 220 insertions(+), 82 deletions(-) diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 2ba343c34cd..89c3adc4c78 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -34,23 +34,22 @@ typedef DevToolsExtensionsGroup = ({ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - ExtensionService({this.fixedAppRoot, this.ignoreServiceConnection = false}); + ExtensionService({ + this.fixedVmServiceUri, + this.ignoreServiceConnection = false, + }); - /// The fixed (unchanging) root file:// URI for the application this + /// The fixed (unchanging) VM service URI for the application this /// [ExtensionService] will manage DevTools extensions for. /// - /// When null, [_appRoot] will be calculated from the + /// When null, the VM service URI will be retrieved from the /// `serviceConnection.serviceManager`'s currently connected app. - final Uri? fixedAppRoot; + final String? fixedVmServiceUri; /// Whether to ignore the VM service connection for the context of this /// service. final bool ignoreServiceConnection; - /// The root file:// URI for the Dart / Flutter application this - /// [ExtensionService] will manage DevTools extensions for. - Uri? _appRoot; - /// A listenable for the current set of DevTools extensions. /// /// The [DevToolsExtensionsGroup] contains both the List of available @@ -134,8 +133,8 @@ class ExtensionService extends DisposableController // 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) { + // [fixedVmServiceUri] is null). + if (fixedVmServiceUri == null && !ignoreServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, () async { @@ -171,16 +170,14 @@ class ExtensionService extends DisposableController _log.fine('refreshing the ExtensionService'); _reset(); - _appRoot = null; - if (fixedAppRoot != null) { - _appRoot = fixedAppRoot; + String? vmServiceUri; + if (fixedVmServiceUri != null) { + vmServiceUri = fixedVmServiceUri; } else if (!ignoreServiceConnection && serviceConnection.serviceManager.connectedState.value.connected && serviceConnection.serviceManager.isolateManager.mainIsolate.value != null) { - _appRoot = await serviceConnection.serviceManager.connectedAppPackageRoot( - dtdManager, - ); + vmServiceUri = serviceConnection.serviceManager.serviceUri; } // TODO(kenz): gracefully handle app connections / disconnects when there @@ -188,7 +185,9 @@ class ExtensionService extends DisposableController // 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 +335,6 @@ class ExtensionService extends DisposableController 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 290abeacd49..faa39eee968 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 @@ part of 'server.dart'; /// 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> 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> refreshAvailableExtensions({ + String? vmServiceUri, +}) async { + _log.fine('refreshAvailableExtensions for vmServiceUri: $vmServiceUri'); if (debugDevToolsExtensions) { return debugHandleRefreshAvailableExtensions( - includeRuntime: appRoot != null, + includeRuntime: vmServiceUri != null && vmServiceUri.isNotEmpty, ); } 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 1dc6e7e63dd..fe63c052c61 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 @@ -141,9 +141,12 @@ class SidebarDevToolsExtensionsController extends DisposableController Future _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(fileUri, vmServiceUri: vmServiceUri); } } } @@ -162,14 +165,17 @@ class SidebarDevToolsExtensionsController extends DisposableController // 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 _detectExtensions(Uri? projectRootUri) async { + Future _detectExtensions( + Uri? projectRootUri, { + String? vmServiceUri, + }) 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, + fixedVmServiceUri: vmServiceUri, ignoreServiceConnection: true, ); assert( diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 1dfdcb637d3..aeee7c24e84 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 @@ TODO: Remove this section if there are not any updates. * 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. + [#TODO](https://github.com/flutter/devtools/pull/TODO) ## 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 036c5985fa0..ec26155d7fa 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 @@ void main() { 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 fea1cc26ace..b1e4cc228cf 100644 --- a/packages/devtools_app/test/extensions/extension_service_test.dart +++ b/packages/devtools_app/test/extensions/extension_service_test.dart @@ -36,7 +36,7 @@ void main() { test('initialize when connected', () 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); @@ -87,7 +87,7 @@ void main() { 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 9e172184c88..0ed74c1b0b0 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 @@ void main() { 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_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 50bc259549b..5c7c7925deb 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -35,6 +35,10 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens 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`. # 14.0.0 diff --git a/packages/devtools_shared/lib/src/devtools_api.dart b/packages/devtools_shared/lib/src/devtools_api.dart index c3d9a7e393f..f50595d077b 100644 --- a/packages/devtools_shared/lib/src/devtools_api.dart +++ b/packages/devtools_shared/lib/src/devtools_api.dart @@ -112,11 +112,18 @@ abstract class ExtensionsApi { static const apiServeAvailableExtensions = '${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 af2b3f33957..b7bf68e58ea 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 @@ extension _ExtensionsApiHandler on Never { DtdInfo? dtd, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( - [ExtensionsApi.packageRootUriPropertyName], + const [ExtensionsApi.vmServiceUriPropertyName], queryParams: queryParams, api: api, requestName: ExtensionsApi.apiServeAvailableExtensions, @@ -21,19 +21,39 @@ extension _ExtensionsApiHandler on Never { if (missingRequiredParams != null) return missingRequiredParams; final logs = []; - 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 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, + ); + if (!detectRootResponse.success) { + return api.serverError(detectRootResponse.message, logs); + } + rootFileUriString = detectRootResponse.uri?.toString(); + } catch (e) { + return api.serverError('$e', logs); + } finally { + await dartToolingDaemon?.close(); + } } final result = {}; 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 94fd867e199..15aa256175e 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -18,6 +18,23 @@ extension VmServiceHandler on Never { /// never be used. static final _packageRootsForVmServiceConnections = {}; + /// Registers a cached [rootPackageUri] for [vmServiceUriAsString] in + /// [_packageRootsForVmServiceConnections] for testing. + @visibleForTesting + static void setPackageRootForVmServiceForTesting( + String vmServiceUriAsString, + Uri rootPackageUri, + ) { + _packageRootsForVmServiceConnections[vmServiceUriAsString] = rootPackageUri; + } + + /// Clears all cached package roots in [_packageRootsForVmServiceConnections] + /// for testing. + @visibleForTesting + static void clearPackageRootsForTesting() { + _packageRootsForVmServiceConnections.clear(); + } + static Future handleNotifyForVmServiceConnection( ServerApi api, Map queryParams, @@ -110,13 +127,16 @@ extension VmServiceHandler on Never { required String vmServiceUriAsString, required Uri vmServiceUri, required bool connected, - required DartToolingDaemon dtd, + required DartToolingDaemon? dtd, }) async { 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[vmServiceUriAsString] ?? + _packageRootsForVmServiceConnections[vmServiceUri.toString()]; + if (cachedRoot != null) { + return (success: true, message: null, uri: cachedRoot); + } VmService? vmService; try { @@ -139,6 +159,8 @@ extension VmServiceHandler on Never { rootPackageUri = Uri.parse(root); _packageRootsForVmServiceConnections[vmServiceUriAsString] = rootPackageUri; + _packageRootsForVmServiceConnections[vmServiceUri.toString()] = + rootPackageUri; } catch (e) { return ( success: false, @@ -151,7 +173,8 @@ extension VmServiceHandler on Never { } } else { final cachedRootForVmService = - _packageRootsForVmServiceConnections[vmServiceUriAsString]; + _packageRootsForVmServiceConnections[vmServiceUriAsString] ?? + _packageRootsForVmServiceConnections[vmServiceUri.toString()]; if (cachedRootForVmService == null) { // If there is no root to remove, there is nothing for us to do. return (success: true, message: null, uri: null); @@ -183,23 +206,90 @@ extension VmServiceHandler on Never { extension on VmService { Future rootPackageDirectoryForMainIsolate( - DartToolingDaemon dtd, + DartToolingDaemon? dtd, ) async { - final fileUriString = await _rootLibraryForMainIsolate; - return fileUriString != null - ? await packageRootFromFileUriString(fileUriString, dtd: dtd) - : null; - } - - Future get _rootLibraryForMainIsolate async { final mainIsolate = await _detectMainIsolate; - final rootLib = mainIsolate.rootLib?.uri; - if (rootLib == null) return null; + final rootLib = mainIsolate.rootLib; + final rootLibUri = rootLib?.uri; + if (rootLibUri == null) return null; - final fileUriAsString = (await lookupResolvedPackageUris(mainIsolate.id!, [ - rootLib, + final fileUriString = (await lookupResolvedPackageUris(mainIsolate.id!, [ + rootLibUri, ])).uris?.first; - return fileUriAsString; + if (fileUriString == null) return null; + + var 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') && rootLib?.id != null) { + packageRootUriString = + (await _lookupTestTargetPackageRoot( + isolateId: mainIsolate.id!, + rootLibraryId: rootLib!.id!, + dtd: dtd, + )) ?? + packageRootUriString; + } + + return packageRootUriString; + } + + Future _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) { + final packageConfig = evalResult.valueAsString; + final packageConfigSuffix = p.posix.join( + '.dart_tool', + 'package_config.json', + ); + if (packageConfig != null && + packageConfig.endsWith(packageConfigSuffix)) { + return packageConfig.substring( + 0, + packageConfig.length - packageConfigSuffix.length - 1, + ); + } + } + } catch (_) { + // Fall back to import prefix lookup if evaluation fails. + } + + final testTargetUri = (obj.dependencies ?? []) + .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 (_) { + // Fail gracefully if the test target lookup fails. + } + return null; } /// Uses heuristics to detect the main isolate. 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 044d88620bd..b7bc8555327 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 @@ void main() { 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 @@ void main() { includeBadExtension: includeBadExtension, includeSpoofedExtension: includeSpoofedExtension, ); + VmServiceHandler.setPackageRootForVmServiceForTesting( + fakeRuntimeVmServiceUri, + Uri.parse(extensionTestManager.runtimeAppRoot), + ); await testDtdConnection!.setIDEWorkspaceRoots(dtd!.info!.secret!, [ extensionTestManager.packagesRootUri, ]); @@ -60,7 +67,7 @@ void main() { Future serveExtensions( ExtensionsManager manager, { bool includeRuntimeRoot = true, - String? packageRootUriOverride, + String? vmServiceUriOverride, }) async { final request = Request( 'post', @@ -69,9 +76,9 @@ void main() { host: 'localhost', path: ExtensionsApi.apiServeAvailableExtensions, queryParameters: { - ExtensionsApi.packageRootUriPropertyName: - packageRootUriOverride ?? - (includeRuntimeRoot ? extensionTestManager.runtimeAppRoot : null), + ExtensionsApi.vmServiceUriPropertyName: + vmServiceUriOverride ?? + (includeRuntimeRoot ? fakeRuntimeVmServiceUri : null), }, ), headers: const {devToolsRequestHeader: '1'}, @@ -181,17 +188,28 @@ void main() { ); 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, [], null), throwsArgumentError, From 0f80ea89423ab3aceb288b1b8e582175dcefbe0b Mon Sep 17 00:00:00 2001 From: John Ryan Date: Wed, 18 Nov 2026 17:07:42 -0800 Subject: [PATCH 02/14] Update CHANGELOG --- packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index aeee7c24e84..9bf254debd6 100644 --- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md +++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md @@ -117,7 +117,7 @@ TODO: Remove this section if there are not any updates. * 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. - [#TODO](https://github.com/flutter/devtools/pull/TODO) + [#10097](https://github.com/flutter/devtools/pull/10097) ## Advanced developer mode updates From 6e91d1e7fa097a58763ee76568632c96a239d4eb Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 19 Nov 2026 09:28:06 -0800 Subject: [PATCH 03/14] Apply batched suggestions from code review Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../devtools_shared/lib/src/server/handlers/_vm_service.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 15aa256175e..364a7b1c5f0 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -225,7 +225,9 @@ extension on VmService { // 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') && rootLib?.id != null) { + if (packageRootUriString != null && + packageRootUriString.endsWith('.dart') && + rootLib?.id != null) { packageRootUriString = (await _lookupTestTargetPackageRoot( isolateId: mainIsolate.id!, From a42714cc07a9444dfa0e8edab402afa62bcd7388 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 19 Nov 2026 09:28:48 -0800 Subject: [PATCH 04/14] Apply suggestion from code review --- .../devtools_shared/lib/src/server/handlers/_vm_service.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) 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 364a7b1c5f0..77b5d626954 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -263,10 +263,7 @@ extension on VmService { ); if (packageConfig != null && packageConfig.endsWith(packageConfigSuffix)) { - return packageConfig.substring( - 0, - packageConfig.length - packageConfigSuffix.length - 1, - ); + return p.posix.dirname(p.posix.dirname(packageConfig)); } } } catch (_) { From 227e336601b7b4a4503038d08f65709798b71bc5 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 19 Nov 2026 11:07:54 -0800 Subject: [PATCH 05/14] Fix analyzer warning --- .../lib/src/server/handlers/_vm_service.dart | 4 +-- pubspec.lock | 32 +++++++++---------- 2 files changed, 17 insertions(+), 19 deletions(-) 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 77b5d626954..3d88baf085a 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -225,9 +225,7 @@ extension on VmService { // 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 != null && - packageRootUriString.endsWith('.dart') && - rootLib?.id != null) { + if (packageRootUriString.endsWith('.dart') && rootLib?.id != null) { packageRootUriString = (await _lookupTestTargetPackageRoot( isolateId: mainIsolate.id!, diff --git a/pubspec.lock b/pubspec.lock index a5a55b68152..4f8220ac588 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,18 +5,18 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: "9bfb8122e2505aca17219018593c384a87166cfe860d11c7ae927e7f978eb05f" + sha256: "1b0e6a07425a3e460666e88bf1c949ccc7bb0116ad562ce94a1eca60fe820725" url: "https://pub.dev" source: hosted - version: "110.0.0" + version: "103.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: "74c36179c4de542efea24c9dff78324375e4b118a2c1e14e8a7659f457947f8d" + sha256: "61c04d0c1bfed555c681ea079519933f071a5a026578ff73c4ff0df2d3462e5e" url: "https://pub.dev" source: hosted - version: "14.6.0" + version: "13.3.0" archive: dependency: transitive description: @@ -85,10 +85,10 @@ packages: dependency: "direct dev" description: name: build_runner - sha256: "6feadd32d90a68253c1f7b4fcff76adb4b41ad32a53f8bad835dc65f01ac9dc5" + sha256: "894c243f6bc32015fec466ce30a6925bd537a77a426ee5bf481120477eb3de67" url: "https://pub.dev" source: hosted - version: "2.16.2" + version: "2.16.1" built_collection: dependency: transitive description: @@ -615,10 +615,10 @@ packages: dependency: transitive description: name: package_config - sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "2.2.0" path: dependency: transitive description: @@ -787,10 +787,10 @@ packages: dependency: transitive description: name: source_gen - sha256: "833ea7d15b5be79949d3d6c077da0267a0bd93c16897b36a771395a91e63086e" + sha256: a603f1fb984a7391ae5978d1b92bfaaa08b350dca5c825256f925818f7943bf5 url: "https://pub.dev" source: hosted - version: "4.3.1" + version: "4.2.4" source_map_stack_trace: dependency: transitive description: @@ -891,26 +891,26 @@ packages: dependency: transitive description: name: test - sha256: "44b2fccf4407bcdb5e105c064c5d6b5e2a640c87761f8b03cdce8cf532d98cfa" + sha256: de5d145b0afff7921e5e788a880f52d7e5f3ae24068a202f6fd3b58e4ba26323 url: "https://pub.dev" source: hosted - version: "1.33.0" + version: "1.32.0" test_api: dependency: transitive description: name: test_api - sha256: "47481c58bb92d0b1d218f0510ff5647e768f8e1256d07077a151fb520923b51d" + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" url: "https://pub.dev" source: hosted - version: "0.7.15" + version: "0.7.14" test_core: dependency: transitive description: name: test_core - sha256: "9dec4c178bd61493e1cd2060ffe701fcb61c43da2493e99590fb1b0cc82eb4af" + sha256: "80f3fb49087454e07e7e07c67578cfdd156c8c3a5227d8b3f47c7b2d019c2e93" url: "https://pub.dev" source: hosted - version: "0.6.21" + version: "0.6.20" typed_data: dependency: transitive description: From f8a241409aad6bd03cf139b25022c6022c2f4050 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 10:35:51 -0800 Subject: [PATCH 06/14] Refactor ExtensionService to use named constructors for each situation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../lib/src/extensions/extension_service.dart | 49 ++++++++++++------- .../sidebar_extensions_controller.dart | 19 ++++--- .../extensions/extension_screen_test.dart | 2 +- .../extensions/extension_service_test.dart | 14 ++---- .../extensions/extension_settings_test.dart | 2 +- 5 files changed, 49 insertions(+), 37 deletions(-) diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 89c3adc4c78..06f2968ece3 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -34,21 +34,35 @@ typedef DevToolsExtensionsGroup = ({ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - ExtensionService({ - this.fixedVmServiceUri, - this.ignoreServiceConnection = false, - }); + /// Creates an [ExtensionService] that detects DevTools extensions for the + /// currently connected VM service (via `serviceConnection.serviceManager`) + /// as well as static extensions from DTD project roots. + ExtensionService() + : _fixedVmServiceUri = null, + _useGlobalServiceConnection = true; + + /// Creates an [ExtensionService] that detects DevTools extensions for a + /// specific, fixed [vmServiceUri] as well as static extensions from DTD + /// project roots, without listening to the global `serviceConnection`. + ExtensionService.forVmService(String vmServiceUri) + : _fixedVmServiceUri = vmServiceUri, + _useGlobalServiceConnection = false; + + /// Creates an [ExtensionService] that only detects static DevTools + /// extensions for the IDE workspace (via DTD project roots), without using + /// any VM service connection. + ExtensionService.forWorkspace() + : _fixedVmServiceUri = null, + _useGlobalServiceConnection = false; /// The fixed (unchanging) VM service URI for the application this - /// [ExtensionService] will manage DevTools extensions for. - /// - /// When null, the VM service URI will be retrieved from the - /// `serviceConnection.serviceManager`'s currently connected app. - final String? fixedVmServiceUri; + /// [ExtensionService] will manage DevTools extensions for, if constructed via + /// [ExtensionService.forVmService]. + final String? _fixedVmServiceUri; - /// Whether to ignore the VM service connection for the context of this - /// service. - final bool ignoreServiceConnection; + /// Whether this service should track the global + /// `serviceConnection.serviceManager` for the currently connected app. + final bool _useGlobalServiceConnection; /// A listenable for the current set of DevTools extensions. /// @@ -132,9 +146,8 @@ class ExtensionService extends DisposableController cancelListeners(); // We only need to add VM service manager related listeners when we are - // interacting with the currently connected app (i.e. when - // [fixedVmServiceUri] is null). - if (fixedVmServiceUri == null && !ignoreServiceConnection) { + // tracking the currently connected app via the global service connection. + if (_useGlobalServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, () async { @@ -171,9 +184,9 @@ class ExtensionService extends DisposableController _reset(); String? vmServiceUri; - if (fixedVmServiceUri != null) { - vmServiceUri = fixedVmServiceUri; - } else if (!ignoreServiceConnection && + if (_fixedVmServiceUri != null) { + vmServiceUri = _fixedVmServiceUri; + } else if (_useGlobalServiceConnection && serviceConnection.serviceManager.connectedState.value.connected && serviceConnection.serviceManager.isolateManager.mainIsolate.value != null) { 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 fe63c052c61..1fc1a1330a3 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 @@ -169,15 +169,18 @@ class SidebarDevToolsExtensionsController extends DisposableController Uri? projectRootUri, { String? vmServiceUri, }) async { - final extensionService = projectRootUri == null + 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 ? - // 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( - fixedVmServiceUri: vmServiceUri, - ignoreServiceConnection: true, - ); + // A null [vmServiceUri] indicates a static-only extensions lookup for + // the workspace, rather than a lookup for a specific debug session. + ExtensionService.forWorkspace() + : ExtensionService.forVmService(vmServiceUri); assert( !_extensionServiceByRootUri.containsKey(projectRootUri), 'The initialization for the ExtensionService for root uri ' diff --git a/packages/devtools_app/test/extensions/extension_screen_test.dart b/packages/devtools_app/test/extensions/extension_screen_test.dart index ec26155d7fa..7624c0c5b17 100644 --- a/packages/devtools_app/test/extensions/extension_screen_test.dart +++ b/packages/devtools_app/test/extensions/extension_screen_test.dart @@ -36,7 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), + ExtensionService.forVmService('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 b1e4cc228cf..a956c9f7910 100644 --- a/packages/devtools_app/test/extensions/extension_service_test.dart +++ b/packages/devtools_app/test/extensions/extension_service_test.dart @@ -34,10 +34,8 @@ void main() { resetDevToolsExtensionEnabledStates(); }); - test('initialize when connected', () async { - final service = ExtensionService( - fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', - ); + test('initialize with forVmService', () async { + final service = ExtensionService.forVmService('ws://127.0.0.1:8181/ws'); expect(service.availableExtensions, isEmpty); expect(service.staticExtensions, isEmpty); expect(service.runtimeExtensions, isEmpty); @@ -61,12 +59,12 @@ void main() { 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); @@ -86,9 +84,7 @@ void main() { }); test('setExtensionEnabledState', () async { - final service = ExtensionService( - fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', - ); + final service = ExtensionService.forVmService('ws://127.0.0.1:8181/ws'); await service.initialize(); expect(service.staticExtensions.length, 4); expect(service.runtimeExtensions.length, 3); diff --git a/packages/devtools_app/test/extensions/extension_settings_test.dart b/packages/devtools_app/test/extensions/extension_settings_test.dart index 0ed74c1b0b0..2103bb9e226 100644 --- a/packages/devtools_app/test/extensions/extension_settings_test.dart +++ b/packages/devtools_app/test/extensions/extension_settings_test.dart @@ -36,7 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), + ExtensionService.forVmService('ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4); From c00e98e24670882c20813c087db8f9793517edb8 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 12:53:50 -0800 Subject: [PATCH 07/14] Remove unneeded check for mainIsolate.value != null MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _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. --- .../devtools_app/lib/src/extensions/extension_service.dart | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 06f2968ece3..e7a3f18af79 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -187,9 +187,7 @@ class ExtensionService extends DisposableController if (_fixedVmServiceUri != null) { vmServiceUri = _fixedVmServiceUri; } else if (_useGlobalServiceConnection && - serviceConnection.serviceManager.connectedState.value.connected && - serviceConnection.serviceManager.isolateManager.mainIsolate.value != - null) { + serviceConnection.serviceManager.connectedState.value.connected) { vmServiceUri = serviceConnection.serviceManager.serviceUri; } From acaa4d106998fd9fe0545d8c8647c8b90fc0ce79 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 12:55:50 -0800 Subject: [PATCH 08/14] use isNullOrEmpty extension method --- .../devtools_app/lib/src/shared/server/_extensions_api.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 faa39eee968..b8cc6b9265d 100644 --- a/packages/devtools_app/lib/src/shared/server/_extensions_api.dart +++ b/packages/devtools_app/lib/src/shared/server/_extensions_api.dart @@ -13,7 +13,7 @@ Future> refreshAvailableExtensions({ _log.fine('refreshAvailableExtensions for vmServiceUri: $vmServiceUri'); if (debugDevToolsExtensions) { return debugHandleRefreshAvailableExtensions( - includeRuntime: vmServiceUri != null && vmServiceUri.isNotEmpty, + includeRuntime: !vmServiceUri.isNullOrEmpty, ); } if (isDevToolsServerAvailable) { From 5351721684c8789d634a18fa07ff6eb8c3a124e0 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 12:58:27 -0800 Subject: [PATCH 09/14] Make `_detectExtensions` take two optional parameters --- .../devtools/sidebar_extensions_controller.dart | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) 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 1fc1a1330a3..ea3634f858c 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,9 +133,9 @@ class SidebarDevToolsExtensionsController extends DisposableController ); } - // Pass a null project root URI to initialize the set of extensions - // available for the entire workspace. - await _detectExtensions(null); + // Omit [projectRootUri] and [vmServiceUri] to initialize the set of + // extensions available for the entire workspace. + await _detectExtensions(); } Future _initExtensionsForDebugSessions() async { @@ -146,7 +146,10 @@ class SidebarDevToolsExtensionsController extends DisposableController vmServiceUri != null && !_searchedProjectRoots.contains(fileUri)) { _searchedProjectRoots.add(fileUri); - await _detectExtensions(fileUri, vmServiceUri: vmServiceUri); + await _detectExtensions( + projectRootUri: fileUri, + vmServiceUri: vmServiceUri, + ); } } } @@ -165,8 +168,8 @@ class SidebarDevToolsExtensionsController extends DisposableController // 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 _detectExtensions( - Uri? projectRootUri, { + Future _detectExtensions({ + Uri? projectRootUri, String? vmServiceUri, }) async { assert( From 3a7ea01993ee4c0ecba63043c061fcf6f323b423 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 13:00:40 -0800 Subject: [PATCH 10/14] Revert changes to pubspec.lock --- pubspec.lock | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 4f8220ac588..a5a55b68152 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,18 +5,18 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: "1b0e6a07425a3e460666e88bf1c949ccc7bb0116ad562ce94a1eca60fe820725" + sha256: "9bfb8122e2505aca17219018593c384a87166cfe860d11c7ae927e7f978eb05f" url: "https://pub.dev" source: hosted - version: "103.0.0" + version: "110.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: "61c04d0c1bfed555c681ea079519933f071a5a026578ff73c4ff0df2d3462e5e" + sha256: "74c36179c4de542efea24c9dff78324375e4b118a2c1e14e8a7659f457947f8d" url: "https://pub.dev" source: hosted - version: "13.3.0" + version: "14.6.0" archive: dependency: transitive description: @@ -85,10 +85,10 @@ packages: dependency: "direct dev" description: name: build_runner - sha256: "894c243f6bc32015fec466ce30a6925bd537a77a426ee5bf481120477eb3de67" + sha256: "6feadd32d90a68253c1f7b4fcff76adb4b41ad32a53f8bad835dc65f01ac9dc5" url: "https://pub.dev" source: hosted - version: "2.16.1" + version: "2.16.2" built_collection: dependency: transitive description: @@ -615,10 +615,10 @@ packages: dependency: transitive description: name: package_config - sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "3.0.0" path: dependency: transitive description: @@ -787,10 +787,10 @@ packages: dependency: transitive description: name: source_gen - sha256: a603f1fb984a7391ae5978d1b92bfaaa08b350dca5c825256f925818f7943bf5 + sha256: "833ea7d15b5be79949d3d6c077da0267a0bd93c16897b36a771395a91e63086e" url: "https://pub.dev" source: hosted - version: "4.2.4" + version: "4.3.1" source_map_stack_trace: dependency: transitive description: @@ -891,26 +891,26 @@ packages: dependency: transitive description: name: test - sha256: de5d145b0afff7921e5e788a880f52d7e5f3ae24068a202f6fd3b58e4ba26323 + sha256: "44b2fccf4407bcdb5e105c064c5d6b5e2a640c87761f8b03cdce8cf532d98cfa" url: "https://pub.dev" source: hosted - version: "1.32.0" + version: "1.33.0" test_api: dependency: transitive description: name: test_api - sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" + sha256: "47481c58bb92d0b1d218f0510ff5647e768f8e1256d07077a151fb520923b51d" url: "https://pub.dev" source: hosted - version: "0.7.14" + version: "0.7.15" test_core: dependency: transitive description: name: test_core - sha256: "80f3fb49087454e07e7e07c67578cfdd156c8c3a5227d8b3f47c7b2d019c2e93" + sha256: "9dec4c178bd61493e1cd2060ffe701fcb61c43da2493e99590fb1b0cc82eb4af" url: "https://pub.dev" source: hosted - version: "0.6.20" + version: "0.6.21" typed_data: dependency: transitive description: From 5fe497d6a5b319613b06de32ad62f04466fa9ac7 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 13:40:09 -0800 Subject: [PATCH 11/14] 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`. --- packages/devtools_app_shared/CHANGELOG.md | 2 + .../lib/src/service/service_manager.dart | 120 +------------- packages/devtools_shared/CHANGELOG.md | 2 + .../server/handlers/_devtools_extensions.dart | 31 ++-- .../lib/src/server/handlers/_vm_service.dart | 148 +++--------------- .../lib/src/server/server_api.dart | 1 - .../lib/src/service/service.dart | 1 + .../lib/src/service_utils.dart | 141 +++++++++++++++++ .../server/devtools_extensions_api_test.dart | 39 +++++ .../test/server/general_api_test.dart | 15 ++ 10 files changed, 247 insertions(+), 253 deletions(-) diff --git a/packages/devtools_app_shared/CHANGELOG.md b/packages/devtools_app_shared/CHANGELOG.md index ee3e1246427..f12fddc7fd5 100644 --- a/packages/devtools_app_shared/CHANGELOG.md +++ b/packages/devtools_app_shared/CHANGELOG.md @@ -19,6 +19,8 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens 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 da70413c75a..394647715ac 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,19 @@ class ServiceManager { /// `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 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 packageRootUriString = await service + ?.rootPackageDirectoryForMainIsolate(dtd: dtdManager.connection.value); + _log.fine('[connectedAppPackageRoot] package root: $packageRootUriString'); return packageRootUriString == null ? null : Uri.parse(packageRootUriString); } - Future _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 _lookupPackageRootByImportPrefix( - Library rootLibrary, - DTDManager dtdManager, - ) async { - final testTargetFileUriString = - (rootLibrary.dependencies ?? []) - .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 _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_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 5c7c7925deb..383137873c1 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -39,6 +39,8 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens `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/server/handlers/_devtools_extensions.dart b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart index b7bf68e58ea..39ffa3d839f 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -21,6 +21,7 @@ extension _ExtensionsApiHandler on Never { if (missingRequiredParams != null) return missingRequiredParams; final logs = []; + final warnings = []; final vmServiceUriString = queryParams[ExtensionsApi.vmServiceUriPropertyName]; String? rootFileUriString; @@ -46,26 +47,33 @@ extension _ExtensionsApiHandler on Never { dtd: dartToolingDaemon, ); if (!detectRootResponse.success) { - return api.serverError(detectRootResponse.message, logs); + warnings.add( + detectRootResponse.message ?? + 'Failed to detect root package for VM service ' + '($vmServiceUriString).', + ); + } else { + rootFileUriString = detectRootResponse.uri?.toString(); } - rootFileUriString = detectRootResponse.uri?.toString(); } catch (e) { - return api.serverError('$e', logs); + warnings.add('$e'); } finally { await dartToolingDaemon?.close(); } } + final rootDetectionFailed = warnings.isNotEmpty; final result = {}; /// 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), @@ -82,14 +90,19 @@ extension _ExtensionsApiHandler on Never { } 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 3d88baf085a..9f35e8b3800 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -25,7 +25,16 @@ extension VmServiceHandler on Never { String vmServiceUriAsString, Uri rootPackageUri, ) { - _packageRootsForVmServiceConnections[vmServiceUriAsString] = rootPackageUri; + final normalizedUri = normalizeVmServiceUri(vmServiceUriAsString); + if (normalizedUri == null) { + throw ArgumentError.value( + vmServiceUriAsString, + 'vmServiceUriAsString', + 'Cannot normalize VM service URI', + ); + } + _packageRootsForVmServiceConnections[normalizedUri.toString()] = + rootPackageUri; } /// Clears all cached package roots in [_packageRootsForVmServiceConnections] @@ -129,11 +138,11 @@ extension VmServiceHandler on Never { required bool connected, required DartToolingDaemon? dtd, }) async { + final normalizedUriAsString = vmServiceUri.toString(); final Uri rootPackageUri; if (connected) { final cachedRoot = - _packageRootsForVmServiceConnections[vmServiceUriAsString] ?? - _packageRootsForVmServiceConnections[vmServiceUri.toString()]; + _packageRootsForVmServiceConnections[normalizedUriAsString]; if (cachedRoot != null) { return (success: true, message: null, uri: cachedRoot); } @@ -146,7 +155,9 @@ extension VmServiceHandler on Never { serviceFactory: VmService.defaultFactory, ); - final root = await vmService.rootPackageDirectoryForMainIsolate(dtd); + final root = await vmService.rootPackageDirectoryForMainIsolate( + dtd: dtd, + ); if (root == null) { return ( success: false, @@ -157,9 +168,7 @@ extension VmServiceHandler on Never { ); } rootPackageUri = Uri.parse(root); - _packageRootsForVmServiceConnections[vmServiceUriAsString] = - rootPackageUri; - _packageRootsForVmServiceConnections[vmServiceUri.toString()] = + _packageRootsForVmServiceConnections[normalizedUriAsString] = rootPackageUri; } catch (e) { return ( @@ -172,9 +181,8 @@ extension VmServiceHandler on Never { vmService = null; } } else { - final cachedRootForVmService = - _packageRootsForVmServiceConnections[vmServiceUriAsString] ?? - _packageRootsForVmServiceConnections[vmServiceUri.toString()]; + 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); @@ -204,125 +212,5 @@ extension VmServiceHandler on Never { } } -extension on VmService { - Future rootPackageDirectoryForMainIsolate( - DartToolingDaemon? dtd, - ) async { - final mainIsolate = await _detectMainIsolate; - final rootLib = mainIsolate.rootLib; - final rootLibUri = rootLib?.uri; - if (rootLibUri == null) return null; - - final fileUriString = (await lookupResolvedPackageUris(mainIsolate.id!, [ - rootLibUri, - ])).uris?.first; - if (fileUriString == null) return null; - - var 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') && rootLib?.id != null) { - packageRootUriString = - (await _lookupTestTargetPackageRoot( - isolateId: mainIsolate.id!, - rootLibraryId: rootLib!.id!, - dtd: dtd, - )) ?? - packageRootUriString; - } - - return packageRootUriString; - } - - Future _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) { - final packageConfig = evalResult.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 (_) { - // Fall back to import prefix lookup if evaluation fails. - } - - final testTargetUri = (obj.dependencies ?? []) - .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 (_) { - // Fail gracefully if the test target lookup fails. - } - 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 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 f284d7f281f..854eb5bb9cd 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_enablement.dart'; 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 00fadb001e5..c290eaeb69e 100644 --- a/packages/devtools_shared/lib/src/service/service.dart +++ b/packages/devtools_shared/lib/src/service/service.dart @@ -55,6 +55,7 @@ Future _connectWithWebSocket({ // the VM service. uri = convertToWebSocketUrl(serviceProtocolUrl: uri); final ws = WebSocketChannel.connect(uri); + 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 83ddbc1e2af..ef428c33922 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,137 @@ Uri? normalizeVmServiceUri(String value) { 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 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; + + var 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') && rootLib?.id != null) { + packageRootUriString = + (await _lookupTestTargetPackageRoot( + isolateId: mainIsolate.id!, + rootLibraryId: rootLib!.id!, + dtd: dtd, + )) ?? + packageRootUriString; + } + + return packageRootUriString; + } + + Future _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) { + final packageConfig = evalResult.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 (_) { + // Fall back to import prefix lookup if evaluation fails. + } + + final testTargetUri = (obj.dependencies ?? []) + .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 (_) { + // Fail gracefully if the test target lookup fails. + } + 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 get _detectMainIsolate async { + final isolateRefs = (await getVM()).isolates; + if (isolateRefs == null || isolateRefs.isEmpty) return null; + 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; + } +} 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 b7bc8555327..d50505effc2 100644 --- a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart +++ b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart @@ -187,6 +187,45 @@ void main() { }, ); + 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 non-loopback or invalid vmServiceUri and UNC packageRootUri', () async { diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index f0902307d63..85b7ecbcbe6 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -790,6 +790,21 @@ void main() { disconnectResponse.uri!.toFilePath(), endsWith(app!.directory.path), ); + + // A subsequent disconnect should find no cached entry because the + // first disconnect removed it from the cache. + final secondDisconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(secondDisconnectResponse, ( + success: true, + message: null, + uri: null, + )); }, ); }); From 450a29db77a7240bdf04433249df43ae0dc9147a Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 14:14:35 -0800 Subject: [PATCH 12/14] Simplify ExtensionService constructors --- .../lib/src/extensions/extension_service.dart | 35 +++++++------------ .../sidebar_extensions_controller.dart | 6 ++-- .../extensions/extension_screen_test.dart | 2 +- .../extensions/extension_service_test.dart | 10 ++++-- .../extensions/extension_settings_test.dart | 2 +- 5 files changed, 25 insertions(+), 30 deletions(-) diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index e7a3f18af79..5497e49afef 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -34,34 +34,26 @@ typedef DevToolsExtensionsGroup = ({ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - /// Creates an [ExtensionService] that detects DevTools extensions for the - /// currently connected VM service (via `serviceConnection.serviceManager`) - /// as well as static extensions from DTD project roots. - ExtensionService() - : _fixedVmServiceUri = null, - _useGlobalServiceConnection = true; - - /// Creates an [ExtensionService] that detects DevTools extensions for a - /// specific, fixed [vmServiceUri] as well as static extensions from DTD - /// project roots, without listening to the global `serviceConnection`. - ExtensionService.forVmService(String vmServiceUri) - : _fixedVmServiceUri = vmServiceUri, - _useGlobalServiceConnection = false; + /// Creates an [ExtensionService] that detects both runtime and static + /// DevTools extensions. + /// + /// Pass [fixedVmServiceUri] to detect runtime extensions for a specific VM + /// service instead of listening to `serviceConnection.serviceManager`. + ExtensionService({String? fixedVmServiceUri}) + : _fixedVmServiceUri = fixedVmServiceUri, + _useGlobalServiceConnection = fixedVmServiceUri == null; /// Creates an [ExtensionService] that only detects static DevTools - /// extensions for the IDE workspace (via DTD project roots), without using - /// any VM service connection. + /// extensions for the IDE workspace. ExtensionService.forWorkspace() : _fixedVmServiceUri = null, _useGlobalServiceConnection = false; - /// The fixed (unchanging) VM service URI for the application this - /// [ExtensionService] will manage DevTools extensions for, if constructed via - /// [ExtensionService.forVmService]. + /// A fixed VM service URI to detect runtime extensions for, if set. final String? _fixedVmServiceUri; - /// Whether this service should track the global - /// `serviceConnection.serviceManager` for the currently connected app. + /// Whether to listen to `serviceConnection.serviceManager` for the connected + /// app. final bool _useGlobalServiceConnection; /// A listenable for the current set of DevTools extensions. @@ -145,8 +137,7 @@ class ExtensionService extends DisposableController await _refresh(); cancelListeners(); - // We only need to add VM service manager related listeners when we are - // tracking the currently connected app via the global service connection. + // Only listen to the VM service manager when tracking the connected app. if (_useGlobalServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, 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 ea3634f858c..fc060cc050c 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 @@ -180,10 +180,10 @@ class SidebarDevToolsExtensionsController extends DisposableController ); final extensionService = vmServiceUri == null ? - // A null [vmServiceUri] indicates a static-only extensions lookup for - // the workspace, rather than a lookup for a specific debug session. + // A null [vmServiceUri] means this is a workspace-level lookup rather + // than a specific debug session. ExtensionService.forWorkspace() - : ExtensionService.forVmService(vmServiceUri); + : ExtensionService(fixedVmServiceUri: vmServiceUri); assert( !_extensionServiceByRootUri.containsKey(projectRootUri), 'The initialization for the ExtensionService for root uri ' diff --git a/packages/devtools_app/test/extensions/extension_screen_test.dart b/packages/devtools_app/test/extensions/extension_screen_test.dart index 7624c0c5b17..ec26155d7fa 100644 --- a/packages/devtools_app/test/extensions/extension_screen_test.dart +++ b/packages/devtools_app/test/extensions/extension_screen_test.dart @@ -36,7 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService.forVmService('ws://127.0.0.1:8181/ws'), + 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 a956c9f7910..28c04326f6d 100644 --- a/packages/devtools_app/test/extensions/extension_service_test.dart +++ b/packages/devtools_app/test/extensions/extension_service_test.dart @@ -34,8 +34,10 @@ void main() { resetDevToolsExtensionEnabledStates(); }); - test('initialize with forVmService', () async { - final service = ExtensionService.forVmService('ws://127.0.0.1:8181/ws'); + test('initialize with fixedVmServiceUri', () async { + final service = ExtensionService( + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', + ); expect(service.availableExtensions, isEmpty); expect(service.staticExtensions, isEmpty); expect(service.runtimeExtensions, isEmpty); @@ -84,7 +86,9 @@ void main() { }); test('setExtensionEnabledState', () async { - final service = ExtensionService.forVmService('ws://127.0.0.1:8181/ws'); + final service = ExtensionService( + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', + ); await service.initialize(); expect(service.staticExtensions.length, 4); expect(service.runtimeExtensions.length, 3); diff --git a/packages/devtools_app/test/extensions/extension_settings_test.dart b/packages/devtools_app/test/extensions/extension_settings_test.dart index 2103bb9e226..0ed74c1b0b0 100644 --- a/packages/devtools_app/test/extensions/extension_settings_test.dart +++ b/packages/devtools_app/test/extensions/extension_settings_test.dart @@ -36,7 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService.forVmService('ws://127.0.0.1:8181/ws'), + ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4); From a298106cdbb549a4060afde959658b5ee6752a88 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 14:27:55 -0800 Subject: [PATCH 13/14] Remove unused path dependency --- packages/devtools_app_shared/pubspec.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/devtools_app_shared/pubspec.yaml b/packages/devtools_app_shared/pubspec.yaml index 786defea6ca..5c6312247b4 100644 --- a/packages/devtools_app_shared/pubspec.yaml +++ b/packages/devtools_app_shared/pubspec.yaml @@ -22,7 +22,6 @@ dependencies: 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' From ec3355a0a5fb238a18d9d7806521bcbca5af5ad7 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Fri, 20 Nov 2026 14:39:22 -0800 Subject: [PATCH 14/14] Update comments --- .../lib/src/extensions/extension_service.dart | 15 ++++----------- .../devtools/sidebar_extensions_controller.dart | 8 ++------ .../lib/src/server/handlers/_vm_service.dart | 6 ++---- .../devtools_shared/lib/src/service_utils.dart | 5 +++-- .../test/server/general_api_test.dart | 4 ++-- 5 files changed, 13 insertions(+), 25 deletions(-) diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 5497e49afef..6e153a4cb6d 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -34,26 +34,20 @@ typedef DevToolsExtensionsGroup = ({ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - /// Creates an [ExtensionService] that detects both runtime and static - /// DevTools extensions. + /// Detects runtime and static DevTools extensions. /// - /// Pass [fixedVmServiceUri] to detect runtime extensions for a specific VM - /// service instead of listening to `serviceConnection.serviceManager`. + /// 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; - /// Creates an [ExtensionService] that only detects static DevTools - /// extensions for the IDE workspace. + /// Detects static DevTools extensions for the IDE workspace only. ExtensionService.forWorkspace() : _fixedVmServiceUri = null, _useGlobalServiceConnection = false; - /// A fixed VM service URI to detect runtime extensions for, if set. final String? _fixedVmServiceUri; - - /// Whether to listen to `serviceConnection.serviceManager` for the connected - /// app. final bool _useGlobalServiceConnection; /// A listenable for the current set of DevTools extensions. @@ -137,7 +131,6 @@ class ExtensionService extends DisposableController await _refresh(); cancelListeners(); - // Only listen to the VM service manager when tracking the connected app. if (_useGlobalServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, 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 fc060cc050c..b43cbf40498 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,8 +133,7 @@ class SidebarDevToolsExtensionsController extends DisposableController ); } - // Omit [projectRootUri] and [vmServiceUri] to initialize the set of - // extensions available for the entire workspace. + // Initialize extensions available for the entire workspace. await _detectExtensions(); } @@ -179,10 +178,7 @@ class SidebarDevToolsExtensionsController extends DisposableController '(debug session lookup).', ); final extensionService = vmServiceUri == null - ? - // A null [vmServiceUri] means this is a workspace-level lookup rather - // than a specific debug session. - ExtensionService.forWorkspace() + ? ExtensionService.forWorkspace() : ExtensionService(fixedVmServiceUri: vmServiceUri); assert( !_extensionServiceByRootUri.containsKey(projectRootUri), 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 9f35e8b3800..1c767c5a3d2 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -18,8 +18,7 @@ extension VmServiceHandler on Never { /// never be used. static final _packageRootsForVmServiceConnections = {}; - /// Registers a cached [rootPackageUri] for [vmServiceUriAsString] in - /// [_packageRootsForVmServiceConnections] for testing. + /// Caches [rootPackageUri] for [vmServiceUriAsString] in tests. @visibleForTesting static void setPackageRootForVmServiceForTesting( String vmServiceUriAsString, @@ -37,8 +36,7 @@ extension VmServiceHandler on Never { rootPackageUri; } - /// Clears all cached package roots in [_packageRootsForVmServiceConnections] - /// for testing. + /// Clears cached package roots between tests. @visibleForTesting static void clearPackageRootsForTesting() { _packageRootsForVmServiceConnections.clear(); diff --git a/packages/devtools_shared/lib/src/service_utils.dart b/packages/devtools_shared/lib/src/service_utils.dart index ef428c33922..fab729680a1 100644 --- a/packages/devtools_shared/lib/src/service_utils.dart +++ b/packages/devtools_shared/lib/src/service_utils.dart @@ -167,7 +167,8 @@ extension VmServicePackageRootExtension on VmService { } } } catch (_) { - // Fall back to import prefix lookup if evaluation fails. + // Older versions of package:test don't define `packageConfigLocation`; + // fall back to checking the `test` import prefix below. } final testTargetUri = (obj.dependencies ?? []) @@ -186,7 +187,7 @@ extension VmServicePackageRootExtension on VmService { } } } catch (_) { - // Fail gracefully if the test target lookup fails. + // Ignore errors; the caller will fall back to the root library URI. } return null; } diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index 85b7ecbcbe6..43f5c23cc83 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -791,8 +791,8 @@ void main() { endsWith(app!.directory.path), ); - // A subsequent disconnect should find no cached entry because the - // first disconnect removed it from the cache. + // Disconnecting again should be a no-op since the cache entry was + // already removed. final secondDisconnectResponse = await server.VmServiceHandler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!,