Use interactive mode with devicectl to redirect stdout (#178405)

Reverts https://github.com/flutter/flutter/pull/178167 and instead runs
`devicectl` in interactive mode by prefixing command with `script -t 0
/dev/null` to convince `devicectl` it has a terminal attached in order
to redirect stdout.

Fixes b/454953393. Related to
https://github.com/flutter/flutter/issues/178319.

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

**Note**: The Flutter team is currently trialing the use of [Gemini Code
Assist for
GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code).
Comments from the `gemini-code-assist` bot should not be taken as
authoritative feedback from the Flutter team. If you find its comments
useful you can update your code accordingly, but if you are unsure or
disagree with the feedback, please feel free to wait for a Flutter team
member's review for guidance on which automated comments should be
addressed.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
This commit is contained in:
Victoria Ashworth 2025-11-21 11:19:20 -06:00 committed by GitHub
parent 64c1b7d0d7
commit a7fd1467d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 79 additions and 98 deletions

View File

@ -95,6 +95,7 @@ class IOSCoreDeviceLauncher {
required String bundlePath,
required String bundleId,
required List<String> launchArguments,
required ShutdownHooks shutdownHooks,
}) async {
// Install app to device
final (bool installStatus, IOSCoreDeviceInstallResult? installResult) = await _coreDeviceControl
@ -111,6 +112,7 @@ class IOSCoreDeviceLauncher {
bundleId: bundleId,
launchArguments: launchArguments,
startStopped: true,
shutdownHooks: shutdownHooks,
);
if (!launchResult) {
@ -335,8 +337,6 @@ class IOSCoreDeviceControl {
'Failed to execute code (error: EXC_BAD_ACCESS, debugger assist: not detected)',
];
static const kCoreDeviceLaunchCompleteLog = 'Waiting for the application to terminate';
/// Executes `devicectl` command to get list of devices. The command will
/// likely complete before [timeout] is reached. If [timeout] is reached,
/// the command will be stopped as a failure.
@ -653,22 +653,19 @@ class IOSCoreDeviceControl {
/// If [attachToConsole] is true, attaches the application to the console and waits for the app
/// to terminate.
///
/// When [jsonOutputFile] is provided, devicectl will write a JSON file with the command results
/// after the command has completed. This will not have the results when using [attachToConsole]
/// until the process has exited.
///
/// When [logOutputFile] is provided, devicectl will write all logging otherwise passed to
/// stdout/stderr to the file. It will also continue to stream the logs to stdout/stderr.
/// If [interactiveMode] is true, runs the process in interactive mode (via script) to convince
/// devicectl it has a terminal attached in order to redirect stdout.
List<String> _launchAppCommand({
required String deviceId,
required String bundleId,
List<String> launchArguments = const <String>[],
bool startStopped = false,
bool attachToConsole = false,
File? jsonOutputFile,
File? logOutputFile,
File? outputFile,
bool interactiveMode = false,
}) {
return <String>[
if (interactiveMode) ...<String>['script', '-t', '0', '/dev/null'],
..._xcode.xcrunCommand(),
'devicectl',
'device',
@ -684,8 +681,7 @@ class IOSCoreDeviceControl {
// See https://github.com/llvm/llvm-project/blob/19b43e1757b4fd3d0f188cf8a08e9febb0dbec2f/lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp#L1227-L1233
'{"OS_ACTIVITY_DT_MODE": "enable"}',
],
if (jsonOutputFile != null) ...<String>['--json-output', jsonOutputFile.path],
if (logOutputFile != null) ...<String>['--log-output', logOutputFile.path],
if (outputFile != null) ...<String>['--json-output', outputFile.path],
bundleId,
if (launchArguments.isNotEmpty) ...launchArguments,
];
@ -714,7 +710,7 @@ class IOSCoreDeviceControl {
deviceId: deviceId,
launchArguments: launchArguments,
startStopped: startStopped,
jsonOutputFile: output,
outputFile: output,
);
try {
@ -751,6 +747,7 @@ class IOSCoreDeviceControl {
required IOSCoreDeviceLogForwarder coreDeviceLogForwarder,
required String deviceId,
required String bundleId,
required ShutdownHooks shutdownHooks,
List<String> launchArguments = const <String>[],
bool startStopped = false,
}) async {
@ -765,9 +762,6 @@ class IOSCoreDeviceControl {
return false;
}
final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.');
final File output = tempDirectory.childFile('launch_log.txt')..createSync();
final launchCompleter = Completer<bool>();
final List<String> command = _launchAppCommand(
bundleId: bundleId,
@ -775,9 +769,9 @@ class IOSCoreDeviceControl {
launchArguments: launchArguments,
startStopped: startStopped,
attachToConsole: true,
logOutputFile: output,
interactiveMode: true,
);
Timer? timer;
try {
final Process launchProcess = await _processUtils.start(command);
coreDeviceLogForwarder.launchProcess = launchProcess;
@ -785,13 +779,16 @@ class IOSCoreDeviceControl {
final StreamSubscription<String> stdoutSubscription = launchProcess.stdout
.transform(utf8LineDecoder)
.listen((String line) {
if (line.trim().isEmpty) {
return;
}
if (launchCompleter.isCompleted && !_ignoreLog(line)) {
coreDeviceLogForwarder.addLog(line);
} else {
_logger.printTrace(line);
}
if (!launchCompleter.isCompleted && line.contains(kCoreDeviceLaunchCompleteLog)) {
if (line.contains('Waiting for the application to terminate')) {
launchCompleter.complete(true);
}
});
@ -799,6 +796,9 @@ class IOSCoreDeviceControl {
final StreamSubscription<String> stderrSubscription = launchProcess.stderr
.transform(utf8LineDecoder)
.listen((String line) {
if (line.trim().isEmpty) {
return;
}
if (launchCompleter.isCompleted && !_ignoreLog(line)) {
coreDeviceLogForwarder.addLog(line);
} else {
@ -821,26 +821,14 @@ class IOSCoreDeviceControl {
}),
);
// Sometimes devicectl launch logs don't stream to stdout.
// As a workaround, we also use the log output file to check if it has finished launching.
timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
if (await output.exists()) {
final String contents = await output.readAsString();
if (!launchCompleter.isCompleted && contents.contains(kCoreDeviceLaunchCompleteLog)) {
launchCompleter.complete(true);
}
}
});
// Do not return the launchCompleter.future directly, otherwise, the timer will be canceled
// prematurely.
final bool status = await launchCompleter.future;
return status;
// devicectl is running in an interactive shell.
// Signal script child jobs to exit and exit the shell.
// See https://linux.die.net/Bash-Beginners-Guide/sect_12_01.html#sect_12_01_01_02.
shutdownHooks.addShutdownHook(() => launchProcess.kill());
return launchCompleter.future;
} on ProcessException catch (err) {
_logger.printTrace('Error executing devicectl: $err');
return false;
} finally {
timer?.cancel();
}
}

View File

@ -1055,6 +1055,7 @@ class IOSDevice extends Device {
bundlePath: package.deviceBundlePath,
bundleId: package.id,
launchArguments: launchArguments,
shutdownHooks: globals.shutdownHooks,
);
// If it succeeds to launch with LLDB, return, otherwise continue on to

View File

@ -55,6 +55,8 @@ class LocalFileSystemFake extends Fake implements LocalFileSystem {
var _disposed = false;
}
final _interactiveModeArgs = <String>['script', '-t', '0', '/dev/null'];
void main() {
late MemoryFileSystem fileSystem;
@ -214,6 +216,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isTrue);
@ -263,6 +266,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -306,6 +310,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -355,6 +360,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -398,6 +404,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -443,6 +450,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -490,6 +498,7 @@ void main() {
bundlePath: 'bundle-path',
bundleId: 'bundle-id',
launchArguments: <String>[],
shutdownHooks: FakeShutdownHooks(),
);
expect(result, isFalse);
@ -1778,8 +1787,9 @@ invalid JSON
testWithoutContext('Successful launch without launch args', () async {
fakeProcessManager.addCommand(
const FakeCommand(
FakeCommand(
command: <String>[
..._interactiveModeArgs,
'xcrun',
'devicectl',
'device',
@ -1791,8 +1801,6 @@ invalid JSON
'--console',
'--environment-variables',
'{"OS_ACTIVITY_DT_MODE": "enable"}',
'--log-output',
'/.tmp_rand0/core_devices.rand0/launch_log.txt',
bundleId,
],
stdout: '''
@ -1805,22 +1813,26 @@ Waiting for the application to terminate...
),
);
final shutdownHooks = FakeShutdownHooks();
final bool result = await deviceControl.launchAppAndStreamLogs(
deviceId: deviceId,
bundleId: bundleId,
coreDeviceLogForwarder: FakeIOSCoreDeviceLogForwarder(),
startStopped: true,
shutdownHooks: shutdownHooks,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
expect(shutdownHooks.registeredHooks.length, 1);
expect(logger.errorText, isEmpty);
expect(result, isTrue);
});
testWithoutContext('Successful launch with launch args', () async {
fakeProcessManager.addCommand(
const FakeCommand(
FakeCommand(
command: <String>[
..._interactiveModeArgs,
'xcrun',
'devicectl',
'device',
@ -1832,8 +1844,6 @@ Waiting for the application to terminate...
'--console',
'--environment-variables',
'{"OS_ACTIVITY_DT_MODE": "enable"}',
'--log-output',
'/.tmp_rand0/core_devices.rand0/launch_log.txt',
bundleId,
'--arg1',
'--arg2',
@ -1847,24 +1857,27 @@ Waiting for the application to terminate...
''',
),
);
final shutdownHooks = FakeShutdownHooks();
final bool result = await deviceControl.launchAppAndStreamLogs(
deviceId: deviceId,
bundleId: bundleId,
coreDeviceLogForwarder: FakeIOSCoreDeviceLogForwarder(),
startStopped: true,
launchArguments: ['--arg1', '--arg2'],
shutdownHooks: shutdownHooks,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
expect(shutdownHooks.registeredHooks.length, 1);
expect(logger.errorText, isEmpty);
expect(result, isTrue);
});
testWithoutContext('Successful stream logs', () async {
fakeProcessManager.addCommand(
const FakeCommand(
FakeCommand(
command: <String>[
..._interactiveModeArgs,
'xcrun',
'devicectl',
'device',
@ -1876,8 +1889,6 @@ Waiting for the application to terminate...
'--console',
'--environment-variables',
'{"OS_ACTIVITY_DT_MODE": "enable"}',
'--log-output',
'/.tmp_rand0/core_devices.rand0/launch_log.txt',
bundleId,
],
stdout: '''
@ -1896,14 +1907,17 @@ This log happens after the application is launched and should be sent to FakeIOS
),
);
final logForwarder = FakeIOSCoreDeviceLogForwarder();
final shutdownHooks = FakeShutdownHooks();
final bool result = await deviceControl.launchAppAndStreamLogs(
deviceId: deviceId,
bundleId: bundleId,
coreDeviceLogForwarder: logForwarder,
startStopped: true,
shutdownHooks: shutdownHooks,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
expect(shutdownHooks.registeredHooks.length, 1);
expect(logger.errorText, isEmpty);
expect(logForwarder.logs.length, 3);
expect(
@ -1932,8 +1946,9 @@ Waiting for the application to terminate...
testWithoutContext('devicectl fails launch with an error', () async {
fakeProcessManager.addCommand(
const FakeCommand(
FakeCommand(
command: <String>[
..._interactiveModeArgs,
'xcrun',
'devicectl',
'device',
@ -1945,8 +1960,6 @@ Waiting for the application to terminate...
'--console',
'--environment-variables',
'{"OS_ACTIVITY_DT_MODE": "enable"}',
'--log-output',
'/.tmp_rand0/core_devices.rand0/launch_log.txt',
bundleId,
],
exitCode: 1,
@ -1957,66 +1970,20 @@ ERROR: The operation couldn?t be completed. (OSStatus error -10814.) (NSOSStatus
''',
),
);
final shutdownHooks = FakeShutdownHooks();
final bool result = await deviceControl.launchAppAndStreamLogs(
deviceId: deviceId,
bundleId: bundleId,
coreDeviceLogForwarder: FakeIOSCoreDeviceLogForwarder(),
startStopped: true,
shutdownHooks: shutdownHooks,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
expect(shutdownHooks.registeredHooks.length, 1);
expect(logger.errorText, isEmpty);
expect(result, isFalse);
});
testWithoutContext('Successful launch with output in log file', () async {
final Completer<void> launchCompleter = Completer();
fakeProcessManager.addCommand(
FakeCommand(
command: const <String>[
'xcrun',
'devicectl',
'device',
'process',
'launch',
'--device',
deviceId,
'--start-stopped',
'--console',
'--environment-variables',
'{"OS_ACTIVITY_DT_MODE": "enable"}',
'--log-output',
'/.tmp_rand0/core_devices.rand0/launch_log.txt',
bundleId,
],
onRun: (command) {
fileSystem.file('/.tmp_rand0/core_devices.rand0/launch_log.txt')
..createSync(recursive: true)
..writeAsStringSync('''
10:04:12 Acquired tunnel connection to device.
10:04:12 Enabling developer disk image services.
10:04:12 Acquired usage assertion.
Launched application with com.example.my_app bundle identifier.
Waiting for the application to terminate...
''');
},
completer: launchCompleter,
),
);
final bool result = await deviceControl.launchAppAndStreamLogs(
deviceId: deviceId,
bundleId: bundleId,
coreDeviceLogForwarder: FakeIOSCoreDeviceLogForwarder(),
startStopped: true,
);
launchCompleter.complete();
expect(fakeProcessManager, hasNoRemainingExpectations);
expect(logger.errorText, isEmpty);
expect(result, isTrue);
});
});
group('terminate app', () {
@ -3883,6 +3850,7 @@ class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl {
required IOSCoreDeviceLogForwarder coreDeviceLogForwarder,
required String deviceId,
required String bundleId,
required ShutdownHooks shutdownHooks,
List<String> launchArguments = const <String>[],
bool startStopped = false,
}) async {
@ -4086,3 +4054,23 @@ class FakeIOSCoreDeviceLogForwarder extends Fake implements IOSCoreDeviceLogForw
logs.add(log);
}
}
/// A [ShutdownHooks] implementation that does not actually execute any hooks.
class FakeShutdownHooks extends Fake implements ShutdownHooks {
@override
bool get isShuttingDown => _isShuttingDown;
var _isShuttingDown = false;
@override
final registeredHooks = <ShutdownHook>[];
@override
void addShutdownHook(ShutdownHook shutdownHook) {
registeredHooks.add(shutdownHook);
}
@override
Future<void> runShutdownHooks(Logger logger) async {
_isShuttingDown = true;
}
}

View File

@ -12,6 +12,7 @@ import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/base/version.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
@ -1715,6 +1716,7 @@ class FakeIOSCoreDeviceLauncher extends Fake implements IOSCoreDeviceLauncher {
required String bundlePath,
required String bundleId,
required List<String> launchArguments,
required ShutdownHooks shutdownHooks,
}) async {
return true;
}

View File

@ -11,6 +11,7 @@ import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/base/template.dart';
import 'package:flutter_tools/src/base/version.dart';
import 'package:flutter_tools/src/build_info.dart';
@ -1802,6 +1803,7 @@ class FakeIOSCoreDeviceLauncher extends Fake implements IOSCoreDeviceLauncher {
required String bundlePath,
required String bundleId,
required List<String> launchArguments,
required ShutdownHooks shutdownHooks,
}) async {
launchedWithLLDB = true;
return lldbLaunchResult;