Files
pipelines/app/tool/settings_probe_capture.dart
alan b60ad6d98f Remove alternate hosts from tooling probes
Keep the probe suite on the Material composition so browser fixtures and capture drivers no longer render or select Cupertino hosts. Record the final residual legacy arguments and implementation checks for the delivery gate.
2026-11-11 21:38:30 +00:00

315 lines
9.9 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// Drives the Settings probe in real headless Chrome through the DevTools
/// protocol and writes PNG captures. It only talks to the local probe origin
/// passed with `--url`; it never contacts the production server.
///
/// Usage:
/// dart run tool/settings_probe_capture.dart \
/// --url http://127.0.0.1:PORT/ --out /path/to/captures
///
/// Set CHROME_PATH if Chrome is not at the default macOS location.
Future<void> main(List<String> arguments) async {
final url = _argument(arguments, '--url');
final outPath = _argument(arguments, '--out');
if (url == null || outPath == null) {
stderr.writeln('usage: ... --url URL --out DIRECTORY');
exitCode = 64;
return;
}
final out = Directory(outPath)..createSync(recursive: true);
final chromePath =
Platform.environment['CHROME_PATH'] ??
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
final profile = await Directory.systemTemp.createTemp('settings-probe-');
final chrome = await Process.start(chromePath, <String>[
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
'--remote-debugging-port=0',
'--user-data-dir=${profile.path}',
'about:blank',
]);
final stderrLines = chrome.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.asBroadcastStream();
try {
final browserWs = await stderrLines
.firstWhere((line) => line.contains('DevTools listening on '))
.timeout(const Duration(seconds: 20));
final browserUrl = browserWs.substring(browserWs.indexOf('ws://'));
final parsed = Uri.parse(browserUrl);
final pageWs = await _pageTarget(parsed);
final cdp = Cdp(await WebSocket.connect(pageWs));
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
final scenarios = <String>[
'idle',
'connected',
'validation',
'workspace',
'dark',
'narrow',
];
for (final scenario in scenarios) {
await _runScenario(cdp, url, out, scenario);
stdout.writeln('captured $scenario');
}
await cdp.close();
} finally {
chrome.kill(ProcessSignal.sigterm);
await profile.delete(recursive: true).catchError((_) => profile);
}
}
Future<void> _runScenario(
Cdp cdp,
String base,
Directory out,
String scenario,
) async {
var target = base;
var width = 1200;
var height = 900;
switch (scenario) {
case 'idle':
break;
case 'connected':
target = '$base?connect=1';
break;
case 'validation':
target = '$base?endpoint=http%3A%2F%2Fexample.test';
break;
case 'workspace':
target = '$base?connect=1';
break;
case 'dark':
target = '$base?connect=1&theme=dark';
break;
case 'narrow':
width = 390;
height = 844;
target = '$base?connect=1&scale=1.6';
}
await cdp.send('Emulation.setDeviceMetricsOverride', <String, dynamic>{
'width': width,
'height': height,
'deviceScaleFactor': 1,
'mobile': false,
});
await cdp.send('Page.navigate', <String, dynamic>{'url': target});
await Future<void>.delayed(const Duration(seconds: 4));
if (scenario == 'validation' || scenario == 'workspace') {
await _enableSemantics(cdp);
if (scenario == 'validation') {
await _click(cdp, 'Connect');
await Future<void>.delayed(const Duration(milliseconds: 800));
} else {
await _typeWorkspace(cdp, '/srv/pipelines');
await _click(cdp, 'Save workspace');
await Future<void>.delayed(const Duration(milliseconds: 800));
}
}
final shot = await cdp.send('Page.captureScreenshot', <String, dynamic>{
'format': 'png',
'captureBeyondViewport': false,
});
final data = (shot['result'] as Map)['data'] as String;
File(
'${out.path}/settings-$scenario.png',
).writeAsBytesSync(base64Decode(data));
}
Future<void> _enableSemantics(Cdp cdp) async {
await cdp.evaluate('''
(() => {
const placeholder = document.querySelector('flt-semantics-placeholder');
if (placeholder) {
placeholder.click();
return 'semantics requested';
}
return 'no placeholder';
})()
''');
await Future<void>.delayed(const Duration(milliseconds: 900));
if (Platform.environment['DUMP_DOM'] == '1') {
stdout.writeln(
await cdp.evaluate(
"document.querySelector('flt-semantics-host')?.innerHTML ?? 'none'",
),
);
}
}
Future<void> _click(Cdp cdp, String label) async {
final result = await cdp.evaluate('''
(() => {
const byLabel = [...document.querySelectorAll('[aria-label]')]
.find((element) => element.getAttribute('aria-label') === ${jsonEncode(label)});
const byRole = [...document.querySelectorAll('[role="button"]')]
.find((element) => (element.textContent || '').trim() === ${jsonEncode(label)});
const target = byLabel || byRole;
if (!target) {
return 'missing; labels=' + [...document.querySelectorAll('[aria-label]')]
.map((element) => element.getAttribute('aria-label')).join('|') +
'; roles=' + [...document.querySelectorAll('[role="button"]')]
.map((element) => (element.textContent || '').trim()).join('|');
}
target.click();
return 'clicked ' + target.tagName + ' ' + (target.getAttribute('role') || '');
})()
''');
stdout.writeln('click "$label": $result');
}
Future<void> _typeWorkspace(Cdp cdp, String value) async {
final found = await cdp.evaluate('''
(() => {
const target = [...document.querySelectorAll('[aria-label]')]
.find((element) => (element.getAttribute('aria-label') || '')
.startsWith('Workspace path'));
if (!target) return 'missing';
target.click();
target.focus();
return 'focused ' + target.tagName;
})()
''');
stdout.writeln('workspace field: $found');
await Future<void>.delayed(const Duration(milliseconds: 400));
final rect = await cdp.evaluate('''
(() => {
const target = [...document.querySelectorAll('[aria-label]')]
.find((element) => (element.getAttribute('aria-label') || '')
.startsWith('Workspace path'));
if (!target) return null;
const r = target.getBoundingClientRect();
return {x: r.left + r.width / 2, y: r.top + r.height / 2};
})()
''');
if (rect != 'null') {
final match = RegExp(r'x: ([0-9.]+), y: ([0-9.]+)').firstMatch(rect);
if (match != null) {
final x = double.parse(match.group(1)!);
final y = double.parse(match.group(2)!);
for (final type in <String>['mousePressed', 'mouseReleased']) {
await cdp.send('Input.dispatchMouseEvent', <String, dynamic>{
'type': type,
'x': x,
'y': y,
'button': 'left',
'clickCount': 1,
});
}
await Future<void>.delayed(const Duration(milliseconds: 300));
}
}
await cdp.send('Input.insertText', <String, dynamic>{'text': value});
await Future<void>.delayed(const Duration(milliseconds: 300));
final typed = await cdp.evaluate('''
(() => {
const el = document.activeElement;
if (!el) return 'no active element';
if (el.value === ${jsonEncode(value)}) return 'insertText worked';
el.value = ${jsonEncode(value)};
el.dispatchEvent(new InputEvent('input', {
bubbles: true,
inputType: 'insertText',
data: ${jsonEncode(value)},
}));
el.dispatchEvent(new Event('change', {bubbles: true}));
return 'dispatched input; value=' + el.value;
})()
''');
stdout.writeln('workspace input: $typed');
await Future<void>.delayed(const Duration(milliseconds: 500));
}
Future<String> _pageTarget(Uri browserWs) async {
final client = HttpClient();
try {
final request = await client.getUrl(
Uri(
scheme: 'http',
host: browserWs.host,
port: browserWs.port,
path: '/json/list',
),
);
final response = await request.close();
final body = await response.transform(utf8.decoder).join();
final targets = jsonDecode(body) as List<dynamic>;
final page = targets.cast<Map<String, dynamic>>().firstWhere(
(target) => target['type'] == 'page',
);
return page['webSocketDebuggerUrl'] as String;
} finally {
client.close(force: true);
}
}
String? _argument(List<String> arguments, String name) {
final index = arguments.indexOf(name);
if (index < 0 || index + 1 >= arguments.length) return null;
return arguments[index + 1];
}
class Cdp {
Cdp(this._socket) {
_socket.listen(_onMessage);
}
final WebSocket _socket;
final Map<int, Completer<Map<String, dynamic>>> _pending = {};
int _next = 0;
Future<Map<String, dynamic>> send(
String method, [
Map<String, dynamic> params = const <String, dynamic>{},
]) {
final id = ++_next;
final completer = Completer<Map<String, dynamic>>();
_pending[id] = completer;
_socket.add(
jsonEncode(<String, dynamic>{
'id': id,
'method': method,
'params': params,
}),
);
return completer.future.timeout(const Duration(seconds: 30));
}
Future<String> evaluate(String expression) async {
final reply = await send('Runtime.evaluate', <String, dynamic>{
'expression': expression,
'returnByValue': true,
'awaitPromise': true,
});
final result = reply['result'] as Map<String, dynamic>;
return '${result['result']?['value']}';
}
void _onMessage(dynamic data) {
if (data is! String) return;
final message = jsonDecode(data) as Map<String, dynamic>;
final id = message['id'];
if (id is! int) return;
final completer = _pending.remove(id);
if (completer == null) return;
final error = message['error'];
if (error != null) {
completer.completeError(StateError('$error'));
} else {
completer.complete(message);
}
}
Future<void> close() => _socket.close();
}