Terminals: flow-controlled output, immediate echo, sliced emulator writes
Machine terminals no longer skip output for live viewers. Each connection's subscription is a cursor into the 1 MiB retained tail, drained by the connection's writer as soon as the PTY reader writes (no 50 ms tick; a streaming frame gathers for at most 2 ms). A subscription opened with flow: true gets window (256 KiB) in its reply and acknowledges drawn output with terminal_ack; while one is full the reader stops reading the PTY, so the program waits. A subscription full for 3 s without acking stops holding the terminal and later sees a gap; a gone connection drops its subscriptions. Clients that never ask for flow keep the old pacing (newest 64 KiB per 50 ms). terminal_open/terminal_output replies precede the frames that follow them, which start exactly at the reply's output_end. Chat shell runs share the buffer code: output is pushed as it arrives, oldest first, while the chat's watchers keep short queues; 256 KiB unpushed stops the reader, and watchers behind for 3 s get the old pacing. The app asks for flow, takes offsets from the server (frame end, reply output_end) instead of re-encoded text length, acks per quarter window, and writes replays and bursts into the emulator in slices that yield to the event loop (ChatShellTerminalFeed, shared with chat shells). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
/// 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);
|
||||
|
||||
/// 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).
|
||||
class ChatShellTerminalFeed {
|
||||
ChatShellTerminalFeed(
|
||||
this._write, {
|
||||
this.budget = chatShellFeedBudget,
|
||||
this.slice = chatShellFeedSlice,
|
||||
});
|
||||
|
||||
/// Writes [text] into the emulator; [replay] marks a redraw of old output.
|
||||
final void Function(String text, bool replay) _write;
|
||||
final Duration budget;
|
||||
final int slice;
|
||||
|
||||
/// Called with a piece's end once it is drawn.
|
||||
void Function(int end)? onDrawn;
|
||||
|
||||
final Queue<_Piece> _pieces = Queue();
|
||||
Timer? _timer;
|
||||
bool _pumping = false;
|
||||
int _drawn = 0;
|
||||
int _end = 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();
|
||||
_timer?.cancel();
|
||||
_timer = 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();
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
void _schedule() {
|
||||
if (_timer == null && !_pumping) _pump();
|
||||
}
|
||||
|
||||
void _pump() {
|
||||
_timer = 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;
|
||||
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);
|
||||
piece.at = cut;
|
||||
}
|
||||
if (piece.at >= piece.text.length) {
|
||||
_pieces.removeFirst();
|
||||
if (piece.action != null) {
|
||||
piece.action!();
|
||||
} else {
|
||||
_drawn = piece.end;
|
||||
onDrawn?.call(piece.end);
|
||||
}
|
||||
}
|
||||
if (_pieces.isNotEmpty && clock.elapsed >= budget) {
|
||||
_timer = Timer(Duration.zero, _pump);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
_pumping = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
import 'chat_shell_run.dart';
|
||||
import 'chat_shell_terminal_feed.dart';
|
||||
|
||||
/// Lines of scrollback one card's terminal keeps.
|
||||
const int chatShellTerminalScrollback = 5000;
|
||||
@@ -17,6 +18,7 @@ class ChatShellTerminalSession {
|
||||
required this.onInput,
|
||||
required this.onResize,
|
||||
}) : terminal = _ChatShellTerminal() {
|
||||
_feed = ChatShellTerminalFeed(_write);
|
||||
// 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;
|
||||
@@ -32,12 +34,19 @@ class ChatShellTerminalSession {
|
||||
/// Receives the size the view laid the terminal out at.
|
||||
final void Function(int cols, int rows) onResize;
|
||||
|
||||
int _end = 0;
|
||||
late final ChatShellTerminalFeed _feed;
|
||||
bool _live = false;
|
||||
bool _replaying = false;
|
||||
|
||||
/// The absolute output byte this terminal has drawn up to.
|
||||
int get end => _end;
|
||||
/// The absolute output byte this terminal has drawn up to, or will once
|
||||
/// the output waiting in its feed is written.
|
||||
int get end => _feed.end;
|
||||
|
||||
/// The absolute output byte actually drawn so far.
|
||||
int get drawn => _feed.drawn;
|
||||
|
||||
/// Called with the new [drawn] end each time a chunk is drawn whole.
|
||||
set onDrawn(void Function(int end)? callback) => _feed.onDrawn = callback;
|
||||
|
||||
/// Whether typing reaches a running process.
|
||||
bool get live => _live;
|
||||
@@ -45,8 +54,11 @@ class ChatShellTerminalSession {
|
||||
/// Draws [run]'s held output from scratch: on open, after a gap and after
|
||||
/// a readback replaced the card's copy. Answers the emulator gives to old
|
||||
/// queries in that output are not sent: the process asked them long ago.
|
||||
/// A large output is drawn in slices across turns of the event loop
|
||||
/// (ChatShellTerminalFeed), so it never stalls the UI.
|
||||
void replay(ChatShellRun run) {
|
||||
_live = run.running && run.terminal;
|
||||
_feed.restart(run.outputStart);
|
||||
_replaying = true;
|
||||
try {
|
||||
terminal.useMainBuffer();
|
||||
@@ -57,36 +69,46 @@ class ChatShellTerminalSession {
|
||||
if (run.truncated) {
|
||||
terminal.write('\x1b[2m[earlier output was dropped]\x1b[0m\r\n');
|
||||
}
|
||||
var output = _drawable(run, run.output);
|
||||
// A finished run's final newline would leave an empty line below it.
|
||||
if (!run.running && output.endsWith('\r\n')) {
|
||||
output = output.substring(0, output.length - 2);
|
||||
}
|
||||
terminal.write(output);
|
||||
if (!run.running) terminal.setCursorVisibleMode(false);
|
||||
} finally {
|
||||
_replaying = false;
|
||||
}
|
||||
_end = run.outputEnd;
|
||||
var output = _drawable(run, run.output);
|
||||
// A finished run's final newline would leave an empty line below it.
|
||||
if (!run.running && output.endsWith('\r\n')) {
|
||||
output = output.substring(0, output.length - 2);
|
||||
}
|
||||
_feed.add(output, run.outputEnd, replay: true);
|
||||
if (!run.running) _feed.then(() => terminal.setCursorVisibleMode(false));
|
||||
}
|
||||
|
||||
/// Draws one live chunk covering bytes [offset, end) of [run], which
|
||||
/// already holds it. A chunk after a hole redraws the whole held copy.
|
||||
void append(ChatShellRun run, String text, int offset, int end) {
|
||||
if (end <= _end) return;
|
||||
if (offset != _end) {
|
||||
if (end <= _feed.end) return;
|
||||
if (offset != _feed.end) {
|
||||
replay(run);
|
||||
return;
|
||||
}
|
||||
terminal.write(_drawable(run, text));
|
||||
_end = end;
|
||||
_feed.add(_drawable(run, text), end);
|
||||
}
|
||||
|
||||
/// The run ended: nothing typed reaches it any more.
|
||||
void finish(ChatShellRun run) {
|
||||
if (!_live) return;
|
||||
_live = false;
|
||||
terminal.setCursorVisibleMode(false);
|
||||
_feed.then(() => terminal.setCursorVisibleMode(false));
|
||||
}
|
||||
|
||||
/// Stops drawing what still waits (the emulator is going away).
|
||||
void dispose() => _feed.dispose();
|
||||
|
||||
void _write(String text, bool replay) {
|
||||
_replaying = replay;
|
||||
try {
|
||||
terminal.write(text);
|
||||
} finally {
|
||||
_replaying = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows the drawn output takes, through the cursor's line, when the
|
||||
|
||||
@@ -59,7 +59,7 @@ class ChatShellTerminals {
|
||||
_resizes.remove(runId)?.cancel();
|
||||
_inputs.remove(runId);
|
||||
_sentSizes.remove(runId);
|
||||
_sessions.remove(runId);
|
||||
_sessions.remove(runId)?.dispose();
|
||||
}
|
||||
|
||||
/// [run] ended: draw its final output read-only.
|
||||
@@ -98,6 +98,9 @@ class ChatShellTerminals {
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
for (final session in _sessions.values) {
|
||||
session.dispose();
|
||||
}
|
||||
for (final timer in _resizes.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ class TerminalHub extends ChangeNotifier {
|
||||
}
|
||||
try {
|
||||
final reply = await machine.gateway.call('terminal_open', {
|
||||
'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)},
|
||||
'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd), 'flow': true},
|
||||
});
|
||||
final record = reply['terminal'];
|
||||
if (record is! Map) throw StateError('The server sent no terminal.');
|
||||
|
||||
@@ -28,11 +28,13 @@ class TerminalStream {
|
||||
/// Whether nothing was received yet.
|
||||
bool get empty => stream.isEmpty && end == 0;
|
||||
|
||||
/// Replaces the held copy with a read of the server's retained tail.
|
||||
void reset(String output, int outputStart, String name) {
|
||||
/// Replaces the held copy with a read of the server's retained tail,
|
||||
/// covering bytes [outputStart, outputEnd) (the server's offsets: the
|
||||
/// text's own UTF-8 length differs where invalid bytes were replaced).
|
||||
void reset(String output, int outputStart, int outputEnd, String name) {
|
||||
text = output;
|
||||
start = outputStart;
|
||||
end = outputStart + utf8.encode(output).length;
|
||||
end = outputEnd;
|
||||
stream = name;
|
||||
_bound();
|
||||
}
|
||||
@@ -55,7 +57,11 @@ class TerminalStream {
|
||||
// Never split a surrogate pair.
|
||||
final unit = text.codeUnitAt(cut);
|
||||
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
|
||||
final dropped = text.substring(0, cut);
|
||||
text = text.substring(cut);
|
||||
start = end - utf8.encode(text).length;
|
||||
// The server's offsets are not re-derived from the text: only the
|
||||
// dropped part is measured (approximately, for replaced bytes).
|
||||
start += utf8.encode(dropped).length;
|
||||
if (start > end) start = end;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ class TerminalTab extends ChangeNotifier {
|
||||
onResize: _resized,
|
||||
);
|
||||
session.terminal.onTitleChange = _titled;
|
||||
session.onDrawn = _drawn;
|
||||
}
|
||||
|
||||
final String machineId;
|
||||
@@ -45,6 +46,12 @@ class TerminalTab extends ChangeNotifier {
|
||||
bool _reading = false;
|
||||
bool _again = false;
|
||||
|
||||
/// The flow window the server granted this connection's subscription
|
||||
/// (0: an older server, which takes no acknowledgements), and the end
|
||||
/// last acknowledged.
|
||||
int _window = 0;
|
||||
int _acked = 0;
|
||||
|
||||
/// False while the terminal's machine is not connected.
|
||||
bool connected = true;
|
||||
|
||||
@@ -83,6 +90,7 @@ class TerminalTab extends ChangeNotifier {
|
||||
_gateway = gateway;
|
||||
connected = true;
|
||||
_sentSize = null;
|
||||
_window = 0;
|
||||
_update(info);
|
||||
unawaited(resume());
|
||||
}
|
||||
@@ -119,7 +127,11 @@ class TerminalTab extends ChangeNotifier {
|
||||
|
||||
Future<void> _read(int? after) async {
|
||||
final reply = await _gateway.call('terminal_output', {
|
||||
'terminal_request': {'terminal_id': _info.id, 'after': ?after},
|
||||
'terminal_request': {
|
||||
'terminal_id': _info.id,
|
||||
'after': ?after,
|
||||
'flow': true,
|
||||
},
|
||||
});
|
||||
final record = reply['terminal'];
|
||||
if (_disposed || record is! Map) return;
|
||||
@@ -131,11 +143,18 @@ class TerminalTab extends ChangeNotifier {
|
||||
}
|
||||
final output = '${record['output'] ?? ''}';
|
||||
final start = (record['output_start'] as num?)?.toInt() ?? 0;
|
||||
// The reply's own end (an older server's is its total, which a text
|
||||
// of only valid characters also reaches).
|
||||
var end = (record['output_end'] as num?)?.toInt() ?? 0;
|
||||
if (end < start) end = start + _byteLength(output);
|
||||
// The server counts this connection's window from the reply's end.
|
||||
_window = (record['window'] as num?)?.toInt() ?? 0;
|
||||
_acked = end;
|
||||
if (after == null || start > _stream.end) {
|
||||
_stream.reset(output, start, info.stream);
|
||||
_stream.reset(output, start, end, info.stream);
|
||||
session.replay(_run());
|
||||
} else {
|
||||
_append(output, start, start + _byteLength(output));
|
||||
_append(output, start, end);
|
||||
}
|
||||
if (!info.running) session.finish(_run());
|
||||
}
|
||||
@@ -157,8 +176,9 @@ class TerminalTab extends ChangeNotifier {
|
||||
final before = _stream.end;
|
||||
final fresh = _stream.add(output, offset, end);
|
||||
if (fresh == null) {
|
||||
// Frames were missed: read the retained tail again.
|
||||
unawaited(resume());
|
||||
// A flow-controlled read in flight covers whatever was sent before
|
||||
// it; otherwise frames were missed: read the retained tail again.
|
||||
if (!(_reading && _window > 0)) unawaited(resume());
|
||||
return;
|
||||
}
|
||||
if (fresh.isNotEmpty) session.append(_run(), fresh, before, end);
|
||||
@@ -176,6 +196,21 @@ class TerminalTab extends ChangeNotifier {
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// The emulator drew output up to [end]: acknowledge it once a quarter
|
||||
/// of the window is consumed, so the server sends (and reads) more.
|
||||
void _drawn(int end) {
|
||||
if (_window <= 0 || !connected || _disposed) return;
|
||||
if (end - _acked < _window ~/ 4) return;
|
||||
_acked = end;
|
||||
unawaited(
|
||||
_gateway
|
||||
.call('terminal_ack', {
|
||||
'terminal_request': {'terminal_id': _info.id, 'after': end},
|
||||
})
|
||||
.catchError((Object _) => <String, dynamic>{}),
|
||||
);
|
||||
}
|
||||
|
||||
void _titled(String title) {
|
||||
if (title == _oscTitle) return;
|
||||
_oscTitle = title.trim();
|
||||
@@ -229,6 +264,8 @@ class TerminalTab extends ChangeNotifier {
|
||||
_resize?.cancel();
|
||||
_pipe = null;
|
||||
session.terminal.onTitleChange = null;
|
||||
session.onDrawn = null;
|
||||
session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,8 +115,55 @@ data?, after?}`.
|
||||
loop: it waits up to 3 s for the shell).
|
||||
- Pushed `terminal_event`: output `{terminal_id, output, offset, end}` to
|
||||
subscribed connections, lifecycle `{terminal_id, terminal}` (opened,
|
||||
title, exited, closed) to every connection. A slow connection's queue
|
||||
(256 frames) drops output; the client sees the offset gap and re-reads.
|
||||
title, exited, closed) to every connection. Output flow is described
|
||||
under "Output flow" below; offsets are stream bytes, taken from the
|
||||
server (`end`, `output_end`), never from the text's re-encoded length.
|
||||
|
||||
## Output flow (2026-11-25)
|
||||
|
||||
Server (`terminal_flow.go`, `terminal_clients.go`): each connection's
|
||||
subscription is a cursor into the terminal's 1 MiB retained tail; the
|
||||
connection's writer goroutine sends from it as soon as the PTY reader has
|
||||
written (no tick), coalescing what arrived during the previous write and,
|
||||
while output streams, letting a frame gather for at most 2 ms. The app asks
|
||||
for `flow: true` on `terminal_open`/`terminal_output`; those replies carry
|
||||
`window` (256 KiB) and the app sends `terminal_ack {terminal_id, after}`
|
||||
each time it has drawn a quarter window. A flow subscription is sent at most
|
||||
`window` bytes past its last ack, and while one is full the PTY reader stops
|
||||
(the program blocks on its writes) instead of skipping. One that stays full
|
||||
for 3 s without acknowledging stops holding the terminal; on its next ack it
|
||||
gets a frame after a gap and re-reads. A gone connection drops its
|
||||
subscriptions at once. A subscription without `flow` (an older app build) is
|
||||
never waited for and keeps the old pacing (newest 64 KiB, one frame per
|
||||
50 ms). `terminal_open` and `terminal_output` replies are written before the
|
||||
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.
|
||||
|
||||
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
|
||||
chat has fewer than 8 queued frames; 256 KiB unpushed stops the reader. A
|
||||
watcher behind for 3 s gets the old pacing (newest chunk per flush tick, a
|
||||
gap) until it catches up. The DB snapshot every 2 s is unchanged.
|
||||
|
||||
Measured (`PIPELINES_TERMINAL_MEASURE=1 go test ./internal/server -run
|
||||
TestMeasureTerminalStream -v`, loopback, fast reading client; before = the
|
||||
old server or a client without `flow`):
|
||||
|
||||
| workload | before | after |
|
||||
| --- | --- | --- |
|
||||
| `seq 1 500000` (3.9 MB) | 3 frames, 3.69 MB skipped, 1.3 MB/s | 70 frames, 0 skipped, 27 MB/s |
|
||||
| `cat` 2.1 MB | 1 frame, 2.04 MB skipped | 34 frames, 0 skipped, 117 MB/s |
|
||||
| `yes \| head -1000000` (3.0 MB) | 5 frames, 2.67 MB skipped | 126 frames, 0 skipped, 12 MB/s |
|
||||
| keystroke echo (median, 40 keys) | 43.3 ms | 0.17 ms |
|
||||
| longest gap between frames while streaming | 50 ms | 2.5-4.2 ms |
|
||||
|
||||
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.
|
||||
|
||||
## Login and lifetime (server)
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
|
||||
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart';
|
||||
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
Future<void> turn() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
void main() {
|
||||
test('output is written in slices, one turn at a time past the '
|
||||
'budget, in order', () async {
|
||||
final writes = <(String, bool)>[];
|
||||
final drawn = <int>[];
|
||||
final feed = ChatShellTerminalFeed(
|
||||
(text, replay) => writes.add((text, replay)),
|
||||
budget: Duration.zero,
|
||||
slice: 1000,
|
||||
)..onDrawn = drawn.add;
|
||||
feed.add('a' * 2500, 2500, replay: true);
|
||||
feed.add('b' * 10, 2510);
|
||||
// Only the first slice is written at once.
|
||||
expect(writes, [('a' * 1000, true)]);
|
||||
expect(feed.drawn, 0);
|
||||
expect(feed.end, 2510);
|
||||
await turn();
|
||||
await turn();
|
||||
expect(writes.map((w) => w.$1.length), [1000, 1000, 500]);
|
||||
expect(drawn, [2500]);
|
||||
await turn();
|
||||
expect(writes.last, ('b' * 10, false));
|
||||
expect(drawn, [2500, 2510]);
|
||||
expect(feed.idle, isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'a restart drops what waits; then() runs after what is queued',
|
||||
() async {
|
||||
final writes = <String>[];
|
||||
final feed = ChatShellTerminalFeed(
|
||||
(text, _) => writes.add(text),
|
||||
budget: Duration.zero,
|
||||
slice: 4,
|
||||
);
|
||||
feed.add('abcdefgh', 8);
|
||||
feed.restart(20);
|
||||
await turn();
|
||||
expect(writes, ['abcd']);
|
||||
expect((feed.drawn, feed.end), (20, 20));
|
||||
final order = <String>[];
|
||||
feed.add('wxyz12', 26);
|
||||
feed.then(() => order.add('then@${writes.last}'));
|
||||
await turn();
|
||||
await turn();
|
||||
expect(order, ['then@12']);
|
||||
},
|
||||
);
|
||||
|
||||
test('a surrogate pair is never split between two writes', () {
|
||||
final writes = <String>[];
|
||||
final feed = ChatShellTerminalFeed((text, _) => writes.add(text), slice: 3);
|
||||
feed.add('ab\u{1F600}cd', 8);
|
||||
expect(writes.first, 'ab\u{1F600}');
|
||||
expect(writes.join(), 'ab\u{1F600}cd');
|
||||
});
|
||||
|
||||
test('a 1 MiB replay never blocks a turn for long (measured)', () async {
|
||||
final big = List.filled(1 << 16, 'y\r\nline 0123\r\n').join();
|
||||
final direct = Stopwatch()..start();
|
||||
(Terminal(
|
||||
maxLines: chatShellTerminalScrollback,
|
||||
)..resize(80, 24)).write(big);
|
||||
direct.stop();
|
||||
final run = ChatShellRun.fromJson({
|
||||
'id': 'run_1',
|
||||
'command': 'yes',
|
||||
'directory': '/w',
|
||||
'status': 'running',
|
||||
'started_at': 1,
|
||||
'output': '',
|
||||
'output_bytes': 0,
|
||||
'terminal': true,
|
||||
'cols': 80,
|
||||
'rows': 24,
|
||||
})!;
|
||||
final session = ChatShellTerminalSession(
|
||||
run,
|
||||
onInput: (_) {},
|
||||
onResize: (_, _) {},
|
||||
);
|
||||
final held = ChatShellRun.fromJson({
|
||||
...{
|
||||
'id': 'run_1',
|
||||
'command': 'yes',
|
||||
'directory': '/w',
|
||||
'status': 'running',
|
||||
'started_at': 1,
|
||||
'terminal': true,
|
||||
'cols': 80,
|
||||
'rows': 24,
|
||||
},
|
||||
'output': big,
|
||||
'output_bytes': big.length,
|
||||
})!;
|
||||
final clock = Stopwatch()..start();
|
||||
session.replay(held);
|
||||
var longest = clock.elapsed;
|
||||
var turns = 1;
|
||||
while (session.drawn < big.length) {
|
||||
final before = clock.elapsed;
|
||||
await turn();
|
||||
final spent = clock.elapsed - before;
|
||||
if (spent > longest) longest = spent;
|
||||
turns++;
|
||||
}
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'replay of ${big.length >> 10} KiB: one write ${direct.elapsedMilliseconds} ms; '
|
||||
'sliced ${clock.elapsedMilliseconds} ms over $turns turns, '
|
||||
'longest turn ${longest.inMicroseconds / 1000} ms',
|
||||
);
|
||||
expect(longest, lessThan(const Duration(milliseconds: 60)));
|
||||
expect(session.terminal.buffer.lines.length, greaterThan(1000));
|
||||
});
|
||||
}
|
||||
@@ -21,6 +21,13 @@ class TerminalGateway implements ApiGateway {
|
||||
/// When set, requests of this type fail with this message.
|
||||
final Map<String, String> refuse = {};
|
||||
|
||||
/// The flow window terminal_output grants (0: an older server).
|
||||
int window = 0;
|
||||
|
||||
/// Bytes a terminal's stream holds beyond its text's UTF-8 (negative
|
||||
/// where runs of invalid bytes became one shorter replacement character).
|
||||
final Map<String, int> byteShift = {};
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
|
||||
@@ -52,9 +59,10 @@ class TerminalGateway implements ApiGateway {
|
||||
return {
|
||||
...terminals[id]!,
|
||||
'stream': stream,
|
||||
'output_end': bytes.length,
|
||||
'output_end': bytes.length + (byteShift[id] ?? 0),
|
||||
if (withOutput) 'output': utf8.decode(bytes.sublist(start)),
|
||||
if (withOutput) 'output_start': start,
|
||||
if (withOutput && window > 0) 'window': window,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -67,15 +75,16 @@ class TerminalGateway implements ApiGateway {
|
||||
}
|
||||
}
|
||||
|
||||
void pushOutput(String id, String text, int offset) => _frames.add({
|
||||
'type': 'terminal_event',
|
||||
'terminal_event': {
|
||||
'terminal_id': id,
|
||||
'output': text,
|
||||
'offset': offset,
|
||||
'end': offset + utf8.encode(text).length,
|
||||
},
|
||||
});
|
||||
void pushOutput(String id, String text, int offset, {int? end}) =>
|
||||
_frames.add({
|
||||
'type': 'terminal_event',
|
||||
'terminal_event': {
|
||||
'terminal_id': id,
|
||||
'output': text,
|
||||
'offset': offset,
|
||||
'end': end ?? offset + utf8.encode(text).length,
|
||||
},
|
||||
});
|
||||
|
||||
void lifecycle(String id, Map<String, dynamic> changes) {
|
||||
terminals[id] = {...terminals[id]!, ...changes};
|
||||
@@ -117,6 +126,7 @@ class TerminalGateway implements ApiGateway {
|
||||
terminals.remove(id);
|
||||
return {'type': type, 'terminal': record};
|
||||
case 'terminal_input':
|
||||
case 'terminal_ack':
|
||||
return {'type': type};
|
||||
case 'terminal_resize':
|
||||
return {'type': type, 'terminal': _record(id)};
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
String screen(TerminalTab tab) {
|
||||
final buffer = tab.session.terminal.buffer;
|
||||
return [
|
||||
for (var y = 0; y < buffer.height; y++)
|
||||
buffer.lines[y].getText().trimRight(),
|
||||
].where((line) => line.isNotEmpty).join('\n');
|
||||
}
|
||||
|
||||
void main() {
|
||||
late TerminalGateway mac;
|
||||
late TerminalHub hub;
|
||||
|
||||
setUp(() {
|
||||
mac = TerminalGateway();
|
||||
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
|
||||
});
|
||||
tearDown(() async {
|
||||
hub.dispose();
|
||||
await mac.close();
|
||||
});
|
||||
|
||||
Future<void> settle() async {
|
||||
for (var i = 0; i < 3; i++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
Future<TerminalTab> opened(String text) async {
|
||||
mac.add('term_a', text: text);
|
||||
hub.activate();
|
||||
await settle();
|
||||
return hub.tabs.single;
|
||||
}
|
||||
|
||||
test('offsets come from the server, not the re-encoded text', () async {
|
||||
// The server replaced two invalid bytes with one U+FFFD (three bytes):
|
||||
// its stream holds 3 bytes where the text re-encodes to 4.
|
||||
mac.byteShift['term_a'] = -1;
|
||||
final tab = await opened('a�');
|
||||
expect(tab.session.end, 3);
|
||||
mac.pushOutput('term_a', 'b', 3);
|
||||
await settle();
|
||||
expect(screen(tab), 'a�b');
|
||||
expect(tab.session.end, 4);
|
||||
// A continuation, not a gap: nothing is read again.
|
||||
expect(mac.bodies('terminal_output'), hasLength(1));
|
||||
});
|
||||
|
||||
test('reads ask for flow; what is drawn is acknowledged per quarter '
|
||||
'window', () async {
|
||||
mac.window = 1024;
|
||||
final tab = await opened('');
|
||||
expect(mac.bodies('terminal_output').single['flow'], isTrue);
|
||||
var end = 0;
|
||||
void push(int bytes) {
|
||||
mac.pushOutput('term_a', 'x' * bytes, end);
|
||||
end += bytes;
|
||||
}
|
||||
|
||||
push(300);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_ack'), [
|
||||
{'terminal_id': 'term_a', 'after': 300},
|
||||
]);
|
||||
push(100);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_ack'), hasLength(1));
|
||||
push(200);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_ack').last, {
|
||||
'terminal_id': 'term_a',
|
||||
'after': 600,
|
||||
});
|
||||
expect(tab.session.drawn, 600);
|
||||
});
|
||||
|
||||
test('an older server (no window) is never acknowledged', () async {
|
||||
await opened('');
|
||||
mac.pushOutput('term_a', 'x' * 100000, 0);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_ack'), isEmpty);
|
||||
});
|
||||
|
||||
test('a large retained tail is drawn over several turns', () async {
|
||||
final big = List.filled(40000, 'line of output\r\n').join();
|
||||
final tab = await opened('');
|
||||
mac.output['term_a'] = big;
|
||||
await tab.resume();
|
||||
// The read is drawn in slices: not all of it in the turn it arrived.
|
||||
expect(tab.session.drawn, lessThan(tab.session.end));
|
||||
for (var turn = 0; turn < 1000 && tab.session.drawn < big.length; turn++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
expect(tab.session.drawn, big.length);
|
||||
expect(screen(tab).split('\n').last, 'line of output');
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user