Files
pipelines/app/lib/features/chat/shell/chat_shell_terminal_session.dart
T
alan 0963a071d0 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>
2026-11-25 23:57:18 +00:00

174 lines
6.1 KiB
Dart

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;
/// The terminal emulator state of one run: the xterm [terminal] fed with the
/// run's output in order, and the bridge from what the operator types (or
/// the emulator answers) to the running process.
///
/// It keeps no copy of typed input: [Terminal.onOutput] hands each key or
/// paste straight to [onInput], which sends it.
class ChatShellTerminalSession {
ChatShellTerminalSession(
ChatShellRun run, {
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;
terminal.onResize = (cols, rows, _, _) => onResize(cols, rows);
replay(run);
}
final Terminal terminal;
/// Receives input for the process; only called while the run is live.
final void Function(String data) onInput;
/// Receives the size the view laid the terminal out at.
final void Function(int cols, int rows) onResize;
late final ChatShellTerminalFeed _feed;
bool _live = false;
bool _replaying = false;
/// 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;
/// 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();
terminal.buffer.clear();
terminal.buffer.setCursor(0, 0);
terminal.setCursorVisibleMode(true);
terminal.write('\x1b[0m');
if (run.truncated) {
terminal.write('\x1b[2m[earlier output was dropped]\x1b[0m\r\n');
}
} finally {
_replaying = false;
}
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 <= _feed.end) return;
if (offset != _feed.end) {
replay(run);
return;
}
_feed.add(_drawable(run, text), end);
}
/// The run ended: nothing typed reaches it any more.
void finish(ChatShellRun run) {
if (!_live) return;
_live = 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
/// terminal is [cols] wide: a finished run's box is sized by it before the
/// view lays the terminal out, so a card never changes height after it.
int rowsAt(int cols) {
final buffer = terminal.buffer;
final last = buffer.absoluteCursorY.clamp(0, buffer.height - 1);
var rows = 0;
var length = 0;
void close() => rows += length <= 0 ? 1 : (length + cols - 1) ~/ cols;
for (var y = 0; y <= last; y++) {
final line = buffer.lines[y];
if (y > 0 && !line.isWrapped) {
close();
length = 0;
}
// A row the next one continues is full to the terminal's width.
final continued = y + 1 < buffer.height && buffer.lines[y + 1].isWrapped;
length += continued ? line.length : line.getTrimmedLength();
}
close();
return rows;
}
void _output(String data) {
if (_live && !_replaying) onInput(data);
}
/// Plain-pipe output has bare newlines, which a terminal draws as a line
/// feed without a carriage return.
static String _drawable(ChatShellRun run, String text) =>
run.terminal ? text : text.replaceAll('\n', '\r\n');
}
/// The emulator with the scrollback the cards keep. It answers a cursor
/// position query (DSR 6) with the one-based row and column the protocol
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
class _ChatShellTerminal extends Terminal {
_ChatShellTerminal() : super(maxLines: chatShellTerminalScrollback);
@override
void sendCursorPosition() {
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
}
/// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank
/// row below the cursor while doing so: the extra rows push the top of
/// the output into scrollback. Blank rows below the cursor are dropped
/// instead, keeping the cursor on its line.
@override
void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) {
super.resize(width, height, pixelWidth, pixelHeight);
final lines = buffer.lines;
while (buffer.height > viewHeight &&
buffer.height - 1 > buffer.absoluteCursorY &&
lines[buffer.height - 1].getText().trim().isEmpty) {
lines.pop();
buffer.setCursor(buffer.cursorX, buffer.cursorY + 1);
}
}
}