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,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