Files
pipelines/app/lib/features/terminal/terminal_tab.dart
T
alan c3458d8a7f Terminals: one active client per terminal; keystrokes skip the request queue
Several clients drawing one terminal (machine terminal or chat terminal
command) no longer interfere. The server tracks, per terminal, the
connections drawing it, most recently active first: the active client
(the opener, then whoever last typed or focused it) owns the PTY size and
is the only one whose emulator's automatic query answers reach the
process; other clients' answers are acknowledged and dropped, and their
sizes recorded but not applied. When the active connection closes the next
most recent client's size is applied.

Protocol (backwards compatible; all new fields optional):
- terminal_input / chat_shell_input: reply (emulator answer), cols/rows
  (the typist's size, applied before the input).
- terminal_resize / chat_shell_resize: activate (the client focused it).

Latency: PipelinesClient sends terminal_input, terminal_resize,
chat_shell_input and chat_shell_resize at once rather than behind the
previous request's reply. The server reads those onto a per-connection
terminal lane handled in order beside the ordinary request loop, and
terminal_open (up to 5 s waiting for su) now runs off the read loop.

Client: ChatShellTerminalSession routes what the emulator emits while
drawing output to onReply and reports focus through activate();
ChatShellInputPipe keeps answers and typing in separate requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:37:16 +00:00

279 lines
8.1 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;
}
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;
/// 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;
_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},
});
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;
if (after == null || start > _stream.end) {
_stream.reset(output, start, info.stream);
session.replay(_run());
} else {
_append(output, start, start + _byteLength(output));
}
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) {
// Frames were missed: read the retained tail again.
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();
}
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;
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;