Terminal feed: message-task yields, slices sized to speed, one show per frame

- On the web a turn yields through a MessageChannel task: a chain of
  zero-length timers is clamped to 4 ms each, which left the emulator
  idle for a third of a burst.
- Slices are cut to what the measured speed writes in the budget left,
  so a turn ends near 6 ms however costly the output is to parse; the
  first write takes 4 Ki units to measure.
- Writes no longer notify the view each: the feed shows the emulator's
  state once everything queued is written, and while output still waits
  after a turn at most every 32 ms, so a flood draws its final state per
  frame instead of a frame per turn.
- Stream bench: producer follows a flow window (256 KiB past drawn, 32 KiB
  frames, rate by elapsed time), reports time spent parsing, ?show=each
  for the old per-write notify; tool/perf/terminal_stream_profile.mjs
  prints a CPU profile of one workload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 02:52:41 +00:00
parent f7ef4d1445
commit ae07fe14db
8 changed files with 328 additions and 21 deletions
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:collection';
import 'chat_shell_terminal_yield.dart';
/// UTF-16 units one emulator write takes at most.
const int chatShellFeedSlice = 16 * 1024;
@@ -8,32 +9,66 @@ const int chatShellFeedSlice = 16 * 1024;
/// large replay or burst never holds a UI frame for long.
const Duration chatShellFeedBudget = Duration(milliseconds: 6);
/// While output waits after a turn, the view is shown the emulator's state
/// at most this often (about 30 frames a second), so a flood spends its
/// time parsing rather than drawing screens nobody can read.
const Duration chatShellFeedShowGap = Duration(milliseconds: 32);
/// The fewest units a write takes while more waits, however slow the
/// output has been to write.
const int _minimumSlice = 1024;
/// The units the first write takes, before the speed is known.
const int _firstSlice = 4096;
/// Output on its way into one emulator, in order: written in slices of at
/// most [slice] units, and after [budget] of writing the rest waits for the
/// next turn of the event loop. Each piece carries the server's absolute
/// byte offset its text ends at; [drawn] is the end of the last piece
/// written whole (what a terminal acknowledges as consumed).
/// next turn of the event loop ([chatShellYield]). A slice is cut to what
/// the measured speed writes in the budget left, so a turn ends close to
/// the budget however costly the output is to parse. Each piece carries
/// the server's absolute byte offset its text ends at; [drawn] is the end
/// of the last piece written whole (what a terminal acknowledges as
/// consumed).
///
/// With [show], writes do not notify the view themselves: [show] is called
/// once everything queued is written, and while output still waits after
/// a turn at most every [showGap], so a burst draws its final state per
/// frame instead of one frame per turn.
class ChatShellTerminalFeed {
ChatShellTerminalFeed(
this._write, {
this.show,
this.budget = chatShellFeedBudget,
this.slice = chatShellFeedSlice,
this.showGap = chatShellFeedShowGap,
});
/// Writes [text] into the emulator; [replay] marks a redraw of old output.
final void Function(String text, bool replay) _write;
/// Lets the view show what was written (the emulator's listeners).
final void Function()? show;
final Duration budget;
final int slice;
final Duration showGap;
/// Since [show] was last called; whether anything was written since.
final Stopwatch _sinceShown = Stopwatch()..start();
bool _unshown = false;
/// Called with a piece's end once it is drawn.
void Function(int end)? onDrawn;
final Queue<_Piece> _pieces = Queue();
Timer? _timer;
void Function()? _cancel;
bool _pumping = false;
int _drawn = 0;
int _end = 0;
/// Units written per millisecond, as last measured (0 before a write
/// took measurable time).
double _speed = 0;
/// The end of the output drawn so far.
int get drawn => _drawn;
@@ -46,8 +81,8 @@ class ChatShellTerminalFeed {
/// Drops what waits: the emulator is redrawn and continues from [end].
void restart(int end) {
_pieces.clear();
_timer?.cancel();
_timer = null;
_cancel?.call();
_cancel = null;
_drawn = end;
_end = end;
}
@@ -71,23 +106,35 @@ class ChatShellTerminalFeed {
void dispose() {
_pieces.clear();
_timer?.cancel();
_timer = null;
_cancel?.call();
_cancel = null;
}
void _schedule() {
if (_timer == null && !_pumping) _pump();
if (_cancel == null && !_pumping) _pump();
}
/// Units the next write takes, [elapsed] microseconds into the turn.
int _sliceAt(int elapsed) {
// Unmeasured (the first write, cold code): a small slice to measure.
if (_speed <= 0) return slice < _firstSlice ? slice : _firstSlice;
final left = (budget.inMicroseconds - elapsed) / 1000;
final fits = (_speed * left).floor();
if (fits >= slice) return slice;
final least = slice < _minimumSlice ? slice : _minimumSlice;
return fits < least ? least : fits;
}
void _pump() {
_timer = null;
_cancel = null;
_pumping = true;
final clock = Stopwatch()..start();
try {
while (_pieces.isNotEmpty) {
final piece = _pieces.first;
if (piece.at < piece.text.length) {
var cut = piece.at + slice;
final started = clock.elapsedMicroseconds;
var cut = piece.at + _sliceAt(started);
if (cut >= piece.text.length) {
cut = piece.text.length;
} else if (_highSurrogate(piece.text.codeUnitAt(cut - 1))) {
@@ -95,11 +142,17 @@ class ChatShellTerminalFeed {
cut++;
}
_write(piece.text.substring(piece.at, cut), piece.replay);
_unshown = true;
final took = clock.elapsedMicroseconds - started;
// Small writes (an echo) say little about the speed.
final units = cut - piece.at;
if (took > 0 && units >= _minimumSlice) _speed = units * 1000 / took;
piece.at = cut;
}
if (piece.at >= piece.text.length) {
_pieces.removeFirst();
if (piece.action != null) {
_show();
piece.action!();
} else {
_drawn = piece.end;
@@ -107,14 +160,23 @@ class ChatShellTerminalFeed {
}
}
if (_pieces.isNotEmpty && clock.elapsed >= budget) {
_timer = Timer(Duration.zero, _pump);
if (_sinceShown.elapsed >= showGap) _show();
_cancel = chatShellYield(_pump);
return;
}
}
_show();
} finally {
_pumping = false;
}
}
void _show() {
if (!_unshown) return;
_unshown = false;
_sinceShown.reset();
show?.call();
}
}
class _Piece {
@@ -47,7 +47,7 @@ class ChatShellTerminalSession {
ChatShellInputHandler(optionAsMeta: this.optionAsMeta),
defaultInputHandler,
]);
_feed = ChatShellTerminalFeed(_write);
_feed = ChatShellTerminalFeed(_write, show: terminal.notifyListeners);
// Drawn at the process's own size until a view lays it out at its own.
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
terminal.onOutput = _output;
@@ -185,7 +185,7 @@ class ChatShellTerminalSession {
_replaying = replay;
_drawing = !replay;
try {
terminal.write(text);
terminal.write(text, notify: false);
} finally {
_replaying = false;
_drawing = false;
@@ -0,0 +1,11 @@
import 'chat_shell_terminal_yield_stub.dart'
if (dart.library.js_interop) 'chat_shell_terminal_yield_web.dart'
as impl;
/// Runs [callback] in a later turn of the event loop, after which the UI
/// may have drawn a frame; the returned function cancels it if it has not
/// run. On the web this is a message task: a chain of zero-length timers
/// is clamped to 4 ms each after a few, which left the emulator idle for
/// a third of a large burst. Elsewhere it is a zero-length timer.
void Function() chatShellYield(void Function() callback) =>
impl.chatShellYield(callback);
@@ -0,0 +1,4 @@
import 'dart:async';
void Function() chatShellYield(void Function() callback) =>
Timer(Duration.zero, callback).cancel;
@@ -0,0 +1,32 @@
import 'dart:async';
import 'dart:collection';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
/// One channel for every terminal: each message runs the oldest waiting
/// callback, in order.
final _waiting = Queue<_Turn>();
web.MessageChannel? _channel;
void Function() chatShellYield(void Function() callback) {
final channel = _channel ??= web.MessageChannel()
..port1.onmessage = _next.toJS;
final turn = _Turn(Zone.current.bindCallbackGuarded(callback));
_waiting.add(turn);
channel.port2.postMessage(null);
return () => turn.cancelled = true;
}
void _next(web.MessageEvent _) {
if (_waiting.isEmpty) return;
final turn = _waiting.removeFirst();
if (!turn.cancelled) turn.callback();
}
class _Turn {
_Turn(this.callback);
final void Function() callback;
bool cancelled = false;
}