Files
pipelines/app/lib/features/terminal/terminal_tab.dart
T
alan aaed57e105 Merge main into the terminal flow-control branch
Conflicts resolved keeping both sides: main's active-client rules, input
lane, reply marking and key input, and this branch's flow control,
acknowledgements, subscriptions and sliced emulator feed. terminal_ack
joins the terminal lane; the feed marks each live slice it writes as
drawing, so the emulator's answers still go to onReply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:03:20 +00:00

316 lines
9.4 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,
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;
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();
}
/// 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;