Files
pipelines/app/lib/features/chat/shell/chat_shell_terminal_feed.dart
T
alan ae07fe14db 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>
2026-11-26 02:52:41 +00:00

193 lines
5.9 KiB
Dart

import 'dart:collection';
import 'chat_shell_terminal_yield.dart';
/// UTF-16 units one emulator write takes at most.
const int chatShellFeedSlice = 16 * 1024;
/// How long one turn of the event loop writes output before yielding, so a
/// 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 ([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();
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;
/// The end of the output drawn or waiting to be.
int get end => _end;
/// Whether nothing waits to be written.
bool get idle => _pieces.isEmpty;
/// Drops what waits: the emulator is redrawn and continues from [end].
void restart(int end) {
_pieces.clear();
_cancel?.call();
_cancel = null;
_drawn = end;
_end = end;
}
/// Queues [text] ending at byte [end]; as much as the budget allows is
/// written at once.
void add(String text, int end, {bool replay = false}) {
_pieces.add(_Piece(text, end, replay, null));
_end = end;
_schedule();
}
/// Runs [action] once everything queued before it is written.
void then(void Function() action) {
if (_pieces.isEmpty && !_pumping) {
action();
return;
}
_pieces.add(_Piece('', _end, false, action));
}
void dispose() {
_pieces.clear();
_cancel?.call();
_cancel = null;
}
void _schedule() {
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() {
_cancel = null;
_pumping = true;
final clock = Stopwatch()..start();
try {
while (_pieces.isNotEmpty) {
final piece = _pieces.first;
if (piece.at < piece.text.length) {
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))) {
// Never split a surrogate pair between two writes.
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;
onDrawn?.call(piece.end);
}
}
if (_pieces.isNotEmpty && clock.elapsed >= budget) {
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 {
_Piece(this.text, this.end, this.replay, this.action);
final String text;
final int end;
final bool replay;
final void Function()? action;
int at = 0;
}
bool _highSurrogate(int unit) => unit >= 0xD800 && unit <= 0xDBFF;