From f7ef4d1445e8803a5552a5cada599869c36a830b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 02:34:08 +0000 Subject: [PATCH 1/4] Terminal emulator: faster write path (ASCII runs, reused lines, no per-char allocation) - Parser reads the written strings directly (no rune list per write) and handles printable ASCII runs and C0 controls straight from the string; a run is written into the line in one call (Buffer.writeAscii, BufferLine.setAsciiCells), as writeChar would one by one. - A line leaving a full scrollback (or a one-line region scroll) is cleared and reused instead of allocating a 4 KiB line; lines with anchors (selection ends) still leave detached. Lines track the cells written since made or cleared, so a clear touches only those. - Grapheme join rejects characters that cannot join before reading the cell (it built a String per character); width table covers plane 1. - Switch dispatch for C0 controls, direct calls for CSI and SGR (torn-off handlers are slow in JavaScript); CSI params emptied without clear(); circular buffer index without %; insert keeps the start index wrapped. - Terminal.write(notify: false) lets a host notify once per frame. - tool/perf/terminal_parse_bench.dart: parse throughput in the VM or V8. Co-Authored-By: Claude Opus 5.5 --- .../third_party_xterm/write_path_test.dart | 226 ++++++++++++++++++ .../xterm/lib/src/core/buffer/buffer.dart | 67 +++++- .../lib/src/core/buffer/grapheme_join.dart | 8 + .../xterm/lib/src/core/buffer/line.dart | 84 ++++++- .../xterm/lib/src/core/charset.dart | 4 + .../xterm/lib/src/core/escape/handler.dart | 4 + .../xterm/lib/src/core/escape/parser.dart | 111 ++++++--- app/third_party/xterm/lib/src/terminal.dart | 15 +- .../xterm/lib/src/utils/byte_consumer.dart | 99 ++++---- .../xterm/lib/src/utils/circular_buffer.dart | 7 +- .../xterm/lib/src/utils/debugger.dart | 7 +- .../xterm/lib/src/utils/unicode_width.dart | 17 +- app/tool/perf/terminal_parse_bench.dart | 110 +++++++++ 13 files changed, 674 insertions(+), 85 deletions(-) create mode 100644 app/test/third_party_xterm/write_path_test.dart create mode 100644 app/tool/perf/terminal_parse_bench.dart diff --git a/app/test/third_party_xterm/write_path_test.dart b/app/test/third_party_xterm/write_path_test.dart new file mode 100644 index 00000000..ccb36366 --- /dev/null +++ b/app/test/third_party_xterm/write_path_test.dart @@ -0,0 +1,226 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +/// Every cell of every line, the cursor and the wrap flags: what two +/// terminals must agree on to have drawn the same output. +List state(Terminal terminal) { + final buffer = terminal.buffer; + final cells = [buffer.height, buffer.cursorX, buffer.cursorY]; + final cell = CellData.empty(); + for (var y = 0; y < buffer.height; y++) { + final line = buffer.lines[y]; + cells.add(line.isWrapped); + for (var x = 0; x < line.length; x++) { + line.getCellData(x, cell); + cells.addAll([ + cell.foreground, + cell.background, + cell.flags, + cell.content, + ]); + } + } + return cells; +} + +// Sized before the scrollback shrinks: the default 24 rows must fit first. +Terminal make({int width = 10, int height = 4, int maxLines = 50}) => + Terminal(maxLines: 100) + ..resize(width, height) + ..maxLines = maxLines; + +void main() { + group('printable ASCII runs', () { + // [setup] goes through the parser in both terminals; [text] is written + // as one run in the first and one character at a time through + // Buffer.writeChar (the path every character took before) in the other. + void same(String setup, String text, {int width = 10}) { + final fast = make(width: width)..write(setup); + final slow = make(width: width)..write(setup); + fast.write(text); + for (final unit in text.codeUnits) { + slow.buffer.writeChar(unit); + } + expect(state(fast), state(slow), reason: '$setup | $text'); + } + + test('wrap across rows and into the scrollback', () { + same('', 'abcdefghij' * 7 + 'xyz'); + same('abc', 'defghijklmnopqrstuvwxyz0123456789'); + same('\x1b[3;1H', 'a' * 95); + }); + + test('a full row waits at the last column, as one character does', () { + same('', 'abcdefghij'); + same('abcdefghi', 'j'); + same('abcdefghij', 'k'); + }); + + test('without autowrap', () { + same('\x1b[?7l', 'abcdefghijklmnop'); + same('\x1b[?7lab', 'cdefghijklmnop'); + }); + + test('in the cursor style (colours, bold, links)', () { + same('\x1b[1;31;44m', 'styled text that wraps'); + same('\x1b]8;;https://example.com\x1b\\', 'linked text'); + }); + + test('over a wide character', () { + // Writing over the second column of a wide character blanks its + // first; over the first column, as before. + same('中文\r\x1b[C', 'ab'); + same('中文\r', 'abc'); + }); + + test('in the DEC line drawing set', () { + same('\x1b(0', 'lqqk xx mqqj'); + }); + + test('in insert mode the run shifts nothing (as one character)', () { + same('hello\r\x1b[4h', 'ab'); + }); + }); + + test('a run and the characters around it parse as before', () { + final terminal = make(width: 20); + terminal.write('ab\x1b[31mcd\x1b[0méf\u{1F600}g\r\nnext'); + final buffer = terminal.buffer; + expect(buffer.lines[0].getText(), 'abcdéf\u{1F600}g'); + expect(buffer.lines[0].getForeground(2), CellColor.named | 1); + expect(buffer.lines[0].getForeground(4), 0); + expect(buffer.lines[1].getText().trimRight(), 'next'); + }); + + test('a sequence split between writes resumes (rollback)', () { + final terminal = make(width: 20); + terminal.write('ab\x1b[3'); + terminal.write('1mcd\x1b'); + terminal.write('[0me'); + final line = terminal.buffer.lines[0]; + expect(line.getText().trimRight(), 'abcde'); + expect(line.getForeground(1), 0); + expect(line.getForeground(2), CellColor.named | 1); + expect(line.getForeground(4), 0); + }); + + test('a surrogate pair is one character; split halves are not', () { + final terminal = make(width: 20); + terminal.write('a\u{1F600}b'); + final line = terminal.buffer.lines[0]; + expect(line.getCodePoint(1), 0x1F600); + expect(line.getWidth(1), 2); + expect(line.getCodePoint(3), 'b'.codeUnitAt(0)); + expect(terminal.buffer.cursorX, 4); + }); + + test('REP repeats the last character of a run', () { + final terminal = make(width: 20); + terminal.write('xyz\x1b[3b'); + expect(terminal.buffer.lines[0].getText().trimRight(), 'xyzzzz'); + }); + + group('lines leaving the scrollback are reused', () { + test('as empty lines: output keeps its text, wraps and widths', () { + final terminal = make(width: 10, height: 3, maxLines: 6); + final reference = make(width: 10, height: 3, maxLines: 1000); + final output = [ + for (var i = 0; i < 40; i++) + i.isEven + ? '\x1b[4${i % 8}mline $i that wraps\x1b[0m\r\n' + : '中$i\r\n', + ].join(); + terminal.write(output); + reference.write(output); + final buffer = terminal.buffer; + expect(buffer.height, 6); + final tail = reference.buffer.height - 6; + for (var y = 0; y < 6; y++) { + final line = buffer.lines[y]; + final expected = reference.buffer.lines[tail + y]; + expect(line.getText(), expected.getText(), reason: 'row $y'); + expect(line.isWrapped, expected.isWrapped, reason: 'row $y'); + expect(line.getTrimmedLength(), expected.getTrimmedLength()); + for (var x = 0; x < 10; x++) { + expect(line.getBackground(x), expected.getBackground(x)); + expect(line.getWidth(x), expected.getWidth(x)); + } + } + }); + + test('a reused line has a new version, so its picture is redrawn', () { + final terminal = make(width: 10, height: 2, maxLines: 2); + terminal.write('a\r\nb'); + final top = terminal.buffer.lines[0]; + final version = top.version; + terminal.write('\r\nc'); + expect(identical(terminal.buffer.lines[1], top), isTrue); + expect(top.version, isNot(version)); + expect(top.getText().trimRight(), 'c'); + }); + + test('a line with an anchor (a selection end) leaves detached', () { + final terminal = make(width: 10, height: 2, maxLines: 2); + terminal.write('a\r\nb'); + final top = terminal.buffer.lines[0]; + final anchor = terminal.buffer.createAnchor(0, 0); + terminal.write('\r\nc'); + expect(anchor.attached, isFalse); + expect(top.attached, isFalse); + expect(top.getText().trimRight(), 'a'); + expect(terminal.buffer.lines[1].getText().trimRight(), 'c'); + }); + + test('a top scroll region feeding a full scrollback wraps around', () { + // Line feeds at the bottom of a region that starts at the top insert + // into the scrollback rather than push; well past its capacity. + String screen(Terminal terminal) => [ + for (var y = 0; y < 4; y++) + terminal.buffer.lines[terminal.buffer.scrollBack + y] + .getText() + .trimRight(), + ].join('|'); + final small = make(width: 10, height: 4, maxLines: 8); + final large = make(width: 10, height: 4, maxLines: 1000); + for (final terminal in [small, large]) { + terminal.write('\x1b[1;3r\x1b[4;1Hstatus\x1b[1;1H'); + for (var i = 0; i < 50; i++) { + terminal.write('\x1b[3;1Hrow $i\n'); + } + } + expect(small.buffer.height, 8); + expect(screen(small), screen(large)); + for (var y = 0; y < 8; y++) { + expect(small.buffer.lines[y].index, y); + } + }); + + test('in a scroll region on the alternate screen', () { + final terminal = make(width: 10, height: 4); + terminal.write('\x1b[?1049h\x1b[2;3r\x1b[1;1Htop\x1b[4;1Hbottom'); + terminal.write('\x1b[2;1H\x1b[41mone\r\n\x1b[0mtwo\r\nthree\r\nfour'); + final buffer = terminal.buffer; + String row(int y) => buffer.lines[y].getText().trimRight(); + expect([row(0), row(1), row(2), row(3)], [ + 'top', + 'three', + 'four', + 'bottom', + ]); + // The reused lines carry nothing of what scrolled out. + expect(buffer.lines[2].getBackground(0), 0); + expect(buffer.lines[2].getBackground(9), 0); + }); + }); + + test('a write without notify leaves notifying to the host', () { + final terminal = make(); + var heard = 0; + terminal.addListener(() => heard++); + terminal.write('quiet', notify: false); + expect(heard, 0); + terminal.write('loud'); + expect(heard, 1); + expect(terminal.buffer.lines[0].getText().trimRight(), 'quietloud'); + }); +} diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart index 75cbe370..4bb6d794 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -179,6 +179,42 @@ class Buffer { } } + /// Writes the printable ASCII characters of [text] from [start] to [end] + /// (exclusive), exactly as [writeChar] would one at a time, a row's worth + /// at once. Such a character never joins a grapheme cluster and is one + /// column wide. + void writeAscii(String text, int start, int end) { + if (!charset.isAscii) { + for (var i = start; i < end; i++) { + writeChar(text.codeUnitAt(i)); + } + return; + } + final style = terminal.cursor; + final width = viewWidth; + var i = start; + while (i < end) { + if (_cursorX >= width) { + index(); + setCursorX(0); + if (terminal.autoWrapMode) { + currentLine.isWrapped = true; + } + } + final line = currentLine; + final x = _cursorX; + // Overwriting the second column of a wide character blanks its first. + if (x > 0 && line.getWidth(x - 1) == 2) { + line.eraseCell(x - 1, style); + } + var count = end - i; + if (count > width - x) count = width - x; + line.setAsciiCells(x, text, i, count, style); + _cursorX = x + count; + i += count; + } + } + /// The line at the current cursor position. BufferLine get currentLine { return lines[absoluteCursorY]; @@ -265,11 +301,14 @@ class Buffer { } void scrollUp(int lines) { + // The line a one-line scroll (a line feed at the bottom of a region) + // drops is cleared and reused as the new bottom line. + final out = lines == 1 ? _reusable(this.lines[absoluteMarginTop]) : null; for (var i = absoluteMarginTop; i <= absoluteMarginBottom; i++) { if (i <= absoluteMarginBottom - lines) { this.lines[i] = this.lines[i + lines]; } else { - this.lines[i] = _newEmptyLine(); + this.lines[i] = out ?? _newEmptyLine(); } } } @@ -285,7 +324,12 @@ class Buffer { if (isInVerticalMargin) { if (_cursorY == _marginBottom) { if (marginTop == 0 && !isAltBuffer) { - lines.insert(absoluteMarginBottom + 1, _newEmptyLine()); + final at = absoluteMarginBottom + 1; + if (at == lines.length) { + _pushLine(); + } else { + lines.insert(at, _newEmptyLine()); + } } else { scrollUp(1); } @@ -301,7 +345,7 @@ class Buffer { if (isAltBuffer) { scrollUp(1); } else { - lines.push(_newEmptyLine()); + _pushLine(); } } else { // there're still lines so we simply move cursor down. @@ -561,6 +605,23 @@ class Buffer { return line; } + /// Adds an empty line below the others. When the scrollback is full the + /// oldest line, which this drops, is cleared and reused: streaming output + /// then allocates no lines. + void _pushLine() { + final oldest = lines.isFull ? _reusable(lines[0]) : null; + lines.push(oldest ?? _newEmptyLine()); + } + + /// [line], about to leave the buffer, cleared for reuse as an empty line, + /// or null when something still points into it (an anchor: a selection + /// or highlight end), which must see it detached. + BufferLine? _reusable(BufferLine line) { + if (line.anchors.isNotEmpty) return null; + line.clear(viewWidth); + return line; + } + static final defaultWordSeparators = { 0, r' '.codeUnitAt(0), diff --git a/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart index a3dcc303..ead2e909 100644 --- a/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart +++ b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart @@ -35,6 +35,14 @@ int? joinPreviousCell( int width, ) { if (cursorX <= 0) return width == 0 ? 0 : null; + // Most characters can only start a cell; tell them apart before reading + // the cell before the cursor. + if (width != 0 && + !UnicodeWidth.isRegionalIndicator(codePoint) && + !UnicodeWidth.isEmojiModifier(codePoint) && + !UnicodeWidth.isPictographic(codePoint)) { + return null; + } var x = (cursorX > viewWidth ? viewWidth : cursorX) - 1; // The second column of a wide character: its cluster is one to the left. if (x > 0 && line.getContent(x) == 0 && line.getWidth(x - 1) == 2) x--; diff --git a/app/third_party/xterm/lib/src/core/buffer/line.dart b/app/third_party/xterm/lib/src/core/buffer/line.dart index 20bdf679..0fe133bf 100644 --- a/app/third_party/xterm/lib/src/core/buffer/line.dart +++ b/app/third_party/xterm/lib/src/core/buffer/line.dart @@ -89,6 +89,7 @@ class BufferLine with IndexedItem { CellData createCellData(int index) { final cellData = CellData.empty(); + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = cellData.foreground; _data[offset + _cellBackground] = cellData.background; @@ -99,21 +100,25 @@ class BufferLine with IndexedItem { void setForeground(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellForeground] = value; } void setBackground(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellBackground] = value; } void setAttributes(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellAttributes] = value; } void setContent(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellContent] = value; } @@ -124,6 +129,7 @@ class BufferLine with IndexedItem { void setCell(int index, int char, int witdh, CursorStyle style) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -131,8 +137,79 @@ class BufferLine with IndexedItem { _data[offset + _cellContent] = char | (witdh << CellContent.widthShift); } + /// Sets [count] cells from [index] to the one-column characters of [text] + /// from [start] (printable ASCII, so no width lookup) in [style]. + void setAsciiCells( + int index, + String text, + int start, + int count, + CursorStyle style, + ) { + _version++; + _touch(index + count - 1); + final data = _data; + final foreground = style.foreground; + final background = style.background; + final attrs = style.attrs; + const oneColumn = 1 << CellContent.widthShift; + var offset = index * _cellSize; + final end = start + count; + for (var i = start; i < end; i++) { + data[offset + _cellForeground] = foreground; + data[offset + _cellBackground] = background; + data[offset + _cellAttributes] = attrs; + data[offset + _cellContent] = text.codeUnitAt(i) | oneColumn; + offset += _cellSize; + } + } + + /// Makes this an empty, unwrapped line of [length] cells, as a new line, + /// so a line leaving the buffer can be reused instead of allocating one. + /// The version keeps counting, so nothing drawn from the old cells is + /// mistaken for the new ones. + void clear(int length) { + _version++; + isWrapped = false; + final size = _calcCapacity(length) * _cellSize; + if (size > _data.length) { + _data = Uint32List(size); + } else { + // Only the cells written since the line was made or cleared need + // clearing: a line of output usually fills a few of its columns. A + // long run is copied from zeros (a memory move, where fillRange is a + // loop); up to 64 cells are quicker set in place (compiled to + // JavaScript, setRange makes a view of each array). + final used = _dirty * _cellSize; + if (used <= 256) { + final data = _data; + for (var i = 0; i < used; i++) { + data[i] = 0; + } + } else { + if (_zeros.length < used) _zeros = Uint32List(_data.length); + _data.setRange(0, used, _zeros); + } + } + _dirty = 0; + _length = length; + } + + /// Cells from this index on have never been written since the line was + /// made or cleared: they are all zero. + int _dirty = 0; + + @pragma('vm:prefer-inline') + @pragma('dart2js:prefer-inline') + void _touch(int index) { + if (index >= _dirty) _dirty = index + 1; + } + + static var _zeros = Uint32List(0); + void setCellData(int index, CellData cellData) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = cellData.foreground; _data[offset + _cellBackground] = cellData.background; @@ -142,6 +219,7 @@ class BufferLine with IndexedItem { void eraseCell(int index, CursorStyle style) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -151,6 +229,7 @@ class BufferLine with IndexedItem { void resetCell(int index) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = 0; _data[offset + _cellBackground] = 0; @@ -185,6 +264,7 @@ class BufferLine with IndexedItem { assert(count >= 0 && start + count <= _length); style ??= CursorStyle.empty; + _touch(_length - 1); if (start + count < _length) { final moveStart = start * _cellSize; @@ -220,6 +300,7 @@ class BufferLine with IndexedItem { void insertCells(int start, int count, [CursorStyle? style]) { _version++; style ??= CursorStyle.empty; + _touch(_length - 1); if (start > 0 && getWidth(start - 1) == 2) { eraseCell(start - 1, style); @@ -288,7 +369,7 @@ class BufferLine with IndexedItem { /// Returns the offset of the last cell that has content from the start of /// the line. int getTrimmedLength([int? cols]) { - final maxCols = _data.length ~/ _cellSize; + final maxCols = _dirty; if (cols == null || cols > maxCols) { cols = maxCols; @@ -326,6 +407,7 @@ class BufferLine with IndexedItem { // Uint32List.sublistView(src.data, srcCol * _cellSize, len * _cellSize), // ); + _touch(dstCol + len - 1); var srcOffset = srcCol * _cellSize; var dstOffset = dstCol * _cellSize; diff --git a/app/third_party/xterm/lib/src/core/charset.dart b/app/third_party/xterm/lib/src/core/charset.dart index d062368c..c391ced6 100644 --- a/app/third_party/xterm/lib/src/core/charset.dart +++ b/app/third_party/xterm/lib/src/core/charset.dart @@ -18,6 +18,10 @@ class Charset { _cached = _charsetMap[_currentIndex] ?? asciiTranslator; } + /// Whether characters are written as they are (no designated set such + /// as DEC line drawing is in use). + bool get isAscii => identical(_cached, asciiTranslator); + int translate(int codePoint) { return _cached(codePoint); } diff --git a/app/third_party/xterm/lib/src/core/escape/handler.dart b/app/third_party/xterm/lib/src/core/escape/handler.dart index 68781a22..51e1ddb3 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -3,6 +3,10 @@ import 'package:xterm/src/core/mouse/mode.dart'; abstract class EscapeHandler { void writeChar(int char); + /// Writes the printable ASCII characters (U+0020-007E) of [data] from + /// [start] to [end] (exclusive), as [writeChar] would one by one. + void writeAscii(String data, int start, int end); + /* SBC */ void bell(); diff --git a/app/third_party/xterm/lib/src/core/escape/parser.dart b/app/third_party/xterm/lib/src/core/escape/parser.dart index 0f795be7..10896214 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -39,6 +39,8 @@ class EscapeParser { continue; } + if (_processPlain()) continue; + tokenBegin = _queue.totalConsumed; final char = _queue.consume(); @@ -54,19 +56,69 @@ class EscapeParser { } } + /// Handles the plain text at the head of the input, most of any output, + /// straight from the written string: runs of printable ASCII are written + /// at once and C0 controls other than ESC (line feeds, carriage returns) + /// handled as they come. Stops at the end of the string or at anything + /// else (an escape sequence, a character outside ASCII), which the caller + /// parses one at a time. Returns whether anything was handled. + bool _processPlain() { + final block = _queue.block; + final length = block.length; + final first = _queue.offset; + var at = first; + while (at < length) { + final unit = block.codeUnitAt(at); + if (unit >= Ascii.space && unit <= Ascii.tilde) { + var end = at + 1; + while (end < length) { + final next = block.codeUnitAt(end); + if (next < Ascii.space || next > Ascii.tilde) break; + end++; + } + tokenBegin = _queue.totalConsumed; + _queue.skip(end - at); + handler.writeAscii(block, at, end); + at = end; + } else if (unit < Ascii.space && unit != Ascii.ESC) { + tokenBegin = _queue.totalConsumed; + _queue.skip(1); + _processChar(unit); + at++; + // A handler's callback (the bell) wrote more: read it afresh. + if (_queue.offset != at) return true; + } else { + break; + } + } + return at > first; + } + + /// A single character: a C0 control's action, or a character to print. + /// (A switch rather than a table of torn-off handlers: compiled to + /// JavaScript, a call through a tear-off costs several times a direct + /// call, and line feeds and carriage returns come with every line.) void _processChar(int char) { - if (char > _sbcHandlers.maxIndex) { - handler.writeChar(char); - return; + switch (char) { + case 0x07: + handler.bell(); + case 0x08: + handler.backspaceReturn(); + case 0x09: + handler.tab(); + case 0x0a || 0x0b || 0x0c: + handler.lineFeed(); + case 0x0d: + handler.carriageReturn(); + case 0x0e: + handler.shiftOut(); + case 0x0f: + handler.shiftIn(); + case < 0x07: + handler.unkownEscape(char); + default: + handler.writeChar(char); } - - final sbcHandler = _sbcHandlers[char]; - if (sbcHandler == null) { - handler.unkownEscape(char); - return; - } - - sbcHandler(); } /// Processes a sequence of characters that starts with an escape character. @@ -83,6 +135,9 @@ class EscapeParser { return true; } + // CSI, nearly every sequence, without the table's torn-off call. + if (escapeChar == Ascii.openBracket) return _escHandleCSI(); + final escapeHandler = _escHandlers[escapeChar]; if (escapeHandler == null) { @@ -93,18 +148,6 @@ class EscapeParser { return escapeHandler(); } - late final _sbcHandlers = FastLookupTable<_SbcHandler>({ - 0x07: handler.bell, - 0x08: handler.backspaceReturn, - 0x09: handler.tab, - 0x0a: handler.lineFeed, - 0x0b: handler.lineFeed, - 0x0c: handler.lineFeed, - 0x0d: handler.carriageReturn, - 0x0e: handler.shiftOut, - 0x0f: handler.shiftIn, - }); - late final _escHandlers = FastLookupTable<_EscHandler>({ '['.charCode: _escHandleCSI, ']'.charCode: _escHandleOSC, @@ -301,6 +344,12 @@ class EscapeParser { return true; } + // Colours and attributes, the commonest sequence, called directly. + if (finalByte == Ascii.m && _csi.prefix == null) { + _csiHandleSgr(); + return true; + } + final csiHandler = _csiHandlers[finalByte]; if (csiHandler == null) { @@ -1094,12 +1143,21 @@ class _Csi { void reset() { prefix = null; intermediates = 0; - params.clear(); - rawParams.clear(); - rawIsSub.clear(); + _empty(params); + _empty(rawParams); + _empty(rawIsSub); finalByte = 0; } + /// Empties [list] one element at a time: a sequence has a few parameters, + /// and compiled to JavaScript `clear()` (setting an array's length) costs + /// more than every other step of parsing a colour change. + static void _empty(List list) { + while (list.isNotEmpty) { + list.removeLast(); + } + } + void add(int value, bool isSub) { if (rawParams.length >= maxParams) return; rawParams.add(value); @@ -1117,6 +1175,5 @@ class _Csi { /// Returns [true] if the sequence was processed, [false] if it was not. typedef _EscHandler = bool Function(); -typedef _SbcHandler = void Function(); typedef _CsiHandler = void Function(); diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index a031daaf..6e6f1706 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -284,9 +284,14 @@ class Terminal with Observable implements TerminalState, EscapeHandler { /// Writes the data from the underlying program to the terminal. Calling this /// updates the states of the terminal and emits events such as [onBell] or /// [onTitleChange] when the escape sequences in [data] request it. - void write(String data) { + /// + /// Listeners (the view) hear of the change unless [notify] is false: a + /// host writing a large burst in several writes calls [notifyListeners] + /// itself once the view should show it, so the view draws the final state + /// instead of every step. + void write(String data, {bool notify = true}) { _parser.write(data); - notifyListeners(); + if (notify) notifyListeners(); } /// Sends a key event to the underlying program. @@ -470,6 +475,12 @@ class Terminal with Observable implements TerminalState, EscapeHandler { _buffer.writeChar(char); } + @override + void writeAscii(String data, int start, int end) { + _precedingCodepoint = data.codeUnitAt(end - 1); + _buffer.writeAscii(data, start, end); + } + /* SBC */ @override diff --git a/app/third_party/xterm/lib/src/utils/byte_consumer.dart b/app/third_party/xterm/lib/src/utils/byte_consumer.dart index 4a2ad382..622caac1 100644 --- a/app/third_party/xterm/lib/src/utils/byte_consumer.dart +++ b/app/third_party/xterm/lib/src/utils/byte_consumer.dart @@ -1,9 +1,16 @@ import 'dart:collection'; +/// The parser's input: the written strings, read one character at a time. +/// +/// Positions ([length], [totalConsumed], [rollback]) count UTF-16 code +/// units, so a character outside the BMP counts two. A surrogate pair is +/// read as one code point when both halves are in the same write; a lone +/// surrogate is read as itself, as `String.runes` does. Strings are kept as +/// written rather than decoded into lists, so a write allocates nothing. class ByteConsumer { - final _queue = ListQueue>(); + final _queue = ListQueue(); - final _consumed = ListQueue>(); + final _consumed = ListQueue(); var _currentOffset = 0; @@ -13,37 +20,63 @@ class ByteConsumer { void add(String data) { if (data.isEmpty) return; - final runes = data.runes.toList(growable: false); - _queue.addLast(runes); - _length += runes.length; + _queue.addLast(data); + _length += data.length; + } + + /// The string being read, with at least one unit left at [offset]. + /// Only valid while [isNotEmpty]. + String get block { + var data = _queue.first; + while (_currentOffset >= data.length) { + _consumed.add(_queue.removeFirst()); + _currentOffset -= data.length; + data = _queue.first; + } + return data; + } + + /// Where [block] is read next. + int get offset => _currentOffset; + + /// Consumes [units] code units of [block] at once (the caller has read + /// them there). + void skip(int units) { + _currentOffset += units; + _length -= units; + _totalConsumed += units; } int peek() { - final data = _queue.first; - if (_currentOffset < data.length) { - return data[_currentOffset]; - } else { - final result = consume(); - rollback(); - return result; + final data = block; + final unit = data.codeUnitAt(_currentOffset); + if (unit & 0xFC00 == 0xD800 && _currentOffset + 1 < data.length) { + final next = data.codeUnitAt(_currentOffset + 1); + if (next & 0xFC00 == 0xDC00) { + return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF); + } } + return unit; } int consume() { - final data = _queue.first; - - if (_currentOffset >= data.length) { - _consumed.add(_queue.removeFirst()); - _currentOffset -= data.length; - return consume(); + final data = block; + final unit = data.codeUnitAt(_currentOffset++); + if (unit & 0xFC00 == 0xD800 && _currentOffset < data.length) { + final next = data.codeUnitAt(_currentOffset); + if (next & 0xFC00 == 0xDC00) { + _currentOffset++; + _length -= 2; + _totalConsumed += 2; + return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF); + } } - _length--; _totalConsumed++; - return data[_currentOffset++]; + return unit; } - /// Rolls back the last [n] call. + /// Rolls back [n] code units. void rollback([int n = 1]) { _currentOffset -= n; _totalConsumed -= n; @@ -55,7 +88,7 @@ class ByteConsumer { } } - /// Rolls back to the state when this consumer had [length] bytes. + /// Rolls back to the state when this consumer had [length] units. void rollbackTo(int length) { rollback(length - _length); } @@ -83,25 +116,3 @@ class ByteConsumer { _length = 0; } } - -// void main() { -// final consumer = ByteConsumer(); -// consumer.add(Uint8List.fromList([1, 2, 3])); -// consumer.add(Uint8List.fromList([4, 5, 6])); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } - -// consumer.rollback(5); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } - -// consumer.rollbackTo(3); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } -// } diff --git a/app/third_party/xterm/lib/src/utils/circular_buffer.dart b/app/third_party/xterm/lib/src/utils/circular_buffer.dart index 3b3ee3a1..34ef86ac 100644 --- a/app/third_party/xterm/lib/src/utils/circular_buffer.dart +++ b/app/third_party/xterm/lib/src/utils/circular_buffer.dart @@ -23,7 +23,11 @@ class IndexAwareCircularBuffer { /// the regular index. @pragma('vm:prefer-inline') int _getCyclicIndex(int index) { - return (_startIndex + index) % _array.length; + // Indexes run from 0 to the capacity (one past the end when pushing), + // so one subtraction wraps them; `%` is a helper call in JavaScript. + final cyclic = _startIndex + index; + final capacity = _array.length; + return cyclic >= capacity ? cyclic - capacity : cyclic; } /// Removes the element at [index] from the list. @@ -196,6 +200,7 @@ class IndexAwareCircularBuffer { if (_length >= _array.length) { _startIndex += 1; + if (_startIndex == _array.length) _startIndex = 0; _absoluteStartIndex += 1; } else { _length++; diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 8ab4daf3..f5a647b2 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -36,7 +36,7 @@ class TerminalDebugger with Observable { final commands = []; void write(String chunk) { - recorded.addAll(chunk.runes); + recorded.addAll(chunk.codeUnits); _parser.write(chunk); notifyListeners(); } @@ -89,6 +89,11 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('writeChar(${String.fromCharCode(char)})'); } + @override + void writeAscii(String data, int start, int end) { + onCommand('writeAscii(${data.substring(start, end)})'); + } + /* SBC */ @override diff --git a/app/third_party/xterm/lib/src/utils/unicode_width.dart b/app/third_party/xterm/lib/src/utils/unicode_width.dart index c0101334..068daca5 100644 --- a/app/third_party/xterm/lib/src/utils/unicode_width.dart +++ b/app/third_party/xterm/lib/src/utils/unicode_width.dart @@ -16,7 +16,12 @@ abstract final class UnicodeWidth { static const _textDefault = 8; static const _modifierBase = 16; - static final Uint8List _bmp = _buildBmp(); + /// The properties of every code point below [_tableEnd]: the BMP and the + /// supplementary plane that holds the emoji. Beyond it, the ranges are + /// searched. + static final Uint8List _table = _buildTable(); + + static const _tableEnd = 0x20000; /// Columns [codePoint] takes alone: 0, 1 or 2. Controls are 0. static int width(int codePoint) { @@ -55,7 +60,7 @@ abstract final class UnicodeWidth { codePoint >= 0x1F1E6 && codePoint <= 0x1F1FF; static int _props(int codePoint) { - if (codePoint < 0x10000) return _bmp[codePoint]; + if (codePoint < _tableEnd) return _table[codePoint]; var props = 0; if (_within(zeroWidthRanges, codePoint)) props |= _zero; if (_within(wideRanges, codePoint)) props |= _wide; @@ -65,12 +70,12 @@ abstract final class UnicodeWidth { return props; } - static Uint8List _buildBmp() { - final table = Uint8List(0x10000); + static Uint8List _buildTable() { + final table = Uint8List(_tableEnd); void mark(List ranges, int bit) { for (var i = 0; i < ranges.length; i += 2) { - if (ranges[i] >= 0x10000) break; - final last = ranges[i + 1] < 0x10000 ? ranges[i + 1] : 0xFFFF; + if (ranges[i] >= _tableEnd) break; + final last = ranges[i + 1] < _tableEnd ? ranges[i + 1] : _tableEnd - 1; for (var cp = ranges[i]; cp <= last; cp++) { table[cp] |= bit; } diff --git a/app/tool/perf/terminal_parse_bench.dart b/app/tool/perf/terminal_parse_bench.dart new file mode 100644 index 00000000..2d44caae --- /dev/null +++ b/app/tool/perf/terminal_parse_bench.dart @@ -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 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(); +} From ae07fe14dbfe033d2f3bea942ee59209362d0536 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 02:52:41 +0000 Subject: [PATCH 2/4] 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 --- .../chat/shell/chat_shell_terminal_feed.dart | 88 ++++++++++++++++--- .../shell/chat_shell_terminal_session.dart | 4 +- .../chat/shell/chat_shell_terminal_yield.dart | 11 +++ .../shell/chat_shell_terminal_yield_stub.dart | 4 + .../shell/chat_shell_terminal_yield_web.dart | 32 +++++++ .../shell/chat_shell_terminal_feed_test.dart | 78 ++++++++++++++++ app/tool/perf/terminal_stream_bench.dart | 47 ++++++++-- app/tool/perf/terminal_stream_profile.mjs | 85 ++++++++++++++++++ 8 files changed, 328 insertions(+), 21 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_yield.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart create mode 100644 app/tool/perf/terminal_stream_profile.mjs diff --git a/app/lib/features/chat/shell/chat_shell_terminal_feed.dart b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart index 6c73a60a..3828dce4 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_feed.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart @@ -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 { diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index 06553eaf..f0b92c1e 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -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; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield.dart new file mode 100644 index 00000000..79ffcb26 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield.dart @@ -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); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart new file mode 100644 index 00000000..b034d8c0 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart @@ -0,0 +1,4 @@ +import 'dart:async'; + +void Function() chatShellYield(void Function() callback) => + Timer(Duration.zero, callback).cancel; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart new file mode 100644 index 00000000..acc17871 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart @@ -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; +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart index bc8e4730..06bdc2d3 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart @@ -55,6 +55,84 @@ void main() { }, ); + test('the view is shown once what waits is written, and while a burst ' + 'is behind at most every show gap', () async { + var shown = 0; + final writes = []; + final feed = ChatShellTerminalFeed( + (text, _) => writes.add(text), + show: () => shown++, + budget: Duration.zero, + slice: 10, + showGap: const Duration(hours: 1), + ); + feed.add('abc', 3); + // Written whole at once: shown at once. + expect(writes, ['abc']); + expect(shown, 1); + feed.add('x' * 35, 38); + await turn(); + await turn(); + // Behind, within the gap: not shown again. + expect(writes.length, 4); + expect(shown, 1); + await turn(); + await turn(); + // Caught up: the final state is shown. + expect(writes.skip(1).join(), 'x' * 35); + expect(feed.idle, isTrue); + expect(shown, 2); + // An action waiting behind output sees it shown first. + feed.add('y' * 25, 63); + var shownForAction = -1; + feed.then(() => shownForAction = shown); + for (var i = 0; i < 5; i++) { + await turn(); + } + expect(shownForAction, 3); + expect(shown, 3); + }); + + test('every turn shows its state with no show gap', () async { + var shown = 0; + final feed = ChatShellTerminalFeed( + (_, _) {}, + show: () => shown++, + budget: Duration.zero, + slice: 10, + showGap: Duration.zero, + ); + feed.add('x' * 30, 30); + for (var i = 0; i < 5; i++) { + await turn(); + } + expect(feed.idle, isTrue); + expect(shown, 3); + }); + + test('slices follow the measured speed within the slice', () async { + final sizes = []; + final feed = ChatShellTerminalFeed( + (text, _) { + sizes.add(text.length); + // About 1 ms per 1000 units. + final until = Stopwatch()..start(); + while (until.elapsedMicroseconds < text.length) {} + }, + budget: const Duration(milliseconds: 6), + slice: 16 * 1024, + ); + feed.add('y' * 100000, 100000); + while (!feed.idle) { + await turn(); + } + expect(sizes.reduce((a, b) => a + b), 100000); + expect(sizes.every((s) => s <= 16 * 1024), isTrue); + // After the first slice measured the speed, no write takes much more + // than a turn's budget (6 ms, about 6000 units here). + expect(sizes.skip(1).every((s) => s <= 8000), isTrue, reason: '$sizes'); + }); + test('a surrogate pair is never split between two writes', () { final writes = []; final feed = ChatShellTerminalFeed((text, _) => writes.add(text), slice: 3); diff --git a/app/tool/perf/terminal_stream_bench.dart b/app/tool/perf/terminal_stream_bench.dart index 3470c65b..59947c66 100644 --- a/app/tool/perf/terminal_stream_bench.dart +++ b/app/tool/perf/terminal_stream_bench.dart @@ -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 _timings = []; final List _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); + } }); } @@ -164,6 +196,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 diff --git a/app/tool/perf/terminal_stream_profile.mjs b/app/tool/perf/terminal_stream_profile.mjs new file mode 100644 index 00000000..06df1f93 --- /dev/null +++ b/app/tool/perf/terminal_stream_profile.mjs @@ -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?.(); +} From a3149eef03a0afccb4b133da2ce962d09a20867f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 03:14:17 +0000 Subject: [PATCH 3/4] Terminal feed: on the web, show streaming output at most every 32 ms In the browser a frame rasterises on the thread that parses output, so a stream drawn at 60 frames a second spends half its time drawing. With deferShows (the web default) output written less than a gap after the last show is shown when the gap has passed; output after a quiet spell (an echo) still shows at once. Natively frames rasterise on their own thread and written output keeps showing at once. The stream bench measures the stream without its final 600 ms wait for frame timings. Co-Authored-By: Claude Opus 5.5 --- .../chat/shell/chat_shell_terminal_feed.dart | 46 +++++++++++++----- .../chat/shell/chat_shell_terminal_yield.dart | 4 ++ .../shell/chat_shell_terminal_yield_stub.dart | 4 ++ .../shell/chat_shell_terminal_yield_web.dart | 4 ++ .../shell/chat_shell_terminal_feed_test.dart | 47 ++++++++++++++++--- app/tool/perf/terminal_stream_bench.dart | 3 +- 6 files changed, 89 insertions(+), 19 deletions(-) diff --git a/app/lib/features/chat/shell/chat_shell_terminal_feed.dart b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart index 3828dce4..11689f22 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_feed.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:collection'; import 'chat_shell_terminal_yield.dart'; @@ -9,9 +10,10 @@ 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. +/// 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 @@ -31,9 +33,13 @@ const int _firstSlice = 4096; /// 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. +/// 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, { @@ -41,6 +47,7 @@ class ChatShellTerminalFeed { this.budget = chatShellFeedBudget, this.slice = chatShellFeedSlice, this.showGap = chatShellFeedShowGap, + this.deferShows = chatShellRasterSharesThread, }); /// Writes [text] into the emulator; [replay] marks a redraw of old output. @@ -51,10 +58,13 @@ class ChatShellTerminalFeed { final Duration budget; final int slice; final Duration showGap; + final bool deferShows; - /// Since [show] was last called; whether anything was written since. - final Stopwatch _sinceShown = Stopwatch()..start(); + /// 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; @@ -98,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; } @@ -108,6 +119,8 @@ class ChatShellTerminalFeed { _pieces.clear(); _cancel?.call(); _cancel = null; + _showLater?.cancel(); + _showLater = null; } void _schedule() { @@ -160,21 +173,32 @@ class ChatShellTerminalFeed { } } if (_pieces.isNotEmpty && clock.elapsed >= budget) { - if (_sinceShown.elapsed >= showGap) _show(); + if (_gapPassed) _show(); _cancel = chatShellYield(_pump); return; } } - _show(); + 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(); + _sinceShown + ..reset() + ..start(); show?.call(); } } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield.dart index 79ffcb26..1676ef33 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_yield.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield.dart @@ -9,3 +9,7 @@ import 'chat_shell_terminal_yield_stub.dart' /// 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; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart index b034d8c0..0354fe0c 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield_stub.dart @@ -2,3 +2,7 @@ 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; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart b/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart index acc17871..e2217236 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_yield_web.dart @@ -4,6 +4,10 @@ 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>(); diff --git a/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart index 06bdc2d3..55ec0a96 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart @@ -55,8 +55,8 @@ void main() { }, ); - test('the view is shown once what waits is written, and while a burst ' - 'is behind at most every show gap', () async { + test('output after a quiet spell is shown at once; streaming output at ' + 'most every show gap', () async { var shown = 0; final writes = []; final feed = ChatShellTerminalFeed( @@ -64,10 +64,11 @@ void main() { show: () => shown++, budget: Duration.zero, slice: 10, - showGap: const Duration(hours: 1), + showGap: const Duration(milliseconds: 300), + deferShows: true, ); feed.add('abc', 3); - // Written whole at once: shown at once. + // The first output, written whole at once: shown at once. expect(writes, ['abc']); expect(shown, 1); feed.add('x' * 35, 38); @@ -78,18 +79,50 @@ void main() { expect(shown, 1); await turn(); await turn(); - // Caught up: the final state is shown. + // Caught up within the gap: shown when the gap has passed. expect(writes.skip(1).join(), 'x' * 35); expect(feed.idle, isTrue); + expect(shown, 1); + await Future.delayed(const Duration(milliseconds: 400)); expect(shown, 2); + // After a quiet spell: at once again. + await Future.delayed(const Duration(milliseconds: 400)); + feed.add('q', 39); + expect(shown, 3); // An action waiting behind output sees it shown first. - feed.add('y' * 25, 63); + feed.add('y' * 25, 64); var shownForAction = -1; feed.then(() => shownForAction = shown); for (var i = 0; i < 5; i++) { await turn(); } - expect(shownForAction, 3); + expect(shownForAction, 4); + expect(shown, 4); + feed.dispose(); + }); + + test('without deferred shows (natively) written output is shown at once; ' + 'only a burst still behind waits for the gap', () async { + var shown = 0; + final feed = ChatShellTerminalFeed( + (_, _) {}, + show: () => shown++, + budget: Duration.zero, + slice: 10, + showGap: const Duration(hours: 1), + deferShows: false, + ); + feed.add('abc', 3); + feed.add('def', 6); + expect(shown, 2); + feed.add('x' * 35, 41); + await turn(); + await turn(); + expect(shown, 2); + for (var i = 0; i < 3; i++) { + await turn(); + } + expect(feed.idle, isTrue); expect(shown, 3); }); diff --git a/app/tool/perf/terminal_stream_bench.dart b/app/tool/perf/terminal_stream_bench.dart index 59947c66..96c17ad5 100644 --- a/app/tool/perf/terminal_stream_bench.dart +++ b/app/tool/perf/terminal_stream_bench.dart @@ -178,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 ms(Duration Function(FrameTiming t) pick) => [ for (final t in _timings) pick(t).inMicroseconds / 1000, ]; From 9d46ac1c03263b89405451670b83e11216a269e6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 03:26:54 +0000 Subject: [PATCH 4/4] Terminal notes: client throughput round 3 (hot spots, changes, benches) Co-Authored-By: Claude Opus 5.5 --- app/notes/terminal-panel.md | 119 ++++++++++++++++++++++++++++++-- app/third_party/xterm/README.md | 11 +++ 2 files changed, 126 insertions(+), 4 deletions(-) diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index a511f932..8ea7b424 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -235,9 +235,11 @@ never waited for and keeps the old pacing (newest 64 KiB, one frame per frames that follow them, which start exactly at the reply's `output_end`. Client: `ChatShellTerminalFeed` (shared with chat shells) writes output into -the emulator in 16 Ki-unit slices and yields to the event loop after 6 ms, -so a 1 MiB replay or a burst never holds a UI frame; `drawn` is the server -byte end of what has been written, which `TerminalTab` acknowledges. +the emulator in slices of at most 16 Ki units and yields to the event loop +after 6 ms, so a 1 MiB replay or a burst never holds a UI frame; `drawn` is +the server byte end of what has been written, which `TerminalTab` +acknowledges. Round 3 (below) made the slices follow the measured speed, +the yields message tasks on the web, and the view's updates one per frame. Chat shell runs (`chat_shell_supervise.go`) share the output buffer code: output is pushed as it arrives, oldest first, while every watcher of the @@ -259,7 +261,109 @@ old server or a client without `flow`): Emulator (`chat_shell_terminal_feed_test.dart`, 896 KiB replay): one synchronous write 160 ms; sliced, the same 161 ms over 20 turns, the -longest turn 12.5 ms. +longest turn 12.5 ms. After round 3 (Linux, test JIT): one write 38 ms, +sliced 33 ms over 5 turns, the longest 11-12 ms (the first, cold, call). + +## Client throughput (round 3, 2026-11-26) + +The emulator parsed about 1 MB/s of `seq` and 0.6 MB/s of `yes` on the web, +so the server's flow control held a flooding program to that. Hot spots +(CPU profiles of the VM and of the web build, `tool/perf/terminal_stream_profile.mjs`): + +- every new line allocated a 4 KiB `Uint32List` (256-cell capacity), 65 % + of `yes` in the VM; reusing a dropped line then cleared all 4 KiB; +- each write decoded the string into a growable rune list; +- every character went through the parser's ByteConsumer, a torn-off + handler, `charset.translate`, the width table and `joinPreviousCell`, + which built a String of the previous cell (`cellContentText`) for each; +- C0 controls, ESC and CSI dispatch called torn-off closures (several times + a direct call in JavaScript); CSI reset `clear()`ed three lists (setting a + JS array's length, 20 % of a coloured stream); `%` in the circular buffer; +- on the web the feed's zero-length timers were clamped to 4 ms after a few + (a third of a burst idle), and every write notified the view, so a stream + drew a frame per turn, each rasterised on the same thread. + +Changes (vendored emulator, `third_party/xterm` README lists them; feed in +`lib/features/chat/shell/`): + +- The parser reads the written strings directly; runs of printable ASCII + and C0 controls are handled straight from the string + (`EscapeParser._processPlain`), a run written into the line in one call + (`Buffer.writeAscii`, `BufferLine.setAsciiCells`) exactly as `writeChar` + would (checked cell by cell in `write_path_test.dart`). +- A line leaving a full scrollback (or a one-line region scroll) is cleared + and reused; a line with anchors (selection ends) still leaves detached. + Lines track the highest cell written since made or cleared, so a clear + touches only those (`getTrimmedLength` scans only those too). +- `joinPreviousCell` rejects characters that cannot join before reading the + cell; the width table covers plane 1 (emoji) instead of searching ranges. +- Switch dispatch for C0, direct calls for CSI and SGR, CSI parameters + emptied element by element, circular index without `%` + (`IndexAwareCircularBuffer.insert` now keeps the start index wrapped). +- Feed: on the web a turn yields through a `MessageChannel` message task + (`chat_shell_terminal_yield_web.dart`), not a clamped timer. Slices are + cut to what the measured speed writes in the turn's remaining budget + (first write 4 Ki units, at least 1 Ki, at most 16 Ki), so a turn ends + near 6 ms for any output. `Terminal.write(notify: false)`: the feed shows + the state (`notifyListeners`) once everything queued is written, before + a queued action, and while still behind after a turn at most every 32 ms. + On the web (frames rasterise on the parsing thread) output written less + than 32 ms after the last show is shown when the gap has passed, about + 30 frames a second while streaming; output after a quiet spell (an echo) + shows at once. Natively frames rasterise on their own thread, so written + output keeps showing at once. Lines scrolled off between two frames are + never drawn (the painter draws the visible rows of the final state). + +Benches (same Linux machine, 16 cores, shared with other agents; load +average noted; before = the base commit e526150b with the same bench): + +- `tool/perf/terminal_parse_bench.dart` (16 MB per workload into + `Terminal.write` in 16 Ki slices, 158x48, best of three). Dart VM + (`dart run`, JIT), after; and the same compiled with + `dart compile js -O4` (what the web build uses) in node/V8: + + | workload | VM before | VM after | V8 before | V8 after | + | --- | --- | --- | --- | --- | + | `seq` | 2.2 | 31.5 | 3.4 | 37.4 | + | `yes` | 0.9 | 27.4 | 1.4 | 28.3 | + | unicode lines | 4.9 | 13.7 | 7.6 | 16.1 | + | coloured lines | 6.1 | 33.6 | 9.1 | 39.4 | + | `screen` | 10.2 | 73.0 | 15.6 | 65.1 | + | `progress` | 9.6 | 93.6 | 16.0 | 73.7 | + + (MB/s; before and after run back to back at load average 19-23, the + machine busy with other agents' builds. At load 2-4 the VM reached + about 55 MB/s for `seq` and 31 for `yes` with an earlier state of these + changes.) + +- `tool/perf/terminal_stream_bench.dart` (profile web build, headless + Chromium, CanvasKit software raster, 1280x800, 8 MB per workload; the + producer now follows a 256 KiB flow window past what is drawn in 32 KiB + frames, at up to 100 MB/s; "parse" is MB per second spent inside + `Terminal.write`; "MB/s" is the whole stream, frames included; two + interleaved runs each, load 2-4): + + | workload | parse before | parse after | MB/s before | MB/s after | after, a frame per write | + | --- | --- | --- | --- | --- | --- | + | `seq` | 2.4 | 54-60 | 1.25 | 20.8-22.1 | 12.6-13.8 | + | `yes` | 1.2 | 38-42 | 0.66-0.69 | 18.4-18.9 | 11.5-12.9 | + | unicode lines | 7.4 | 23-25 | 2.4-2.5 | 7.6-8.0 | 6.5-7.0 | + | coloured lines | 9.7-10.0 | 57-61 | 3.6 | 25.1-25.7 | 14.0-15.1 | + | `screen` | 18.2-18.3 | 105-115 | 6.2-6.3 | 27.6-27.9 | 17.9-21.9 | + | `progress` | 18.4 | 124-135 | 6.3-9.0 | 24.8-28.6 | 20.4-22.3 | + + Frame times at the same output rate (0.5 MB/s, both builds keep up): + build p50/p90 and raster p50/p90 equal or lower after (e.g. `seq` 1.4/1.9 + and 8.2/8.9 ms against 1.5/2.0 and 8.2/9.1). While flooding, a stream + draws 11-16 frames for 8 MB instead of 250-470; with so few frames the + p90 is the start-up frame (max raster 48 ms in both modes). Page rAF + p50 stays 16.7 ms. The rendered final screens match the base + (`/tmp/terminal-round3/shots/`). + +The end-to-end rate is now bounded by frames (each software-rasterised +frame costs 8-14 ms of the page's one thread) and by the 256 KiB flow +window (a frame of 30 ms leaves at most 256 KiB to parse after it). A +larger window on the server, or GPU raster, would raise it further. ## Screen state across reloads (2026-11-26) @@ -507,6 +611,13 @@ software) costs about 2 ms more raster. Runs on this machine vary by about `test/third_party_xterm/{grapheme,glyph_paint}_test.dart`. Symbols font `fonts/symbols-nerd-font/`, `lib/ui/text/terminal_symbols_font.dart`. Bench `tool/perf/terminal_stream_bench.{dart,mjs}`. +- Client throughput (round 3): feed `lib/features/chat/shell/chat_shell_terminal_{feed,yield,yield_stub,yield_web}.dart`; + emulator `third_party/xterm/lib/src/core/escape/parser.dart`, + `core/buffer/{buffer,line,grapheme_join}.dart`, `utils/{byte_consumer,circular_buffer}.dart`; + tests `test/third_party_xterm/write_path_test.dart`, + `test/features/chat/shell/chat_shell_terminal_feed_test.dart`; benches + `tool/perf/terminal_parse_bench.dart` (VM or V8), + `tool/perf/terminal_stream_profile.mjs` (CPU profile of the web bench). ## Verification diff --git a/app/third_party/xterm/README.md b/app/third_party/xterm/README.md index 944a559d..bd6d65af 100644 --- a/app/third_party/xterm/README.md +++ b/app/third_party/xterm/README.md @@ -55,3 +55,14 @@ Local patches (keep this list current): reused until the line changes (`ui/row_pictures.dart`, `BufferLine.version`); glyphs wider than their cells scaled to fit; `TerminalStyle` and `TerminalTheme` compare by value +- write path: the parser reads written strings directly (`ByteConsumer` + counts UTF-16 units, no rune lists) and handles printable ASCII runs and + C0 controls straight from the string (`EscapeHandler.writeAscii`, + `Buffer.writeAscii`, `BufferLine.setAsciiCells`); a line leaving a full + scrollback or a one-line region scroll is cleared and reused unless it + has anchors (`BufferLine.clear`, which clears only the cells written + since); switch dispatch for C0 and direct calls for CSI/SGR; + `joinPreviousCell` rejects non-joining characters first; width table + covers plane 1; `IndexAwareCircularBuffer.insert` keeps its start index + wrapped; `Terminal.write(notify: false)` lets the host notify once per + frame