Files
pipelines/app/lib/features/terminal/terminal_tab.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

287 lines
8.3 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,
onResize: _resized,
);
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,
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());
}
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;
if (after == null || start > _stream.end) {
_stream.reset(output, start, end, info.stream);
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();
}
void _input(String data) {
if (_disposed || !connected) return;
final id = _info.id;
final gateway = _gateway;
(_pipe ??= ChatShellInputPipe(
(data) => gateway.call('terminal_input', {
'terminal_request': {'terminal_id': id, 'data': data},
}),
(failure) {
error = '$failure';
_notify();
},
)).add(data);
}
void _resized(int cols, int rows) {
if (_disposed || !_info.running || !connected) return;
_resize?.cancel();
_resize = Timer(chatShellResizeDelay, () {
if (_sentSize == (cols, rows) || !connected) return;
_sentSize = (cols, rows);
_gateway
.call('terminal_resize', {
'terminal_request': {
'terminal_id': _info.id,
'cols': cols,
'rows': rows,
},
})
.catchError((Object failure) {
error = '$failure';
_notify();
return <String, dynamic>{};
});
});
}
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;