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
@@ -1,6 +1,8 @@
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 +10,75 @@ const int chatShellFeedSlice = 16 * 1024;
/// large replay or burst never holds a UI frame for long.
const Duration chatShellFeedBudget = Duration(milliseconds: 6);
/// While output streams, 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. Output after a
/// quiet spell (an echo, a prompt) is shown at once.
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, before an action queued with [then],
/// and while output still waits after a turn at most every [showGap]. A
/// burst draws its final state per frame instead of one frame per turn.
/// With [deferShows] (the web, where frames rasterise on the parsing
/// thread) written output is also shown at most every [showGap]: output
/// written less than a gap after the last show is shown when the gap has
/// passed, so a stream draws about 30 frames a second, not one per piece.
class ChatShellTerminalFeed {
ChatShellTerminalFeed(
this._write, {
this.show,
this.budget = chatShellFeedBudget,
this.slice = chatShellFeedSlice,
this.showGap = chatShellFeedShowGap,
this.deferShows = chatShellRasterSharesThread,
});
/// 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;
final bool deferShows;
/// Since [show] was last called (not running before the first call);
/// whether anything was written since; the show waiting for the gap.
final Stopwatch _sinceShown = Stopwatch();
bool _unshown = false;
Timer? _showLater;
/// 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 +91,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;
}
@@ -63,6 +108,7 @@ class ChatShellTerminalFeed {
/// Runs [action] once everything queued before it is written.
void then(void Function() action) {
if (_pieces.isEmpty && !_pumping) {
_show();
action();
return;
}
@@ -71,23 +117,37 @@ class ChatShellTerminalFeed {
void dispose() {
_pieces.clear();
_timer?.cancel();
_timer = null;
_cancel?.call();
_cancel = null;
_showLater?.cancel();
_showLater = 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 +155,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 +173,34 @@ class ChatShellTerminalFeed {
}
}
if (_pieces.isNotEmpty && clock.elapsed >= budget) {
_timer = Timer(Duration.zero, _pump);
if (_gapPassed) _show();
_cancel = chatShellYield(_pump);
return;
}
}
if (!deferShows || _gapPassed) {
_show();
} else if (_unshown) {
_showLater ??= Timer(showGap - _sinceShown.elapsed, _show);
}
} finally {
_pumping = false;
}
}
bool get _gapPassed =>
!_sinceShown.isRunning || _sinceShown.elapsed >= showGap;
void _show() {
_showLater?.cancel();
_showLater = null;
if (!_unshown) return;
_unshown = false;
_sinceShown
..reset()
..start();
show?.call();
}
}
class _Piece {
@@ -48,7 +48,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;
@@ -191,7 +191,7 @@ class ChatShellTerminalSession {
_replaying = replay;
_drawing = !replay;
try {
terminal.write(text);
terminal.write(text, notify: false);
} finally {
_replaying = false;
_drawing = false;
@@ -0,0 +1,15 @@
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);
/// Whether frames rasterise on the thread that parses output (the web),
/// so that drawing fewer of them while output streams lets it parse more.
const bool chatShellRasterSharesThread = impl.chatShellRasterSharesThread;
@@ -0,0 +1,8 @@
import 'dart:async';
void Function() chatShellYield(void Function() callback) =>
Timer(Duration.zero, callback).cancel;
/// Natively a frame rasterises on its own thread; the UI thread only
/// builds it, so frames take little from parsing.
const bool chatShellRasterSharesThread = false;
@@ -0,0 +1,36 @@
import 'dart:async';
import 'dart:collection';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
/// In the browser a frame rasterises on the page's one thread, between the
/// emulator's turns: every frame drawn is time not spent parsing.
const bool chatShellRasterSharesThread = true;
/// 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;
}