resident_web_runner.dart 26.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:build_daemon/client.dart';
8
import 'package:dwds/dwds.dart';
9
import 'package:meta/meta.dart';
10
import 'package:vm_service/vm_service.dart' as vmservice;
11 12
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
    hide StackTrace;
13

14
import '../application_package.dart';
15
import '../base/async_guard.dart';
16 17
import '../base/common.dart';
import '../base/file_system.dart';
18
import '../base/io.dart';
19
import '../base/logger.dart';
20
import '../base/os.dart';
21 22 23 24
import '../base/terminal.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../convert.dart';
25
import '../devfs.dart';
26
import '../device.dart';
27
import '../features.dart';
28 29
import '../globals.dart';
import '../project.dart';
30
import '../reporting/reporting.dart';
31
import '../resident_runner.dart';
32
import '../run_hot.dart';
33
import '../web/chrome.dart';
34
import '../web/devfs_web.dart';
35
import '../web/web_device.dart';
36 37 38 39 40 41 42
import '../web/web_runner.dart';
import 'web_fs.dart';

/// Injectable factory to create a [ResidentWebRunner].
class DwdsWebRunnerFactory extends WebRunnerFactory {
  @override
  ResidentRunner createWebRunner(
43
    FlutterDevice device, {
44
    String target,
45
    @required bool stayResident,
46 47
    @required FlutterProject flutterProject,
    @required bool ipv6,
48
    @required DebuggingOptions debuggingOptions,
49
    @required List<String> dartDefines,
50
  }) {
51
    if (featureFlags.isWebIncrementalCompilerEnabled && debuggingOptions.buildInfo.isDebug) {
52 53 54 55 56 57 58
      return _ExperimentalResidentWebRunner(
        device,
        target: target,
        flutterProject: flutterProject,
        debuggingOptions: debuggingOptions,
        ipv6: ipv6,
        stayResident: stayResident,
59
        dartDefines: dartDefines,
60 61 62
      );
    }
    return _DwdsResidentWebRunner(
63 64 65 66 67
      device,
      target: target,
      flutterProject: flutterProject,
      debuggingOptions: debuggingOptions,
      ipv6: ipv6,
68
      stayResident: stayResident,
69
      dartDefines: dartDefines,
70 71 72
    );
  }
}
73

74
/// A hot-runner which handles browser specific delegation.
75 76 77
abstract class ResidentWebRunner extends ResidentRunner {
  ResidentWebRunner(
    this.device, {
78 79 80
    String target,
    @required this.flutterProject,
    @required bool ipv6,
81
    @required DebuggingOptions debuggingOptions,
82
    bool stayResident = true,
83
    @required this.dartDefines,
84
  }) : super(
85
          <FlutterDevice>[],
86
          target: target ?? fs.path.join('lib', 'main.dart'),
87
          debuggingOptions: debuggingOptions,
88
          ipv6: ipv6,
89
          stayResident: stayResident,
90 91
        );

92
  final FlutterDevice device;
93
  final FlutterProject flutterProject;
94
  final List<String> dartDefines;
95
  DateTime firstBuildTime;
96

97 98
  // Only the debug builds of the web support the service protocol.
  @override
99
  bool get supportsServiceProtocol => isRunningDebug && deviceIsDebuggable;
100 101

  @override
102 103 104 105 106 107
  bool get debuggingEnabled => isRunningDebug && deviceIsDebuggable;

  /// WebServer device is debuggable when running with --start-paused.
  bool get deviceIsDebuggable => device.device is! WebServerDevice || debuggingOptions.startPaused;

  bool get _enableDwds => debuggingEnabled;
108

109
  WebFs _webFs;
110
  ConnectionResult _connectionResult;
111
  StreamSubscription<vmservice.Event> _stdOutSub;
112
  bool _exited = false;
113
  WipConnection _wipConnection;
114

115 116
  vmservice.VmService get _vmService =>
      _connectionResult?.debugConnection?.vmService;
117

118
  @override
119 120 121
  bool get canHotRestart {
    return true;
  }
122

123
  @override
124 125 126 127
  Future<Map<String, dynamic>> invokeFlutterExtensionRpcRawOnFirstIsolate(
    String method, {
    Map<String, dynamic> params,
  }) async {
128 129
    final vmservice.Response response =
        await _vmService.callServiceExtension(method, args: params);
130
    return response.toJson();
131 132 133
  }

  @override
134
  Future<void> cleanupAfterSignal() async {
135
    await _cleanup();
136 137 138
  }

  @override
139
  Future<void> cleanupAtFinish() async {
140 141 142 143
    await _cleanup();
  }

  Future<void> _cleanup() async {
144 145 146
    if (_exited) {
      return;
    }
147 148
    await _stdOutSub?.cancel();
    await _webFs?.stop();
149
    await device.device.stopApp(null);
150 151 152 153
    if (ChromeLauncher.hasChromeInstance) {
      final Chrome chrome = await ChromeLauncher.connectedInstance;
      await chrome.close();
    }
154
    _exited = true;
155 156
  }

157 158 159 160 161
  Future<void> _cleanupAndExit() async {
    await _cleanup();
    appFinished();
  }

162
  @override
163 164 165 166
  void printHelp({bool details = true}) {
    if (details) {
      return printHelpDetails();
    }
167
    const String fire = '🔥';
168 169 170
    const String rawMessage =
        '  To hot restart changes while running, press "r". '
        'To hot restart (and refresh the browser), press "R".';
171 172 173 174
    final String message = terminal.color(
      fire + terminal.bolden(rawMessage),
      TerminalColor.red,
    );
175 176
    printStatus(
        'Warning: Flutter\'s support for web development is not stable yet and hasn\'t');
177
    printStatus('been thoroughly tested in production environments.');
178
    printStatus('For more information see https://flutter.dev/web');
179
    printStatus('');
180 181 182 183 184
    printStatus(message);
    const String quitMessage = 'To quit, press "q".';
    printStatus('For a more detailed help message, press "h". $quitMessage');
  }

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  @override
  Future<void> debugDumpApp() async {
    try {
      await _vmService?.callServiceExtension(
        'ext.flutter.debugDumpApp',
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpRenderTree() async {
    try {
      await _vmService?.callServiceExtension(
        'ext.flutter.debugDumpRenderTree',
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpLayerTree() async {
    try {
      await _vmService?.callServiceExtension(
        'ext.flutter.debugDumpLayerTree',
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpSemanticsTreeInTraversalOrder() async {
    try {
      await _vmService?.callServiceExtension(
          'ext.flutter.debugDumpSemanticsTreeInTraversalOrder');
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugTogglePlatform() async {
    try {
      final vmservice.Response response = await _vmService
          ?.callServiceExtension('ext.flutter.platformOverride');
233
      final String currentPlatform = response.json['value'] as String;
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
      String nextPlatform;
      switch (currentPlatform) {
        case 'android':
          nextPlatform = 'iOS';
          break;
        case 'iOS':
          nextPlatform = 'android';
          break;
      }
      if (nextPlatform == null) {
        return;
      }
      await _vmService?.callServiceExtension('ext.flutter.platformOverride',
          args: <String, Object>{
            'value': nextPlatform,
          });
      printStatus('Switched operating system to $nextPlatform');
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugDumpSemanticsTreeInInverseHitTestOrder() async {
    try {
      await _vmService?.callServiceExtension(
          'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder');
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleDebugPaintSizeEnabled() async {
    try {
      final vmservice.Response response =
          await _vmService?.callServiceExtension(
        'ext.flutter.debugPaint',
      );
      await _vmService?.callServiceExtension(
        'ext.flutter.debugPaint',
        args: <dynamic, dynamic>{
          'enabled': !(response.json['enabled'] == 'true')
        },
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleDebugCheckElevationsEnabled() async {
    try {
      final vmservice.Response response =
          await _vmService?.callServiceExtension(
        'ext.flutter.debugCheckElevationsEnabled',
      );
      await _vmService?.callServiceExtension(
        'ext.flutter.debugCheckElevationsEnabled',
        args: <dynamic, dynamic>{
          'enabled': !(response.json['enabled'] == 'true')
        },
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugTogglePerformanceOverlayOverride() async {
    try {
      final vmservice.Response response = await _vmService
          ?.callServiceExtension('ext.flutter.showPerformanceOverlay');
      await _vmService?.callServiceExtension(
        'ext.flutter.showPerformanceOverlay',
        args: <dynamic, dynamic>{
          'enabled': !(response.json['enabled'] == 'true')
        },
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleWidgetInspector() async {
    try {
      final vmservice.Response response = await _vmService
          ?.callServiceExtension('ext.flutter.debugToggleWidgetInspector');
      await _vmService?.callServiceExtension(
        'ext.flutter.debugToggleWidgetInspector',
        args: <dynamic, dynamic>{
          'enabled': !(response.json['enabled'] == 'true')
        },
      );
    } on vmservice.RPCError {
      return;
    }
  }

  @override
  Future<void> debugToggleProfileWidgetBuilds() async {
    try {
      final vmservice.Response response = await _vmService
          ?.callServiceExtension('ext.flutter.profileWidgetBuilds');
      await _vmService?.callServiceExtension(
        'ext.flutter.profileWidgetBuilds',
        args: <dynamic, dynamic>{
          'enabled': !(response.json['enabled'] == 'true')
        },
      );
    } on vmservice.RPCError {
      return;
    }
  }
}

class _ExperimentalResidentWebRunner extends ResidentWebRunner {
  _ExperimentalResidentWebRunner(
    FlutterDevice device, {
    String target,
    @required FlutterProject flutterProject,
    @required bool ipv6,
    @required DebuggingOptions debuggingOptions,
    bool stayResident = true,
359
    @required List<String> dartDefines,
360 361 362 363 364 365 366
  }) : super(
          device,
          flutterProject: flutterProject,
          target: target ?? fs.path.join('lib', 'main.dart'),
          debuggingOptions: debuggingOptions,
          ipv6: ipv6,
          stayResident: stayResident,
367
          dartDefines: dartDefines,
368 369
        );

370 371 372 373 374 375
  @override
  Future<int> run({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
    String route,
  }) async {
376
    firstBuildTime = DateTime.now();
377 378 379 380 381
    final ApplicationPackage package = await ApplicationPackageFactory.instance.getPackageForPlatform(
      TargetPlatform.web_javascript,
      applicationBinary: null,
    );
    if (package == null) {
382
      printError('This application is not configured to build on the web.');
383
      printError('To add web support to a project, run `flutter create .`.');
384 385
      return 1;
    }
386 387 388 389 390 391 392 393 394
    if (!fs.isFileSync(mainPath)) {
      String message = 'Tried to run $mainPath, but that file does not exist.';
      if (target == null) {
        message +=
            '\nConsider using the -t option to specify the Dart file to start.';
      }
      printError(message);
      return 1;
    }
395
    final String modeName = debuggingOptions.buildInfo.friendlyModeName;
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    printStatus('Launching ${getDisplayPath(target)} on ${device.device.name} in $modeName mode...');
    final String effectiveHostname = debuggingOptions.hostname ?? 'localhost';
    final int hostPort = debuggingOptions.port == null
        ? await os.findFreePort()
        : int.tryParse(debuggingOptions.port);
    device.devFS = WebDevFS(
      effectiveHostname,
      hostPort,
      packagesFilePath,
    );
    await device.devFS.create();
    await _updateDevFS(fullRestart: true);
    device.generator.accept();
    await device.device.startApp(
      package,
      mainPath: target,
      debuggingOptions: debuggingOptions,
      platformArgs: <String, Object>{
        'uri': 'http://$effectiveHostname:$hostPort',
      },
    );
    return attach(
      connectionInfoCompleter: connectionInfoCompleter,
      appStartedCompleter: appStartedCompleter,
    );
  }

  @override
  Future<OperationResult> restart({
    bool fullRestart = false,
426
    bool pauseAfterRestart = false,
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    String reason,
    bool benchmarkMode = false,
  }) async {
    final Stopwatch timer = Stopwatch()..start();
    final Status status = logger.startProgress(
      'Performing hot restart...',
      timeout: supportsServiceProtocol
          ? timeoutConfiguration.fastOperation
          : timeoutConfiguration.slowOperation,
      progressId: 'hot.restart',
    );

    final UpdateFSReport report = await _updateDevFS(fullRestart: fullRestart);
    if (report.success) {
      device.generator.accept();
    } else {
      await device.generator.reject();
    }
    final String modules = report.invalidatedModules
      .map((String module) => '"$module"')
      .join(',');

    try {
      if (fullRestart) {
451
        await _wipConnection?.sendCommand('Page.reload');
452
      } else {
453 454
        await _wipConnection?.debugger
            ?.sendCommand('Runtime.evaluate', params: <String, Object>{
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
          'expression': 'window.\$hotReloadHook([$modules])',
          'awaitPromise': true,
          'returnByValue': true,
        });
      }
    } on WipError catch (err) {
      printError(err.toString());
      return OperationResult(1, err.toString());
    } finally {
      status.stop();
    }
    final String verb = fullRestart ? 'Restarted' : 'Reloaded';
    printStatus('$verb application in ${getElapsedAsMilliseconds(timer.elapsed)}.');
    if (!fullRestart) {
      flutterUsage.sendTiming('hot', 'web-incremental-restart', timer.elapsed);
    }
    HotEvent(
      'restart',
      targetPlatform: getNameForTargetPlatform(TargetPlatform.web_javascript),
      sdkName: await device.device.sdkNameAndVersion,
      emulator: false,
      fullRestart: true,
      reason: reason,
    ).send();
    return OperationResult.ok;
  }

  Future<UpdateFSReport> _updateDevFS({bool fullRestart = false}) async {
    final bool isFirstUpload = !assetBundle.wasBuiltOnce();
    final bool rebuildBundle = assetBundle.needsBuild();
    if (rebuildBundle) {
      printTrace('Updating assets');
      final int result = await assetBundle.build();
      if (result != 0) {
        return UpdateFSReport(success: false);
      }
    }
    final List<Uri> invalidatedFiles =
        await projectFileInvalidator.findInvalidated(
      lastCompiled: device.devFS.lastCompiled,
      urisToMonitor: device.devFS.sources,
      packagesPath: packagesFilePath,
    );
    final Status devFSStatus = logger.startProgress(
      'Syncing files to device ${device.device.name}...',
      timeout: timeoutConfiguration.fastOperation,
    );
    final UpdateFSReport report = await device.devFS.update(
      mainPath: mainPath,
      target: target,
      bundle: assetBundle,
      firstBuildTime: firstBuildTime,
      bundleFirstUpload: isFirstUpload,
      generator: device.generator,
      fullRestart: fullRestart,
      dillOutputPath: dillOutputPath,
      projectRootPath: projectRootPath,
      pathToReload: getReloadPath(fullRestart: fullRestart),
      invalidatedFiles: invalidatedFiles,
      trackWidgetCreation: true,
    );
    devFSStatus.stop();
    printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.');
    return report;
  }

  @override
  Future<int> attach({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
  }) async {
526 527 528 529 530 531 532
    if (device.device is ChromeDevice) {
      final Chrome chrome = await ChromeLauncher.connectedInstance;
      final ChromeTab chromeTab = await chrome.chromeConnection.getTab((ChromeTab chromeTab) {
        return chromeTab.url.contains(debuggingOptions.hostname);
      });
      _wipConnection = await chromeTab.connect();
    }
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    appStartedCompleter?.complete();
    connectionInfoCompleter?.complete();
    if (stayResident) {
      await waitForAppToFinish();
    } else {
      await stopEchoingDeviceLog();
      await exitApp();
    }
    await cleanupAtFinish();
    return 0;
  }
}

class _DwdsResidentWebRunner extends ResidentWebRunner {
  _DwdsResidentWebRunner(
    FlutterDevice device, {
    String target,
    @required FlutterProject flutterProject,
    @required bool ipv6,
    @required DebuggingOptions debuggingOptions,
    bool stayResident = true,
554
    @required List<String> dartDefines,
555 556 557 558 559 560 561
  }) : super(
          device,
          flutterProject: flutterProject,
          target: target ?? fs.path.join('lib', 'main.dart'),
          debuggingOptions: debuggingOptions,
          ipv6: ipv6,
          stayResident: stayResident,
562
          dartDefines: dartDefines,
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        );

  @override
  Future<int> run({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
    String route,
  }) async {
    firstBuildTime = DateTime.now();
    final ApplicationPackage package = await ApplicationPackageFactory.instance.getPackageForPlatform(
      TargetPlatform.web_javascript,
      applicationBinary: null,
    );
    if (package == null) {
      printError('This application is not configured to build on the web.');
      printError('To add web support to a project, run `flutter create .`.');
      return 1;
    }
    if (!fs.isFileSync(mainPath)) {
      String message = 'Tried to run $mainPath, but that file does not exist.';
      if (target == null) {
        message +=
            '\nConsider using the -t option to specify the Dart file to start.';
      }
      printError(message);
      return 1;
    }
    final String modeName = debuggingOptions.buildInfo.friendlyModeName;
    printStatus(
        'Launching ${getDisplayPath(target)} on ${device.device.name} in $modeName mode...');
593
    Status buildStatus;
594
    bool statusActive = false;
595
    try {
596 597 598
      // dwds does not handle uncaught exceptions from its servers. To work
      // around this, we need to catch all uncaught exceptions and determine if
      // they are fatal or not.
599
      buildStatus = logger.startProgress('Building application for the web...', timeout: null);
600
      statusActive = true;
601 602 603 604 605 606 607 608
      final int result = await asyncGuard(() async {
        _webFs = await webFsFactory(
          target: target,
          flutterProject: flutterProject,
          buildInfo: debuggingOptions.buildInfo,
          initializePlatform: debuggingOptions.initializePlatform,
          hostname: debuggingOptions.hostname,
          port: debuggingOptions.port,
609
          skipDwds: !_enableDwds,
610
          dartDefines: dartDefines,
611
        );
612 613
        // When connecting to a browser, update the message with a seemsSlow notification
        // to handle the case where we fail to connect.
614 615
        buildStatus.stop();
        statusActive = false;
616
        if (supportsServiceProtocol) {
617 618 619 620
          buildStatus = logger.startProgress(
            'Attempting to connect to browser instance..',
            timeout: const Duration(seconds: 30),
          );
621
          statusActive = true;
622
        }
623 624
        await device.device.startApp(
          package,
625 626 627 628 629 630
          mainPath: target,
          debuggingOptions: debuggingOptions,
          platformArgs: <String, Object>{
            'uri': _webFs.uri,
          },
        );
631 632 633
        if (_enableDwds) {
          final bool useDebugExtension = device.device is WebServerDevice && debuggingOptions.startPaused;
          _connectionResult = await _webFs.connect(useDebugExtension);
634
          unawaited(_connectionResult.debugConnection.onDone.whenComplete(_cleanupAndExit));
635
        }
636 637 638 639
        if (statusActive) {
          buildStatus.stop();
          statusActive = false;
        }
640 641 642 643 644 645 646
        appStartedCompleter?.complete();
        return attach(
          connectionInfoCompleter: connectionInfoCompleter,
          appStartedCompleter: appStartedCompleter,
        );
      });
      return result;
647 648 649
    } on VersionSkew {
      // Thrown if an older build daemon is already running.
      throwToolExit(
650 651
          'Another build daemon is already running with an older version.\n'
          'Try exiting other Flutter processes in this project and try again.');
652 653 654
    } on OptionsSkew {
      // Thrown if a build daemon is already running with different configuration.
      throwToolExit(
655 656
          'Another build daemon is already running with different configuration.\n'
          'Exit other Flutter processes running in this project and try again.');
657 658 659 660
    } on WebSocketException {
      throwToolExit('Failed to connect to WebSocket.');
    } on BuildException {
      throwToolExit('Failed to build application for the Web.');
661 662
    } on ChromeDebugException catch (err, stackTrace) {
      throwToolExit(
663 664
          'Failed to establish connection with Chrome. Try running the application again.\n'
          'If this problem persists, please file an issue with the details below:\n$err\n$stackTrace');
665 666
    } on AppConnectionException {
      throwToolExit(
667 668 669 670
          'Failed to establish connection with the application instance in Chrome.\n'
          'This can happen if the websocket connection used by the web tooling is '
          'unabled to correctly establish a connection, for example due to a firewall.');
    } on MissingPortFile {
671
      throwToolExit(
672 673
          'Failed to connect to build daemon.\nThe daemon either failed to '
          'start or was killed by another process.');
674 675
    } on SocketException catch (err) {
      throwToolExit(err.toString());
676 677 678
    } on StateError catch (err) {
      final String message = err.toString();
      if (message.contains('Unable to start build daemon')) {
679 680 681
        throwToolExit('Failed to start build daemon. The process might have '
            'exited unexpectedly during startup. Try running the application '
            'again.');
682 683
      }
      rethrow;
684
    } finally {
685 686 687
      if (statusActive) {
        buildStatus.stop();
      }
688
    }
689
    return 1;
690 691 692
  }

  @override
693 694
  Future<OperationResult> restart({
    bool fullRestart = false,
695
    bool pauseAfterRestart = false,
696 697 698 699 700 701
    String reason,
    bool benchmarkMode = false,
  }) async {
    final Stopwatch timer = Stopwatch()..start();
    final Status status = logger.startProgress(
      'Performing hot restart...',
702 703 704
      timeout: supportsServiceProtocol
          ? timeoutConfiguration.fastOperation
          : timeoutConfiguration.slowOperation,
705
      progressId: 'hot.restart',
706
    );
707 708 709 710 711 712
    final bool success = await _webFs.recompile();
    if (!success) {
      status.stop();
      return OperationResult(1, 'Failed to recompile application.');
    }
    if (supportsServiceProtocol) {
713 714 715
      // Send an event for only recompilation.
      final Duration recompileDuration = timer.elapsed;
      flutterUsage.sendTiming('hot', 'web-recompile', recompileDuration);
716
      try {
717
        final vmservice.Response reloadResponse = fullRestart
718 719
          ? await _vmService.callServiceExtension('fullReload')
          : await _vmService.callServiceExtension('hotRestart');
720
        final String verb = fullRestart ? 'Restarted' : 'Reloaded';
721 722
        printStatus(
            '$verb application in ${getElapsedAsMilliseconds(timer.elapsed)}.');
723 724

        // Send timing analytics for full restart and for refresh.
725 726 727 728
        final bool wasSuccessful = reloadResponse.type == 'Success';
        if (!wasSuccessful) {
          return OperationResult(1, reloadResponse.toString());
        }
729 730 731 732
        if (!fullRestart) {
          flutterUsage.sendTiming('hot', 'web-restart', timer.elapsed);
          flutterUsage.sendTiming('hot', 'web-refresh', timer.elapsed - recompileDuration);
        }
733
        return OperationResult.ok;
734
      } on vmservice.RPCError {
735
        return OperationResult(1, 'Page requires refresh.');
736 737
      } finally {
        status.stop();
738 739
        HotEvent(
          'restart',
740
          targetPlatform: getNameForTargetPlatform(TargetPlatform.web_javascript),
741
          sdkName: await device.device.sdkNameAndVersion,
742 743 744 745
          emulator: false,
          fullRestart: true,
          reason: reason,
        ).send();
746
      }
747
    }
748
    // Allows browser refresh hot restart on non-debug builds.
749
    if (device.device is ChromeDevice && !isRunningDebug) {
750 751 752 753 754 755 756 757 758 759 760 761 762
      try {
        final Chrome chrome = await ChromeLauncher.connectedInstance;
        final ChromeTab chromeTab = await chrome.chromeConnection.getTab((ChromeTab chromeTab) {
          return chromeTab.url.contains(debuggingOptions.hostname);
        });
        final WipConnection wipConnection = await chromeTab.connect();
        await wipConnection.sendCommand('Page.reload');
        status.stop();
        return OperationResult.ok;
      } catch (err) {
        // Ignore error and continue with posted message;
      }
    }
763
    status.stop();
764
    printStatus('Recompile complete. Page requires refresh.');
765 766 767 768
    return OperationResult.ok;
  }

  @override
769 770 771 772 773 774 775 776 777 778 779 780 781
  Future<int> attach({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
  }) async {
    Uri websocketUri;
    if (supportsServiceProtocol) {
      // Cleanup old subscriptions. These will throw if there isn't anything
      // listening, which is fine because that is what we want to ensure.
      try {
        await _vmService.streamCancel('Stdout');
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
782
      }
783 784 785 786 787
      try {
        await _vmService.streamListen('Stdout');
      } on vmservice.RPCError {
        // It is safe to ignore this error because we expect an error to be
        // thrown if we're not already subscribed.
788
      }
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
      _stdOutSub = _vmService.onStdoutEvent.listen((vmservice.Event log) {
        final String message = utf8.decode(base64.decode(log.bytes)).trim();
        printStatus(message);
      });
      unawaited(_vmService.registerService('reloadSources', 'FlutterTools'));
      websocketUri = Uri.parse(_connectionResult.debugConnection.uri);
      // Always run main after connecting because start paused doesn't work yet.
      if (!debuggingOptions.startPaused || !supportsServiceProtocol) {
        _connectionResult.appConnection.runMain();
      } else {
        StreamSubscription<void> resumeSub;
        resumeSub = _connectionResult.debugConnection.vmService.onDebugEvent
            .listen((vmservice.Event event) {
          if (event.type == vmservice.EventKind.kResume) {
            _connectionResult.appConnection.runMain();
            resumeSub.cancel();
          }
806
        });
807
      }
808
    }
809 810
    if (websocketUri != null) {
      printStatus('Debug service listening on $websocketUri');
811
    }
812
    connectionInfoCompleter?.complete(DebugConnectionInfo(wsUri: websocketUri));
813

814 815 816 817 818
    if (stayResident) {
      await waitForAppToFinish();
    } else {
      await stopEchoingDeviceLog();
      await exitApp();
819
    }
820 821
    await cleanupAtFinish();
    return 0;
822 823
  }
}