Files
pipelines/app/lib/features/chat/shell/chat_shell_terminals.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

184 lines
6.0 KiB
Dart

import 'dart:async';
import 'chat_shell_run.dart';
import 'chat_shell_runs_repository.dart';
import 'chat_shell_terminal_session.dart';
/// UTF-16 units of typed or pasted text one `chat_shell_input` carries: at
/// most 12 KiB of UTF-8, inside the server's 16 KiB bound.
const int chatShellInputChunk = 4096;
/// How long a view's size settles before the process is resized.
const Duration chatShellResizeDelay = Duration(milliseconds: 150);
/// The terminal emulators of one chat's runs, kept outside the cards so a
/// card scrolled out of the transcript (or opened full screen) draws the same
/// state, and the delivery of typed input and sizes to the server.
class ChatShellTerminals {
ChatShellTerminals(
this._repository,
this._sessionId, {
required this.onError,
});
final ChatShellRunsRepository _repository;
final String _sessionId;
/// Reports a refused input or resize of a run, in the server's words.
final void Function(String runId, Object error) onError;
final Map<String, ChatShellTerminalSession> _sessions = {};
final Map<String, ChatShellInputPipe> _inputs = {};
final Map<String, Timer> _resizes = {};
final Map<String, (int, int)> _sentSizes = {};
bool _disposed = false;
/// The size a view last laid a terminal out at: new runs start at it, so
/// their first output already fits the reading column.
(int, int)? lastSize;
/// The emulator of [run], created (and fed its held output) on first use.
ChatShellTerminalSession session(ChatShellRun run) => _sessions.putIfAbsent(
run.id,
() => ChatShellTerminalSession(
run,
onInput: (data) => _input(run.id, data),
onReply: (data) => _input(run.id, data, reply: true),
onResize: (cols, rows) => _resized(run.id, cols, rows),
onActivate: (cols, rows) => _activated(run.id, cols, rows),
),
);
/// The card's copy of [run] was replaced (readback, gap): redraw it.
void replaced(ChatShellRun run) => _sessions[run.id]?.replay(run);
/// [run] now holds one more live chunk.
void appended(ChatShellRun run, String text, int offset, int end) =>
_sessions[run.id]?.append(run, text, offset, end);
/// [runId]'s card was dismissed: drop its emulator.
void removed(String runId) {
_resizes.remove(runId)?.cancel();
_inputs.remove(runId);
_sentSizes.remove(runId);
_sessions.remove(runId);
}
/// [run] ended: draw its final output read-only.
void finished(ChatShellRun run) {
_resizes.remove(run.id)?.cancel();
_inputs.remove(run.id);
_sessions[run.id]?.replay(run);
}
void _input(String runId, String data, {bool reply = false}) {
if (_disposed) return;
_inputs
.putIfAbsent(
runId,
() => ChatShellInputPipe(
(data, reply) => _repository.input(
_sessionId,
runId,
data,
reply: reply,
// Typing makes this client the active one at its size.
size: reply ? null : _sessions[runId]?.viewSize,
),
(error) => onError(runId, error),
),
)
.add(data, reply: reply);
}
/// A view of [runId] gained focus: it becomes the active client and the
/// process takes its size at once.
void _activated(String runId, int cols, int rows) {
if (_disposed || !(_sessions[runId]?.live ?? false)) return;
_resizes.remove(runId)?.cancel();
_sentSizes[runId] = (cols, rows);
_repository
.resize(_sessionId, runId, cols, rows, activate: true)
.catchError((Object error) => onError(runId, error));
}
void _resized(String runId, int cols, int rows) {
lastSize = (cols, rows);
if (_disposed || !(_sessions[runId]?.live ?? false)) return;
_resizes.remove(runId)?.cancel();
_resizes[runId] = Timer(chatShellResizeDelay, () {
_resizes.remove(runId);
if (_sentSizes[runId] == (cols, rows)) return;
_sentSizes[runId] = (cols, rows);
_repository
.resize(_sessionId, runId, cols, rows)
.catchError((Object error) => onError(runId, error));
});
}
void dispose() {
_disposed = true;
for (final timer in _resizes.values) {
timer.cancel();
}
_resizes.clear();
_inputs.clear();
}
}
/// One terminal's typed input on its way to the server (a chat run's or a
/// machine terminal's), in order: what arrives
/// while a request is in flight goes in the next one. Nothing is kept once
/// sent, and a refusal discards what was waiting rather than retyping it.
///
/// The emulator's automatic answers ([add] with reply) travel in requests
/// of their own, marked so, never merged with typing on either side.
class ChatShellInputPipe {
ChatShellInputPipe(this._send, this._failed);
final Future<void> Function(String data, bool reply) _send;
final void Function(Object error) _failed;
/// Waiting text in order, each run of typing or of answers in one buffer.
final List<(StringBuffer, bool)> _pending = [];
bool _busy = false;
void add(String data, {bool reply = false}) {
if (data.isEmpty) return;
if (_pending.isEmpty || _pending.last.$2 != reply) {
_pending.add((StringBuffer(), reply));
}
_pending.last.$1.write(data);
if (!_busy) unawaited(_pump());
}
Future<void> _pump() async {
_busy = true;
try {
while (_pending.isNotEmpty) {
final (buffer, reply) = _pending.first;
var waiting = buffer.toString();
buffer.clear();
var cut = waiting.length;
if (cut > chatShellInputChunk) {
cut = chatShellInputChunk;
// Never split a surrogate pair across two requests.
final unit = waiting.codeUnitAt(cut - 1);
if (unit >= 0xD800 && unit <= 0xDBFF) cut--;
buffer.write(waiting.substring(cut));
} else {
_pending.removeAt(0);
}
final chunk = waiting.substring(0, cut);
waiting = '';
await _send(chunk, reply);
}
} catch (error) {
_pending.clear();
_failed(error);
} finally {
_busy = false;
}
}
}