Skip to content

Allow the Dart Debug Extension to communicate with Cider #2234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions dwds/debug_extension_mv3/web/background.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:dwds/data/debug_info.dart';
import 'package:js/js.dart';

import 'chrome_api.dart';
import 'cider_connection.dart';
import 'cross_extension_communication.dart';
import 'data_types.dart';
import 'debug_session.dart';
Expand All @@ -31,6 +32,10 @@ void _registerListeners() {
chrome.runtime.onMessageExternal.addListener(
allowInterop(handleMessagesFromAngularDartDevTools),
);
// The only external service that sends messages to the Dart Debug Extension
// is Cider.
chrome.runtime.onConnectExternal
.addListener(allowInterop(handleCiderConnectRequest));
// Update the extension icon on tab navigation:
chrome.tabs.onActivated.addListener(
allowInterop((ActiveInfo info) async {
Expand Down Expand Up @@ -105,7 +110,7 @@ Future<void> _handleRuntimeMessages(
// Save the debug info for the Dart app in storage:
await setStorageObject<DebugInfo>(
type: StorageObject.debugInfo,
value: _addTabUrl(debugInfo, tabUrl: dartTab.url),
value: _addTabInfo(debugInfo, tab: dartTab),
tabId: dartTab.id,
);
// Update the icon to show that a Dart app has been detected:
Expand Down Expand Up @@ -183,7 +188,7 @@ bool _isInternalNavigation(NavigationInfo navigationInfo) {
].contains(navigationInfo.transitionType);
}

DebugInfo _addTabUrl(DebugInfo debugInfo, {required String tabUrl}) {
DebugInfo _addTabInfo(DebugInfo debugInfo, {required Tab tab}) {
return DebugInfo(
(b) => b
..appEntrypointPath = debugInfo.appEntrypointPath
Expand All @@ -195,7 +200,9 @@ DebugInfo _addTabUrl(DebugInfo debugInfo, {required String tabUrl}) {
..extensionUrl = debugInfo.extensionUrl
..isInternalBuild = debugInfo.isInternalBuild
..isFlutterApp = debugInfo.isFlutterApp
..tabUrl = tabUrl,
..workspaceName = debugInfo.workspaceName
..tabUrl = tab.url
..tabId = tab.id,
);
}

Expand Down
17 changes: 16 additions & 1 deletion dwds/debug_extension_mv3/web/chrome_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ class Runtime {

external ConnectionHandler get onConnect;

external ConnectionHandler get onConnectExternal;

external OnMessageHandler get onMessage;

external OnMessageHandler get onMessageExternal;
Expand All @@ -203,9 +205,19 @@ class ConnectInfo {
class Port {
external String? get name;
external void disconnect();
external void postMessage(Object message);
external OnPortMessageHandler get onMessage;
external ConnectionHandler get onDisconnect;
}

@JS()
@anonymous
class OnPortMessageHandler {
external void addListener(
void Function(dynamic, Port) callback,
);
}

@JS()
@anonymous
class ConnectionHandler {
Expand Down Expand Up @@ -252,7 +264,10 @@ class Storage {
@JS()
@anonymous
class StorageArea {
external Object get(List<String> keys, void Function(Object result) callback);
external Object get(
List<String>? keys,
void Function(Object result) callback,
);

external Object set(Object items, void Function()? callback);

Expand Down
190 changes: 190 additions & 0 deletions dwds/debug_extension_mv3/web/cider_connection.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@JS()
library cider_connection;

import 'dart:convert';

import 'package:dwds/data/debug_info.dart';
import 'package:js/js.dart';

import 'chrome_api.dart';
import 'debug_session.dart';
import 'logger.dart';
import 'storage.dart';

/// Defines the message types that can be passed to/from Cider.
///
/// The types must match those defined by ChromeExtensionMessageType in the
/// Cider extension.
enum CiderMessageType {
error,
startDebugResponse,
startDebugRequest,
stopDebugResponse,
stopDebugRequest,
}

/// Defines the error types that can be sent to Cider.
///
/// The types must match those defined by ChromeExtensionErrorType in the
/// Cider extension.
enum CiderErrorType {
chromeError,
internalError,
invalidRequest,
multipleDartTabs,
noDartTab,
noWorkspace,
}

const _ciderPortName = 'cider';
Port? _ciderPort;

/// Handles a connect request from Cider.
///
/// The only site allowed to connect with this extension is Cider. The allowed
/// URIs for Cider are set in the externally_connectable field in the manifest.
void handleCiderConnectRequest(Port port) {
if (port.name == _ciderPortName) {
_ciderPort = port;

port.onMessage.addListener(
allowInterop(_handleMessageFromCider),
);
}
}

/// Sends a message to the Cider-connected port.
void sendMessageToCider({
required CiderMessageType messageType,
String? messageBody,
}) {
if (_ciderPort == null) return;
final message = jsonEncode({
'messageType': messageType.name,
'messageBody': messageBody,
});
_ciderPort!.postMessage(message);
}

/// Sends an error message to the Cider-connected port.
void sendErrorMessageToCider({
required CiderErrorType errorType,
String? errorDetails,
}) {
debugWarn('CiderError.${errorType.name} $errorDetails');
if (_ciderPort == null) return;
final message = jsonEncode({
'messageType': CiderMessageType.error.name,
'errorType': errorType.name,
'messageBody': errorDetails,
});
_ciderPort!.postMessage(message);
}

Future<void> _handleMessageFromCider(dynamic message, Port _) async {
if (message is! String) {
sendErrorMessageToCider(
errorType: CiderErrorType.invalidRequest,
errorDetails: 'Expected request to be a string: $message',
);
return;
}

final decoded = jsonDecode(message) as Map<String, dynamic>;
final messageType = decoded['messageType'] as String?;
final messageBody = decoded['messageBody'] as String?;

if (messageType == CiderMessageType.startDebugRequest.name) {
await _startDebugging(workspaceName: messageBody);
} else if (messageType == CiderMessageType.stopDebugRequest.name) {
await _stopDebugging(workspaceName: messageBody);
}
}

Future<void> _startDebugging({String? workspaceName}) async {
if (workspaceName == null) {
_sendNoWorkspaceError();
return;
}

final dartTab = await _findDartTabIdForWorkspace(workspaceName);
if (dartTab != null) {
// TODO(https://github.com/dart-lang/webdev/issues/2198): When debugging
// with Cider, disable debugging with DevTools.
await attachDebugger(dartTab, trigger: Trigger.cider);
}
}

Future<void> _stopDebugging({String? workspaceName}) async {
if (workspaceName == null) {
_sendNoWorkspaceError();
return;
}

final dartTab = await _findDartTabIdForWorkspace(workspaceName);
if (dartTab == null) return;
final successfullyDetached = await detachDebugger(
dartTab,
type: TabType.dartApp,
reason: DetachReason.canceledByUser,
);

if (successfullyDetached) {
sendMessageToCider(messageType: CiderMessageType.stopDebugResponse);
} else {
sendErrorMessageToCider(
errorType: CiderErrorType.internalError,
errorDetails: 'Unable to detach debugger.',
);
}
}

void _sendNoWorkspaceError() {
sendErrorMessageToCider(
errorType: CiderErrorType.noWorkspace,
errorDetails: 'Cannot find a debuggable Dart tab without a workspace',
);
}

Future<int?> _findDartTabIdForWorkspace(String workspaceName) async {
final allTabsInfo = await fetchAllStorageObjectsOfType<DebugInfo>(
type: StorageObject.debugInfo,
);
final dartTabIds = allTabsInfo
.where(
(debugInfo) => debugInfo.workspaceName == workspaceName,
)
.map(
(info) => info.tabId,
)
.toList();

if (dartTabIds.isEmpty) {
sendErrorMessageToCider(
errorType: CiderErrorType.noDartTab,
errorDetails: 'No debuggable Dart tabs found.',
);
return null;
}
if (dartTabIds.length > 1) {
sendErrorMessageToCider(
errorType: CiderErrorType.noDartTab,
errorDetails: 'Too many debuggable Dart tabs found.',
);
return null;
}
final tabId = dartTabIds.first;
if (tabId == null) {
sendErrorMessageToCider(
errorType: CiderErrorType.chromeError,
errorDetails: 'Debuggable Dart tab is null.',
);
return null;
}

return tabId;
}
14 changes: 13 additions & 1 deletion dwds/debug_extension_mv3/web/debug_session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import 'package:sse/client/sse_client.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'chrome_api.dart';
import 'cider_connection.dart';
import 'cross_extension_communication.dart';
import 'data_serializers.dart';
import 'data_types.dart';
Expand Down Expand Up @@ -79,6 +80,7 @@ enum TabType {

enum Trigger {
angularDartDevTools,
cider,
extensionPanel,
extensionIcon,
}
Expand Down Expand Up @@ -408,7 +410,15 @@ void _routeDwdsEvent(String eventData, SocketClient client, int tabId) {
tabId: tabId,
);
if (message.method == 'dwds.devtoolsUri') {
_openDevTools(message.params, dartAppTabId: tabId);
if (_tabIdToTrigger[tabId] != Trigger.cider) {
_openDevTools(message.params, dartAppTabId: tabId);
}
}
if (message.method == 'dwds.plainUri') {
sendMessageToCider(
messageType: CiderMessageType.startDebugResponse,
messageBody: message.params,
);
}
if (message.method == 'dwds.encodedUri') {
setStorageObject(
Expand Down Expand Up @@ -774,6 +784,8 @@ DebuggerLocation? _debuggerLocation(int dartAppTabId) {
return DebuggerLocation.angularDartDevTools;
case Trigger.extensionPanel:
return DebuggerLocation.chromeDevTools;
case Trigger.cider:
return DebuggerLocation.ide;
}
}

Expand Down
10 changes: 9 additions & 1 deletion dwds/debug_extension_mv3/web/manifest_mv2.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
"default_icon": "static_assets/dart_grey.png"
},
"externally_connectable": {
"ids": ["nbkbficgbembimioedhceniahniffgpl"]
"ids": ["nbkbficgbembimioedhceniahniffgpl"],
"matches": [
"https://cider.corp.google.com/*",
"https://cider-staging.corp.google.com/*",
"https://cider-test.corp.google.com/*",
"https://cider-v.corp.google.com/*",
"https://cider-v-staging.corp.google.com/*",
"https://cider-v-test.corp.google.com/*"
]
},
"permissions": ["debugger", "notifications", "storage", "webNavigation"],
"background": {
Expand Down
10 changes: 9 additions & 1 deletion dwds/debug_extension_mv3/web/manifest_mv3.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
"default_icon": "static_assets/dart_grey.png"
},
"externally_connectable": {
"ids": ["nbkbficgbembimioedhceniahniffgpl"]
"ids": ["nbkbficgbembimioedhceniahniffgpl"],
"matches": [
"https://cider.corp.google.com/*",
"https://cider-staging.corp.google.com/*",
"https://cider-test.corp.google.com/*",
"https://cider-v.corp.google.com/*",
"https://cider-v-staging.corp.google.com/*",
"https://cider-v-test.corp.google.com/*"
]
},
"permissions": [
"debugger",
Expand Down
30 changes: 30 additions & 0 deletions dwds/debug_extension_mv3/web/storage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,36 @@ Future<T?> fetchStorageObject<T>({required StorageObject type, int? tabId}) {
return completer.future;
}

Future<List<T>> fetchAllStorageObjectsOfType<T>({required StorageObject type}) {
final completer = Completer<List<T>>();
final storageArea = _getStorageArea(type.persistence);
storageArea.get(
null,
allowInterop((Object? storageContents) {
if (storageContents == null) {
debugWarn('No storage objects of type exist.', prefix: type.name);
completer.complete([]);
return;
}
final allKeys = List<String>.from(objectKeys(storageContents));
final storageKeys = allKeys.where((key) => key.contains(type.name));
final result = <T>[];
for (final key in storageKeys) {
final json = getProperty(storageContents, key) as String?;
if (json != null) {
if (T == String) {
result.add(json as T);
} else {
result.add(serializers.deserialize(jsonDecode(json)) as T);
}
}
}
completer.complete(result);
}),
);
return completer.future;
}

Future<bool> removeStorageObject<T>({required StorageObject type, int? tabId}) {
final storageKey = _createStorageKey(type, tabId);
final completer = Completer<bool>();
Expand Down
Loading