Merge branch 'worktree-agent-afe96053a37e02d6f'

This commit is contained in:
2026-11-26 03:27:28 +00:00
23 changed files with 1198 additions and 110 deletions
+110
View File
@@ -0,0 +1,110 @@
// Emulator parse bench in the Dart VM: feeds generated output into
// `Terminal.write` in the app's feed slices (16 Ki units) and prints MB/s
// per workload. Pure Dart (the emulator core has no Flutter imports).
//
// dart run tool/perf/terminal_parse_bench.dart [--mb 16] [--workloads seq,yes,...]
//
// In V8, as the web build runs it:
// dart compile js -O2 -Dworkloads=seq,yes tool/perf/terminal_parse_bench.dart -o /tmp/parse.js
// node -e "globalThis.self = globalThis; require('/tmp/parse.js')"
//
// Workloads match tool/perf/terminal_stream_bench.dart.
import 'package:xterm/core.dart';
void main(List<String> args) {
var megabytes = 16.0;
var workloads = ['seq', 'yes', 'unicode', 'colors', 'screen', 'progress'];
// Compiled to JavaScript (dart compile js, run in node) there are no
// arguments: -Dworkloads=seq,yes picks them.
const only = String.fromEnvironment('workloads');
if (only.isNotEmpty) workloads = only.split(',');
for (var i = 0; i + 1 < args.length; i++) {
if (args[i] == '--mb') megabytes = double.parse(args[i + 1]);
if (args[i] == '--workloads') workloads = args[i + 1].split(',');
}
for (final workload in workloads) {
final data = generateWorkload(workload, (megabytes * 1e6).round());
// Warm up, then measure the best of three.
_run(data.substring(0, data.length ~/ 8));
var best = double.infinity;
for (var round = 0; round < 3; round++) {
final seconds = _run(data);
if (seconds < best) best = seconds;
}
final mb = data.length / 1e6;
// ignore: avoid_print
print(
'{"workload":"$workload","mb":${mb.toStringAsFixed(2)},'
'"seconds":${best.toStringAsFixed(3)},'
'"mbPerSecond":${(mb / best).toStringAsFixed(2)}}',
);
}
}
double _run(String data) {
final terminal = Terminal(maxLines: 10000);
terminal.resize(158, 48);
var notified = 0;
terminal.addListener(() => notified++);
const slice = 16 * 1024;
final clock = Stopwatch()..start();
for (var at = 0; at < data.length; at += slice) {
final end = at + slice < data.length ? at + slice : data.length;
terminal.write(data.substring(at, end));
}
clock.stop();
if (notified == 0) throw StateError('no writes');
return clock.elapsedMicroseconds / 1e6;
}
/// Generated output of about [size] UTF-16 units, as the web bench makes.
String generateWorkload(String workload, int size) {
final out = StringBuffer();
var counter = 0;
while (out.length < size) {
counter++;
switch (workload) {
case 'yes':
out.write('y\r\n');
case 'unicode':
out.write(
'$counter é ñ 中文 \u{1F600} \u{1F44D}\u{1F3FD} '
'\u{1F1F5}\u{1F1F9} │ ╭─╮ ▓▒░ '
'\u{E0B0} done\r\n',
);
case 'colors':
final c = 31 + counter % 7;
out.write(
'\x1b[${c}m$counter\x1b[0m \x1b[1mbold\x1b[0m '
'plain text line with some words\r\n',
);
case 'screen':
out.write('\x1b[H');
for (var row = 0; row < 48; row++) {
final c = 31 + (row + counter) % 7;
out.write(
'\x1b[${c}m${(counter + row).toString().padLeft(8)}'
'\x1b[0m \x1b[7m cpu ${row % 100}% \x1b[0m '
'${'process name and arguments ' * 4}\x1b[K\r\n',
);
}
case 'progress':
if (counter == 1) {
for (var row = 0; row < 47; row++) {
out.write(
'\x1b[3${row % 7 + 1}mline $row\x1b[0m '
'${'static output that does not change ' * 3}\r\n',
);
}
}
final done = counter % 50;
out.write(
'\r\x1b[1m[${'#' * done}${'.' * (50 - done)}]\x1b[0m '
'$counter files',
);
default:
out.write('$counter\r\n');
}
}
return out.toString();
}
+43 -7
View File
@@ -6,7 +6,10 @@
// flutter build web --profile --target tool/perf/terminal_stream_bench.dart \
// --output build/terminal-bench
// Run with tool/perf/terminal_stream_bench.mjs, or open the page with
// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30` (the window size sets the grid).
// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30&window=256`
// (the window size sets the grid; `rate` MB/s caps the producer and
// `window` KiB is how far it may run ahead of what is drawn, as the
// server's flow control, 0 for no limit).
// When the stream ends `window.__benchResult` holds a JSON summary:
// frames, build/raster/total quantiles (ms), rAF interval quantiles (ms),
// MB written, seconds and MB/s.
@@ -40,14 +43,27 @@ class _Bench extends StatefulWidget {
class _BenchState extends State<_Bench> {
late final Terminal _terminal = Terminal(maxLines: 10000);
// Wired as ChatShellTerminalSession wires its feed.
late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed(
(text, _) => _terminal.write(text),
(text, _) {
_parsing.start();
_terminal.write(text, notify: _notifyEachWrite);
_parsing.stop();
},
show: _notifyEachWrite ? null : _terminal.notifyListeners,
);
/// `?show=each`: every write notifies the view, as before frames were
/// coalesced.
bool get _notifyEachWrite => widget.params['show'] == 'each';
final List<FrameTiming> _timings = [];
final List<double> _intervals = [];
Duration? _lastFrame;
Timer? _producer;
final Stopwatch _clock = Stopwatch();
/// Time spent in the emulator's writes (parsing into the buffer).
final Stopwatch _parsing = Stopwatch();
int _written = 0;
int _counter = 0;
bool _done = false;
@@ -76,19 +92,35 @@ class _BenchState extends State<_Bench> {
_lastFrame = stamp;
}
/// KiB the producer may run ahead of what the feed has drawn, as the
/// server's flow window (256 KiB); 0 for no limit.
double get _window => double.tryParse(widget.params['window'] ?? '') ?? 256;
void _start() {
_clock.start();
// Every tick tops the output up to what the rate allows by now, at most
// a flow window past what is drawn: late ticks (a long frame) catch up,
// and a slow emulator holds the producer back as the server's flow
// control does.
const tick = Duration(milliseconds: 4);
final perTick = (_rate * 1e6 * tick.inMicroseconds / 1e6).round();
_producer = Timer.periodic(tick, (_) {
if (_written >= _megabytes * 1e6) {
_producer?.cancel();
_feed.then(_finish);
return;
}
final chunk = _chunk(perTick);
_written += chunk.length;
_feed.add(chunk, _written);
var allowed = _rate * 1e6 * _clock.elapsedMicroseconds / 1e6;
if (_window > 0) {
final ahead = _feed.drawn + _window * 1024;
if (ahead < allowed) allowed = ahead;
}
// In frames of at most 32 KiB, as the server sends a PTY's reads.
while (allowed - _written >= 1024) {
final size = allowed - _written;
final chunk = _chunk(size < 32768 ? size.round() : 32768);
_written += chunk.length;
_feed.add(chunk, _written);
}
});
}
@@ -146,11 +178,12 @@ class _BenchState extends State<_Bench> {
void _finish() {
if (_done) return;
_done = true;
// The stream took this long; the wait below only collects timings.
final seconds = _clock.elapsedMicroseconds / 1e6;
// A last frame flushes the engine's batched timings.
SchedulerBinding.instance.scheduleFrame();
Timer(const Duration(milliseconds: 600), () {
_clock.stop();
final seconds = _clock.elapsedMicroseconds / 1e6;
List<double> ms(Duration Function(FrameTiming t) pick) => [
for (final t in _timings) pick(t).inMicroseconds / 1000,
];
@@ -164,6 +197,9 @@ class _BenchState extends State<_Bench> {
'mb': _written / 1e6,
'seconds': seconds,
'mbPerSecond': _written / 1e6 / seconds,
'parseSeconds': _parsing.elapsedMicroseconds / 1e6,
'parseMbPerSecond':
_written / 1e6 / (_parsing.elapsedMicroseconds / 1e6),
};
_benchResult = jsonEncode(result).toJS;
// ignore: avoid_print
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
// CPU profile of one terminal bench workload (tool/perf/terminal_stream_bench.dart)
// in headless Chrome: prints the functions with the most self and total
// time while the stream runs, and the bench's own summary line.
//
// node tool/perf/terminal_stream_profile.mjs --build build/terminal-bench \
// [--workload seq] [--mb 8] [--top 40] [--out profile.cpuprofile]
import { parseArgs } from 'node:util';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
import { openBrowser } from '../capture/browser.mjs';
import { serveBuild } from '../capture/serve.mjs';
const { values: options } = parseArgs({
options: {
build: { type: 'string' },
workload: { type: 'string', default: 'seq' },
mb: { type: 'string', default: '8' },
rate: { type: 'string', default: '30' },
top: { type: 'string', default: '40' },
out: { type: 'string' },
size: { type: 'string', default: '1280x800' },
},
});
if (!options.build) throw new Error('--build required');
const [width, height] = options.size.split('x').map(Number);
const server = await serveBuild(options.build);
const browser = await openBrowser();
const evaluate = async (expression) =>
(await browser.send('Runtime.evaluate', { expression, returnByValue: true })).result.value;
try {
await browser.send('Page.enable');
await browser.send('Runtime.enable');
await browser.send('Profiler.enable');
await browser.send('Profiler.setSamplingInterval', { interval: 200 });
await browser.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
const url = new URL('/', server.origin);
url.searchParams.set('workload', options.workload);
url.searchParams.set('mb', options.mb);
url.searchParams.set('rate', options.rate);
await browser.send('Page.navigate', { url: url.href });
// The bench streams 1.5 s after start-up; profile from then on.
await delay(1500);
await browser.send('Profiler.start');
let result = null;
for (let i = 0; i < 600 && !result; i++) {
await delay(250);
result = await evaluate('window.__benchResult ?? null');
}
const { profile } = await browser.send('Profiler.stop');
if (options.out) await writeFile(options.out, JSON.stringify(profile));
const byId = new Map(profile.nodes.map((n) => [n.id, n]));
const parent = new Map();
for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n.id);
const hits = new Map();
for (const s of profile.samples) hits.set(s, (hits.get(s) ?? 0) + 1);
const name = (n) => `${n.callFrame.functionName || '(anonymous)'} ${n.callFrame.url.split('/').pop()}:${n.callFrame.lineNumber}`;
const self = new Map();
const total = new Map();
let all = 0;
for (const [id, count] of hits) {
all += count;
const key = name(byId.get(id));
self.set(key, (self.get(key) ?? 0) + count);
const seen = new Set();
for (let at = id; at !== undefined; at = parent.get(at)) {
const k = name(byId.get(at));
if (seen.has(k)) continue;
seen.add(k);
total.set(k, (total.get(k) ?? 0) + count);
}
}
const pct = (v) => (100 * v / all).toFixed(1).padStart(5);
const top = Number(options.top);
console.log(`samples ${all}`);
console.log('--- self');
for (const [k, v] of [...self].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(v), pct(total.get(k)), k);
console.log('--- total');
for (const [k, v] of [...total].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(self.get(k) ?? 0), pct(v), k);
console.log(result);
} finally {
await browser.close?.();
await server.close?.();
}