e13cb99ade
A headless xterm-compatible emulator (internal/termstate) follows each machine terminal's PTY output under the same lock as the 1 MiB tail. A terminal_output from before the retained tail (new page, reload, gap) now gets output_snapshot: an escape stream that resets the client and restores scrollback (1000 lines), main screen, the alternate screen when in use (via ?1049h so the program's exit brings the shell back), saved cursors, tabs, scroll region, cursor incl. pending wrap, modes (mouse tracking/encoding, bracketed paste, DECCKM, keypad, autowrap, origin, focus, ...), charsets, pen and title, as of output_end; frames continue there. Reads inside the tail stay raw. No Go library was adequate: charmbracelet/x/vt and vito/midterm scroll at 0.2-4 MB/s and hide modes/pen/region; vt10x is unmaintained. termstate runs at 160-200 MB/s. The app treats a snapshot reply as a replay without the dropped-output line, and every replay now starts with RIS so stale modes end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
9.7 KiB
Dart
321 lines
9.7 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import '../../core/api_gateway.dart';
|
|
import '../chat/shell/chat_shell_run.dart';
|
|
import '../chat/shell/chat_shell_terminal_session.dart';
|
|
import '../chat/shell/chat_shell_terminals.dart';
|
|
import 'terminal_info.dart';
|
|
import 'terminal_stream.dart';
|
|
|
|
/// One open machine terminal in the app: its record, the output held for
|
|
/// redraws, and the emulator session the panel, window and page draw (the
|
|
/// chat shell's own, so typing, links and colours behave the same).
|
|
///
|
|
/// It outlives every view: hiding the panel keeps it, and reconnecting
|
|
/// resumes its output from the last byte it holds.
|
|
class TerminalTab extends ChangeNotifier {
|
|
TerminalTab({
|
|
required this.machineId,
|
|
required this.machineName,
|
|
required this._gateway,
|
|
required this._info,
|
|
}) {
|
|
session = ChatShellTerminalSession(
|
|
_run(),
|
|
onInput: _input,
|
|
onReply: (data) => _input(data, reply: true),
|
|
onResize: _resized,
|
|
onActivate: _activated,
|
|
);
|
|
session.terminal.onTitleChange = _titled;
|
|
session.onDrawn = _drawn;
|
|
}
|
|
|
|
final String machineId;
|
|
String machineName;
|
|
ApiGateway _gateway;
|
|
TerminalInfo _info;
|
|
late final ChatShellTerminalSession session;
|
|
final TerminalStream _stream = TerminalStream();
|
|
ChatShellInputPipe? _pipe;
|
|
Timer? _resize;
|
|
(int, int)? _sentSize;
|
|
String _oscTitle = '';
|
|
bool _disposed = false;
|
|
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;
|
|
|
|
/// The last refusal of input, a resize or a read, in the server's words.
|
|
String? error;
|
|
|
|
String get key => terminalKey(machineId, _info.id);
|
|
TerminalInfo get info => _info;
|
|
ApiGateway get gateway => _gateway;
|
|
|
|
/// The window title the shell set (seen in its output or recorded by the
|
|
/// server), else the folder it started in.
|
|
String get title {
|
|
if (_oscTitle.isNotEmpty) return _oscTitle;
|
|
if (_info.title.isNotEmpty) return _info.title;
|
|
return terminalFolderLabel(_info.cwd);
|
|
}
|
|
|
|
ChatShellRun _run() => ChatShellRun(
|
|
id: _info.id,
|
|
command: title,
|
|
directory: _info.cwd,
|
|
status: _info.running ? 'running' : 'exited',
|
|
startedAt: _info.createdAt,
|
|
output: _stream.text,
|
|
outputStart: _stream.start,
|
|
outputEnd: _stream.end,
|
|
snapshot: _stream.snapshot,
|
|
terminal: true,
|
|
cols: _info.cols,
|
|
rows: _info.rows,
|
|
);
|
|
|
|
/// The machine connected again (or for the first time): requests go
|
|
/// through [gateway] and the output resumes from the held end.
|
|
void attach(ApiGateway gateway, TerminalInfo info) {
|
|
_gateway = gateway;
|
|
connected = true;
|
|
_sentSize = null;
|
|
_window = 0;
|
|
_update(info);
|
|
unawaited(resume());
|
|
// The new connection reports the size it draws at; the server applies
|
|
// it while no other client is the active one.
|
|
final size = session.viewSize;
|
|
if (size != null) _resized(size.$1, size.$2);
|
|
}
|
|
|
|
void disconnected() {
|
|
connected = false;
|
|
_pipe = null;
|
|
_notify();
|
|
}
|
|
|
|
/// Reads what the server retains after the held end (all of it on a new
|
|
/// stream or after a gap) and subscribes this connection to the rest.
|
|
Future<void> resume() async {
|
|
if (_disposed) return;
|
|
if (_reading) {
|
|
_again = true;
|
|
return;
|
|
}
|
|
_reading = true;
|
|
try {
|
|
do {
|
|
_again = false;
|
|
final same = !_stream.empty && _info.stream == _stream.stream;
|
|
await _read(same ? _stream.end : null);
|
|
} while (_again && !_disposed);
|
|
error = null;
|
|
} catch (failure) {
|
|
error = '$failure';
|
|
} finally {
|
|
_reading = false;
|
|
_notify();
|
|
}
|
|
}
|
|
|
|
Future<void> _read(int? after) async {
|
|
final reply = await _gateway.call('terminal_output', {
|
|
'terminal_request': {
|
|
'terminal_id': _info.id,
|
|
'after': ?after,
|
|
'flow': true,
|
|
},
|
|
});
|
|
final record = reply['terminal'];
|
|
if (_disposed || record is! Map) return;
|
|
final info = TerminalInfo.fromJson(record);
|
|
_info = info;
|
|
if (after != null && info.stream != _stream.stream) {
|
|
// The server restarted since: its stream starts again at zero.
|
|
return _read(null);
|
|
}
|
|
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;
|
|
// A read from before the server's retained tail (a new page, a reload,
|
|
// a gap) is its snapshot of the terminal: the screens, scrollback,
|
|
// cursor and modes as of the reply's end.
|
|
final snapshot = record['output_snapshot'] == true;
|
|
if (after == null || start > _stream.end || snapshot) {
|
|
_stream.reset(output, start, end, info.stream, snapshot: snapshot);
|
|
session.replay(_run());
|
|
} else {
|
|
_append(output, start, end);
|
|
}
|
|
if (!info.running) session.finish(_run());
|
|
}
|
|
|
|
/// One pushed `terminal_event` for this terminal.
|
|
void frame(Map event) {
|
|
final record = event['terminal'];
|
|
if (record is Map) {
|
|
_update(TerminalInfo.fromJson(record));
|
|
return;
|
|
}
|
|
final output = '${event['output'] ?? ''}';
|
|
final offset = (event['offset'] as num?)?.toInt() ?? 0;
|
|
final end = (event['end'] as num?)?.toInt() ?? 0;
|
|
_append(output, offset, end);
|
|
}
|
|
|
|
void _append(String output, int offset, int end) {
|
|
final before = _stream.end;
|
|
final fresh = _stream.add(output, offset, end);
|
|
if (fresh == null) {
|
|
// 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);
|
|
}
|
|
|
|
void _update(TerminalInfo info) {
|
|
final ended = _info.running && !info.running;
|
|
// A lifecycle record carries no stream; keep the one the output has.
|
|
_info = info.stream.isEmpty ? info.withStream(_stream.stream) : info;
|
|
if (ended) {
|
|
_resize?.cancel();
|
|
_pipe = null;
|
|
session.finish(_run());
|
|
}
|
|
_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();
|
|
_notify();
|
|
}
|
|
|
|
/// Sends typed text, or with [reply] the emulator's automatic answer to a
|
|
/// query, which the server passes on only from the active client. Typing
|
|
/// carries the size this client draws at: it becomes the active client.
|
|
void _input(String data, {bool reply = false}) {
|
|
if (_disposed || !connected) return;
|
|
final id = _info.id;
|
|
final gateway = _gateway;
|
|
(_pipe ??= ChatShellInputPipe((data, reply) {
|
|
final size = reply ? null : session.viewSize;
|
|
return gateway.call('terminal_input', {
|
|
'terminal_request': {
|
|
'terminal_id': id,
|
|
'data': data,
|
|
if (reply) 'reply': true,
|
|
'cols': ?size?.$1,
|
|
'rows': ?size?.$2,
|
|
},
|
|
});
|
|
}, _failed)).add(data, reply: reply);
|
|
}
|
|
|
|
void _resized(int cols, int rows) {
|
|
if (_disposed || !_info.running || !connected) return;
|
|
_resize?.cancel();
|
|
_resize = Timer(chatShellResizeDelay, () {
|
|
if (_sentSize == (cols, rows) || !connected) return;
|
|
_sendSize(cols, rows, activate: false);
|
|
});
|
|
}
|
|
|
|
/// A view gained focus: this client becomes the active one and the
|
|
/// terminal takes its size at once.
|
|
void _activated(int cols, int rows) {
|
|
if (_disposed || !_info.running || !connected) return;
|
|
_resize?.cancel();
|
|
_sendSize(cols, rows, activate: true);
|
|
}
|
|
|
|
void _sendSize(int cols, int rows, {required bool activate}) {
|
|
_sentSize = (cols, rows);
|
|
_gateway
|
|
.call('terminal_resize', {
|
|
'terminal_request': {
|
|
'terminal_id': _info.id,
|
|
'cols': cols,
|
|
'rows': rows,
|
|
if (activate) 'activate': true,
|
|
},
|
|
})
|
|
.catchError((Object failure) {
|
|
_failed(failure);
|
|
return <String, dynamic>{};
|
|
});
|
|
}
|
|
|
|
void _failed(Object failure) {
|
|
error = '$failure';
|
|
_notify();
|
|
}
|
|
|
|
void _notify() {
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_resize?.cancel();
|
|
_pipe = null;
|
|
session.terminal.onTitleChange = null;
|
|
session.onDrawn = null;
|
|
session.dispose();
|
|
super.dispose();
|
|
}
|
|
}
|
|
|
|
String terminalKey(String machineId, String terminalId) =>
|
|
'$machineId/$terminalId';
|
|
|
|
/// The last folder of [cwd] ("~" for a home directory), for a tab title.
|
|
String terminalFolderLabel(String cwd) {
|
|
final parts = cwd.split('/').where((part) => part.isNotEmpty).toList();
|
|
if (parts.isEmpty) return '/';
|
|
if (parts.length == 2 && (parts[0] == 'Users' || parts[0] == 'home')) {
|
|
return '~';
|
|
}
|
|
return parts.last;
|
|
}
|
|
|
|
int _byteLength(String text) => utf8.encode(text).length;
|