Files
pipelines/app/tool/perf/terminal_stream_bench.dart
T
alan 018d37f103 Terminal: grapheme-aware widths, drawn box/Powerline glyphs, line pictures
Emulator (vendored xterm):
- Widths follow glibc wcwidth on generated Unicode 16 tables
  (tool/gen_unicode_tables.py); combining marks, variation selectors,
  ZWJ sequences, skin tones, flags and Hangul jamo join the previous cell,
  stored as interned clusters (CellContent.clusterFlag) and drawn and
  copied whole. U+FE0F and flags take two columns, as modern terminals
  do; a wide character never starts in the last column.
- Box drawing, block elements and Powerline separators are drawn as
  geometry filling the cell; rows are whole pixels high.
- Backgrounds merge per colour; each line is a picture reused until the
  line changes (BufferLine.version); a line drawn unchanged settles into
  one laid out paragraph with a span per style. TerminalStyle and
  TerminalTheme compare by value.

App: bundled Symbols Nerd Font Mono subset (568 KiB, MIT) as the
terminal's first fallback, loaded on first use; line height 1.1;
?terminalUnicode=1 fixture showcase; bench gains a progress workload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:14:48 +00:00

216 lines
6.9 KiB
Dart

// Terminal rendering bench: the app's emulator view (theme, text style and
// the sliced output feed the terminals use) streaming generated output at a
// fixed rate, with Flutter frame timings and rAF intervals recorded.
//
// Build (from app/):
// 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).
// 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.
import 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_theme.dart';
import 'package:xterm/xterm.dart';
@JS('__benchResult')
external set _benchResult(JSString value);
void main() {
final params = Uri.base.queryParameters;
runApp(_Bench(params));
}
class _Bench extends StatefulWidget {
const _Bench(this.params);
final Map<String, String> params;
@override
State<_Bench> createState() => _BenchState();
}
class _BenchState extends State<_Bench> {
late final Terminal _terminal = Terminal(maxLines: 10000);
late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed(
(text, _) => _terminal.write(text),
);
final List<FrameTiming> _timings = [];
final List<double> _intervals = [];
Duration? _lastFrame;
Timer? _producer;
final Stopwatch _clock = Stopwatch();
int _written = 0;
int _counter = 0;
bool _done = false;
String get _workload => widget.params['workload'] ?? 'seq';
double get _megabytes => double.tryParse(widget.params['mb'] ?? '') ?? 30;
double get _rate => double.tryParse(widget.params['rate'] ?? '') ?? 30;
@override
void initState() {
super.initState();
SchedulerBinding.instance.addTimingsCallback(_onTimings);
SchedulerBinding.instance.addPersistentFrameCallback(_onFrame);
// Let the first frames settle before streaming.
Timer(const Duration(milliseconds: 1500), _start);
}
void _onTimings(List<FrameTiming> timings) {
if (_clock.isRunning) _timings.addAll(timings);
}
void _onFrame(Duration stamp) {
if (_clock.isRunning && _lastFrame != null) {
_intervals.add((stamp - _lastFrame!).inMicroseconds / 1000);
}
_lastFrame = stamp;
}
void _start() {
_clock.start();
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);
});
}
String _chunk(int size) {
final out = StringBuffer();
while (out.length < size) {
_counter++;
switch (_workload) {
case 'yes':
out.write('y\r\n');
case 'unicode':
out.write(
'$_counter e\u0301 \u00F1 \u4E2D\u6587 \u{1F600} \u{1F44D}\u{1F3FD} \u{1F1F5}\u{1F1F9} \u2502 \u256D\u2500\u256E \u2593\u2592\u2591 \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':
// A full-screen program redrawing every row (top, an editor).
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':
// A screen of text, then one status line rewritten in place (a
// progress bar, a build counter): one row changes per frame.
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();
}
void _finish() {
if (_done) return;
_done = true;
// 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,
];
final result = {
'workload': _workload,
'frames': _timings.length,
'build': _quantiles(ms((t) => t.buildDuration)),
'raster': _quantiles(ms((t) => t.rasterDuration)),
'total': _quantiles(ms((t) => t.totalSpan)),
'interval': _quantiles(_intervals),
'mb': _written / 1e6,
'seconds': seconds,
'mbPerSecond': _written / 1e6 / seconds,
};
_benchResult = jsonEncode(result).toJS;
// ignore: avoid_print
print('BENCH_RESULT ${jsonEncode(result)}');
});
}
static Map<String, double> _quantiles(List<double> values) {
if (values.isEmpty) return const {};
final sorted = [...values]..sort();
double at(double q) =>
sorted[(q * (sorted.length - 1)).round().clamp(0, sorted.length - 1)];
double round(double v) => (v * 100).roundToDouble() / 100;
return {
'p50': round(at(0.5)),
'p90': round(at(0.9)),
'p99': round(at(0.99)),
'max': round(sorted.last),
'mean': round(sorted.reduce((a, b) => a + b) / sorted.length),
};
}
@override
void dispose() {
_producer?.cancel();
_feed.dispose();
SchedulerBinding.instance.removeTimingsCallback(_onTimings);
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(brightness: Brightness.dark),
home: Builder(
builder: (context) => Scaffold(
body: TerminalView(
_terminal,
theme: chatShellTerminalTheme(context),
textStyle: chatShellTerminalStyle(context),
padding: const EdgeInsets.all(8),
readOnly: true,
),
),
),
);
}
}