Merge branch 'worktree-agent-ab9de97501bc94a9c'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -127,11 +127,28 @@ class PipelinesClient implements ApiGateway {
|
||||
if (!_states.isClosed) _states.add(value);
|
||||
}
|
||||
|
||||
/// Requests sent at once rather than after the previous request's reply:
|
||||
/// a terminal's keystrokes and sizes. They are written to the socket in
|
||||
/// call order, and the server handles them in arrival order on a lane of
|
||||
/// their own, so they never wait behind a slow request (a terminal_open
|
||||
/// waiting for its login prompt, a chat backend call) and stay in order
|
||||
/// among themselves. An older server handles them in order with the rest.
|
||||
static const pipelined = {
|
||||
'terminal_input',
|
||||
'terminal_resize',
|
||||
'chat_shell_input',
|
||||
'chat_shell_resize',
|
||||
};
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
final completer = Completer<JsonMap>();
|
||||
final generation = _generation;
|
||||
final snapshot = Map<String, dynamic>.of(fields);
|
||||
if (pipelined.contains(type)) {
|
||||
_send(type, snapshot, completer, generation);
|
||||
return completer.future;
|
||||
}
|
||||
final run = _queue.then(
|
||||
(_) => _sendCall(type, snapshot, completer, generation),
|
||||
);
|
||||
@@ -145,6 +162,22 @@ class PipelinesClient implements ApiGateway {
|
||||
Completer<JsonMap> result,
|
||||
int generation,
|
||||
) async {
|
||||
_send(type, fields, result, generation);
|
||||
// Match the existing client's serialized request semantics, even on errors.
|
||||
try {
|
||||
await result.future;
|
||||
} catch (_) {
|
||||
/* The caller receives the error. */
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one request now; [result] completes with its reply.
|
||||
void _send(
|
||||
String type,
|
||||
JsonMap fields,
|
||||
Completer<JsonMap> result,
|
||||
int generation,
|
||||
) {
|
||||
if (generation != _generation) {
|
||||
result.completeError(StateError('Connection replaced'));
|
||||
return;
|
||||
@@ -175,12 +208,6 @@ class PipelinesClient implements ApiGateway {
|
||||
timer.cancel();
|
||||
if (_pending.remove(id) != null) result.completeError(error);
|
||||
}
|
||||
// Match the existing client's serialized request semantics, even on errors.
|
||||
try {
|
||||
await result.future;
|
||||
} catch (_) {
|
||||
/* The caller receives the error. */
|
||||
}
|
||||
}
|
||||
|
||||
String sendOnly(String type, [JsonMap fields = const {}]) {
|
||||
|
||||
@@ -15,6 +15,8 @@ class ChatShellRunsRepository {
|
||||
String? data,
|
||||
int? after,
|
||||
List<String>? runIds,
|
||||
bool reply = false,
|
||||
bool activate = false,
|
||||
}) => {
|
||||
'chat_shell_run_request': {
|
||||
'session_id': sessionId,
|
||||
@@ -25,6 +27,8 @@ class ChatShellRunsRepository {
|
||||
'data': ?data,
|
||||
'after': ?after,
|
||||
'run_ids': ?runIds,
|
||||
if (reply) 'reply': true,
|
||||
if (activate) 'activate': true,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -43,16 +47,40 @@ class ChatShellRunsRepository {
|
||||
);
|
||||
|
||||
/// Writes typed text (control characters and escape sequences included)
|
||||
/// to a running command's terminal.
|
||||
Future<void> input(String sessionId, String runId, String data) => gateway
|
||||
.call('chat_shell_input', _body(sessionId, runId: runId, data: data));
|
||||
/// to a running command's terminal. [reply] marks the emulator's automatic
|
||||
/// answer to a query, which the server passes on only from the terminal's
|
||||
/// active client; typing carries the [size] this client draws it at.
|
||||
Future<void> input(
|
||||
String sessionId,
|
||||
String runId,
|
||||
String data, {
|
||||
bool reply = false,
|
||||
(int, int)? size,
|
||||
}) => gateway.call(
|
||||
'chat_shell_input',
|
||||
_body(
|
||||
sessionId,
|
||||
runId: runId,
|
||||
data: data,
|
||||
reply: reply,
|
||||
cols: size?.$1,
|
||||
rows: size?.$2,
|
||||
),
|
||||
);
|
||||
|
||||
/// Sets a running command's terminal size.
|
||||
Future<void> resize(String sessionId, String runId, int cols, int rows) =>
|
||||
gateway.call(
|
||||
'chat_shell_resize',
|
||||
_body(sessionId, runId: runId, cols: cols, rows: rows),
|
||||
);
|
||||
/// Reports the size this client draws a running command's terminal at;
|
||||
/// [activate] makes it the active client (it focused the terminal), whose
|
||||
/// size the process takes.
|
||||
Future<void> resize(
|
||||
String sessionId,
|
||||
String runId,
|
||||
int cols,
|
||||
int rows, {
|
||||
bool activate = false,
|
||||
}) => gateway.call(
|
||||
'chat_shell_resize',
|
||||
_body(sessionId, runId: runId, cols: cols, rows: rows, activate: activate),
|
||||
);
|
||||
|
||||
Future<void> stop(String sessionId, String runId) =>
|
||||
gateway.call('chat_shell_stop', _body(sessionId, runId: runId));
|
||||
|
||||
@@ -14,11 +14,19 @@ const int chatShellTerminalScrollback = 5000;
|
||||
///
|
||||
/// It keeps no copy of typed input: [Terminal.onOutput] hands each key or
|
||||
/// paste straight to [onInput], which sends it.
|
||||
///
|
||||
/// Several clients may draw one terminal. The emulator's automatic answers
|
||||
/// to queries in the output (cursor position, device attributes) go to
|
||||
/// [onReply] instead, so the server can let only the active client's
|
||||
/// answers through; a view gaining focus calls [activate], which makes this
|
||||
/// client the active one at its size ([onActivate]).
|
||||
class ChatShellTerminalSession {
|
||||
ChatShellTerminalSession(
|
||||
ChatShellRun run, {
|
||||
required this.onInput,
|
||||
required this.onResize,
|
||||
this.onReply,
|
||||
this.onActivate,
|
||||
bool Function()? optionAsMeta,
|
||||
}) : optionAsMeta =
|
||||
optionAsMeta ?? (() => TerminalLayout.instance.optionAsMeta),
|
||||
@@ -30,7 +38,10 @@ class ChatShellTerminalSession {
|
||||
// Drawn at the process's own size until a view lays it out at its own.
|
||||
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
|
||||
terminal.onOutput = _output;
|
||||
terminal.onResize = (cols, rows, _, _) => onResize(cols, rows);
|
||||
terminal.onResize = (cols, rows, _, _) {
|
||||
_viewSize = (cols, rows);
|
||||
onResize(cols, rows);
|
||||
};
|
||||
replay(run);
|
||||
}
|
||||
|
||||
@@ -39,15 +50,25 @@ class ChatShellTerminalSession {
|
||||
/// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal).
|
||||
final bool Function() optionAsMeta;
|
||||
|
||||
/// Receives input for the process; only called while the run is live.
|
||||
/// Receives what the operator types for the process; only called while
|
||||
/// the run is live.
|
||||
final void Function(String data) onInput;
|
||||
|
||||
/// Receives the size the view laid the terminal out at.
|
||||
final void Function(int cols, int rows) onResize;
|
||||
|
||||
/// Receives the emulator's automatic answers to queries in the live
|
||||
/// output; [onInput] receives them when this is null.
|
||||
final void Function(String data)? onReply;
|
||||
|
||||
/// Receives this client's size when a view of it gains focus.
|
||||
final void Function(int cols, int rows)? onActivate;
|
||||
|
||||
int _end = 0;
|
||||
bool _live = false;
|
||||
bool _replaying = false;
|
||||
bool _drawing = false;
|
||||
(int, int)? _viewSize;
|
||||
|
||||
/// The absolute output byte this terminal has drawn up to.
|
||||
int get end => _end;
|
||||
@@ -55,6 +76,16 @@ class ChatShellTerminalSession {
|
||||
/// Whether typing reaches a running process.
|
||||
bool get live => _live;
|
||||
|
||||
/// The size a view last laid the terminal out at; null before any did.
|
||||
(int, int)? get viewSize => _viewSize;
|
||||
|
||||
/// A view of this terminal gained focus: this client becomes the one the
|
||||
/// process is sized for and whose answers it receives.
|
||||
void activate() {
|
||||
final size = _viewSize;
|
||||
if (_live && size != null) onActivate?.call(size.$1, size.$2);
|
||||
}
|
||||
|
||||
/// Draws [run]'s held output from scratch: on open, after a gap and after
|
||||
/// a readback replaced the card's copy. Answers the emulator gives to old
|
||||
/// queries in that output are not sent: the process asked them long ago.
|
||||
@@ -92,7 +123,13 @@ class ChatShellTerminalSession {
|
||||
replay(run);
|
||||
return;
|
||||
}
|
||||
terminal.write(_drawable(run, text));
|
||||
// What the emulator sends while drawing output answers that output.
|
||||
_drawing = true;
|
||||
try {
|
||||
terminal.write(_drawable(run, text));
|
||||
} finally {
|
||||
_drawing = false;
|
||||
}
|
||||
_end = end;
|
||||
}
|
||||
|
||||
@@ -128,7 +165,13 @@ class ChatShellTerminalSession {
|
||||
}
|
||||
|
||||
void _output(String data) {
|
||||
if (_live && !_replaying) onInput(data);
|
||||
if (!_live || _replaying) return;
|
||||
final reply = onReply;
|
||||
if (_drawing && reply != null) {
|
||||
reply(data);
|
||||
} else {
|
||||
onInput(data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain-pipe output has bare newlines, which a terminal draws as a line
|
||||
|
||||
@@ -98,6 +98,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
final ScrollController _scroll = ScrollController();
|
||||
final Map<ShortcutActivator, Intent> _shortcuts =
|
||||
chatShellTerminalShortcuts();
|
||||
bool _focused = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -105,10 +106,20 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
// A paste while the terminal has focus goes to the process, not to the
|
||||
// chat composer.
|
||||
ChatComposerPasteFocus.registerInput(_focus);
|
||||
_focus.addListener(_focusChanged);
|
||||
}
|
||||
|
||||
/// Focusing a terminal makes this client the one it is sized for, the
|
||||
/// way typing in it does.
|
||||
void _focusChanged() {
|
||||
final focused = _focus.hasFocus;
|
||||
if (focused && !_focused) widget.session.activate();
|
||||
_focused = focused;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.removeListener(_focusChanged);
|
||||
ChatComposerPasteFocus.unregisterInput(_focus);
|
||||
_controller.dispose();
|
||||
_focus.dispose();
|
||||
|
||||
@@ -43,7 +43,9 @@ class ChatShellTerminals {
|
||||
() => 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),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -69,17 +71,35 @@ class ChatShellTerminals {
|
||||
_sessions[run.id]?.replay(run);
|
||||
}
|
||||
|
||||
void _input(String runId, String data) {
|
||||
void _input(String runId, String data, {bool reply = false}) {
|
||||
if (_disposed) return;
|
||||
_inputs
|
||||
.putIfAbsent(
|
||||
runId,
|
||||
() => ChatShellInputPipe(
|
||||
(data) => _repository.input(_sessionId, runId, data),
|
||||
(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);
|
||||
.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) {
|
||||
@@ -110,16 +130,25 @@ class ChatShellTerminals {
|
||||
/// 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) _send;
|
||||
final Future<void> Function(String data, bool reply) _send;
|
||||
final void Function(Object error) _failed;
|
||||
final StringBuffer _pending = StringBuffer();
|
||||
|
||||
/// 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) {
|
||||
_pending.write(data);
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -127,19 +156,22 @@ class ChatShellInputPipe {
|
||||
_busy = true;
|
||||
try {
|
||||
while (_pending.isNotEmpty) {
|
||||
var waiting = _pending.toString();
|
||||
_pending.clear();
|
||||
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--;
|
||||
_pending.write(waiting.substring(cut));
|
||||
buffer.write(waiting.substring(cut));
|
||||
} else {
|
||||
_pending.removeAt(0);
|
||||
}
|
||||
final chunk = waiting.substring(0, cut);
|
||||
waiting = '';
|
||||
await _send(chunk);
|
||||
await _send(chunk, reply);
|
||||
}
|
||||
} catch (error) {
|
||||
_pending.clear();
|
||||
|
||||
@@ -26,7 +26,9 @@ class TerminalTab extends ChangeNotifier {
|
||||
session = ChatShellTerminalSession(
|
||||
_run(),
|
||||
onInput: _input,
|
||||
onReply: (data) => _input(data, reply: true),
|
||||
onResize: _resized,
|
||||
onActivate: _activated,
|
||||
);
|
||||
session.terminal.onTitleChange = _titled;
|
||||
}
|
||||
@@ -85,6 +87,10 @@ class TerminalTab extends ChangeNotifier {
|
||||
_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() {
|
||||
@@ -182,19 +188,25 @@ class TerminalTab extends ChangeNotifier {
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _input(String data) {
|
||||
/// 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) => gateway.call('terminal_input', {
|
||||
'terminal_request': {'terminal_id': id, 'data': data},
|
||||
}),
|
||||
(failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
},
|
||||
)).add(data);
|
||||
(_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) {
|
||||
@@ -202,23 +214,40 @@ class TerminalTab extends ChangeNotifier {
|
||||
_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>{};
|
||||
});
|
||||
_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();
|
||||
}
|
||||
|
||||
@@ -120,8 +120,28 @@ data?, after?}`.
|
||||
when the login cannot ask for a password (below).
|
||||
- `terminal_list` → `terminals` (running and ended, oldest first; live
|
||||
records carry their current title, size and `stream`).
|
||||
- `terminal_input {terminal_id, data}` (UTF-8, ≤ 16 KiB, 64-request queue),
|
||||
`terminal_resize {terminal_id, cols, rows}` (clamped 20–500 × 4–200).
|
||||
- `terminal_input {terminal_id, data, reply?, cols?, rows?}` (UTF-8,
|
||||
≤ 16 KiB, 64-request queue), `terminal_resize {terminal_id, cols, rows,
|
||||
activate?}` (clamped 20–500 × 4–200).
|
||||
- **Several clients on one terminal** (`terminal_viewers.go`,
|
||||
`terminal_active.go`; chat terminal commands too): one *active* client
|
||||
owns the PTY size and is the only one whose emulator's automatic answers
|
||||
(`reply: true`: cursor position, device attributes) reach the shell, so
|
||||
a query gets one answer, not one per client. The opener starts active;
|
||||
typing (carrying the typist's `cols`/`rows`, applied before the input)
|
||||
or focusing a terminal view (`terminal_resize` with `activate`) makes a
|
||||
client active. Others' sizes are kept, not applied; when the active
|
||||
connection closes the next most recent client's size is applied. The
|
||||
client marks answers by what the emulator emits while drawing output
|
||||
(`ChatShellTerminalSession.onReply`).
|
||||
- **Input latency**: `PipelinesClient.call` sends `terminal_input`,
|
||||
`terminal_resize`, `chat_shell_input` and `chat_shell_resize` at once
|
||||
instead of behind the previous request's reply; the server reads them
|
||||
onto a per-connection terminal lane (`terminal_lane.go`) handled in
|
||||
order beside the ordinary loop, and `terminal_open` runs off the read
|
||||
loop. `ChatShellInputPipe` still keeps one request in flight per
|
||||
terminal (typing during it is coalesced; answers go in their own
|
||||
requests).
|
||||
- `terminal_output {terminal_id, after}` → `terminal` with `output`,
|
||||
`output_start`, `output_end`, `stream`; subscribes the connection.
|
||||
- `terminal_close {terminal_id}` → the closed record (runs off the read
|
||||
|
||||
@@ -72,6 +72,76 @@ void main() {
|
||||
await client.dispose();
|
||||
});
|
||||
|
||||
test('terminal keystrokes do not wait behind a slow request', () async {
|
||||
final channel = FakeChannel();
|
||||
final client = PipelinesClient(channelFactory: (_) => channel);
|
||||
final connecting = client.connect(Uri.parse('ws://example.test'));
|
||||
channel.readyCompleter.complete();
|
||||
await connecting;
|
||||
Map<String, dynamic> sent(int i) =>
|
||||
jsonDecode(channel.outgoing[i] as String) as Map<String, dynamic>;
|
||||
// A terminal_open waiting for its login prompt.
|
||||
final open = client.call('terminal_open');
|
||||
final later = client.call('terminal_list');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final keys = [
|
||||
for (final data in ['l', 's', '\r'])
|
||||
client.call('terminal_input', {
|
||||
'terminal_request': {'terminal_id': 't', 'data': data},
|
||||
}),
|
||||
];
|
||||
final size = client.call('chat_shell_resize', {
|
||||
'chat_shell_run_request': {'cols': 80, 'rows': 24},
|
||||
});
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
// The keystrokes and the size went out at once, in order; the ordinary
|
||||
// request behind the slow one still waits for it.
|
||||
expect(channel.outgoing, hasLength(5));
|
||||
expect(
|
||||
[for (var i = 0; i < 5; i++) sent(i)['type']],
|
||||
[
|
||||
'terminal_open',
|
||||
'terminal_input',
|
||||
'terminal_input',
|
||||
'terminal_input',
|
||||
'chat_shell_resize',
|
||||
],
|
||||
);
|
||||
expect(
|
||||
[for (var i = 1; i < 4; i++) sent(i)['terminal_request']['data']],
|
||||
['l', 's', '\r'],
|
||||
);
|
||||
for (var i = 1; i < 5; i++) {
|
||||
channel.incoming.add(
|
||||
jsonEncode({'id': sent(i)['id'], 'type': sent(i)['type']}),
|
||||
);
|
||||
}
|
||||
for (final key in keys) {
|
||||
expect((await key)['type'], 'terminal_input');
|
||||
}
|
||||
expect((await size)['type'], 'chat_shell_resize');
|
||||
channel.incoming.add(
|
||||
jsonEncode({'id': sent(0)['id'], 'type': 'terminal_open'}),
|
||||
);
|
||||
expect((await open)['type'], 'terminal_open');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(sent(5)['type'], 'terminal_list');
|
||||
channel.incoming.add(
|
||||
jsonEncode({'id': sent(5)['id'], 'type': 'terminal_list'}),
|
||||
);
|
||||
expect((await later)['type'], 'terminal_list');
|
||||
await client.dispose();
|
||||
});
|
||||
|
||||
test('a keystroke while disconnected fails at once', () async {
|
||||
final client = PipelinesClient(channelFactory: (_) => FakeChannel());
|
||||
await expectLater(
|
||||
client.call('terminal_input', {'terminal_request': {}}),
|
||||
throwsA(isA<NotConnectedError>()),
|
||||
);
|
||||
await client.dispose();
|
||||
});
|
||||
|
||||
test('disconnect fails pending requests', () async {
|
||||
final channel = FakeChannel();
|
||||
final client = PipelinesClient(channelFactory: (_) => channel);
|
||||
|
||||
@@ -67,6 +67,35 @@ void main() {
|
||||
expect(sent, hasLength(2));
|
||||
});
|
||||
|
||||
test('query answers go to onReply; focus reports the laid out size', () {
|
||||
final typed = <String>[];
|
||||
final replies = <String>[];
|
||||
final activations = <(int, int)>[];
|
||||
final session = ChatShellTerminalSession(
|
||||
_run('prompt'),
|
||||
onInput: typed.add,
|
||||
onReply: replies.add,
|
||||
onResize: (_, _) {},
|
||||
onActivate: (cols, rows) => activations.add((cols, rows)),
|
||||
);
|
||||
session.append(_run('prompt\x1b[6n'), '\x1b[6n', 6, 10);
|
||||
session.terminal.textInput('y');
|
||||
expect(replies, ['\x1b[1;7R']);
|
||||
expect(typed, ['y']);
|
||||
// Drawn at the run's own size until a view lays it out.
|
||||
expect(session.viewSize, isNull);
|
||||
session.activate();
|
||||
expect(activations, isEmpty);
|
||||
session.terminal.resize(90, 20);
|
||||
expect(session.viewSize, (90, 20));
|
||||
session.activate();
|
||||
expect(activations, [(90, 20)]);
|
||||
// A finished run claims nothing.
|
||||
session.finish(_run('prompt', status: 'exited'));
|
||||
session.activate();
|
||||
expect(activations, hasLength(1));
|
||||
});
|
||||
|
||||
test('a chunk after a hole redraws the held copy', () {
|
||||
final session = ChatShellTerminalSession(
|
||||
_run('a\r\n'),
|
||||
|
||||
@@ -377,6 +377,47 @@ void main() {
|
||||
expect(gateway.bodies('chat_shell_input'), isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('focusing the terminal claims it at its size; typing carries '
|
||||
'the size and query answers are marked', (tester) async {
|
||||
await openRunning(tester, output: 'size? \x1b[6n');
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
final laidOut = gateway.bodies('chat_shell_resize').single;
|
||||
// The replayed query is not answered; nothing was claimed yet.
|
||||
expect(gateway.bodies('chat_shell_input'), isEmpty);
|
||||
await tester.tap(find.byType(TerminalView));
|
||||
await tester.pump();
|
||||
final claim = gateway.bodies('chat_shell_resize').last;
|
||||
expect(claim['activate'], isTrue);
|
||||
expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows']));
|
||||
// Typing carries this client's size.
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
|
||||
await tester.pump();
|
||||
var inputs = gateway.bodies('chat_shell_input');
|
||||
expect(inputs.single['data'], 'g');
|
||||
expect(inputs.single['reply'], isNull);
|
||||
expect(
|
||||
(inputs.single['cols'], inputs.single['rows']),
|
||||
(laidOut['cols'], laidOut['rows']),
|
||||
);
|
||||
// A live query is answered with the answer marked, without a size.
|
||||
gateway.emitOutput('run_t', '\x1b[6n', 'size? \x1b[6n'.length);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
inputs = gateway.bodies('chat_shell_input');
|
||||
expect(inputs.last['data'], '\x1b[1;7R');
|
||||
expect(inputs.last['reply'], isTrue);
|
||||
expect(inputs.last['cols'], isNull);
|
||||
// Focusing again after the focus left claims again.
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
await tester.pump();
|
||||
await tester.tap(find.byType(TerminalView));
|
||||
await tester.pump();
|
||||
expect(
|
||||
gateway.bodies('chat_shell_resize').where((b) => b['activate'] == true),
|
||||
hasLength(2),
|
||||
);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
|
||||
|
||||
testWidgets('coloured output is drawn without its escape codes', (
|
||||
tester,
|
||||
) async {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/shell/chat_shell_terminals.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_info.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('answers are marked, typing carries the size, focus activates', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = TerminalGateway();
|
||||
final tab = TerminalTab(
|
||||
machineId: 'm',
|
||||
machineName: 'm',
|
||||
gateway: gateway,
|
||||
info: TerminalInfo.fromJson(gateway.add('t1')),
|
||||
);
|
||||
// Before a view lays it out, focus has no size to claim.
|
||||
tab.session.activate();
|
||||
await tester.pump();
|
||||
expect(gateway.bodies('terminal_resize'), isEmpty);
|
||||
|
||||
tab.session.terminal.resize(100, 30);
|
||||
await tester.pump(chatShellResizeDelay);
|
||||
expect(gateway.bodies('terminal_resize'), [
|
||||
{'terminal_id': 't1', 'cols': 100, 'rows': 30},
|
||||
]);
|
||||
|
||||
// A cursor position query in the output: the answer is marked.
|
||||
tab.frame({'output': '\x1b[6n', 'offset': 0, 'end': 4});
|
||||
await tester.pump();
|
||||
// Typing carries the size this client draws at.
|
||||
tab.session.terminal.textInput('ls');
|
||||
await tester.pump();
|
||||
expect(gateway.bodies('terminal_input'), [
|
||||
{'terminal_id': 't1', 'data': '\x1b[1;1R', 'reply': true},
|
||||
{'terminal_id': 't1', 'data': 'ls', 'cols': 100, 'rows': 30},
|
||||
]);
|
||||
|
||||
// A view gaining focus claims the terminal at once, at its size.
|
||||
tab.session.activate();
|
||||
await tester.pump();
|
||||
expect(gateway.bodies('terminal_resize').last, {
|
||||
'terminal_id': 't1',
|
||||
'cols': 100,
|
||||
'rows': 30,
|
||||
'activate': true,
|
||||
});
|
||||
|
||||
// A new connection reports its size again.
|
||||
tab.attach(gateway, TerminalInfo.fromJson(gateway.terminals['t1']!));
|
||||
await tester.pump(chatShellResizeDelay);
|
||||
expect(gateway.bodies('terminal_resize'), hasLength(3));
|
||||
expect(gateway.bodies('terminal_resize').last, {
|
||||
'terminal_id': 't1',
|
||||
'cols': 100,
|
||||
'rows': 30,
|
||||
});
|
||||
tab.dispose();
|
||||
});
|
||||
|
||||
test('the input pipe keeps answers and typing apart, in order', () async {
|
||||
final sent = <(String, bool)>[];
|
||||
final pipe = ChatShellInputPipe((data, reply) async {
|
||||
sent.add((data, reply));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}, (_) {});
|
||||
pipe.add('a');
|
||||
// While the first is in flight, typing, an answer and typing wait.
|
||||
pipe.add('b');
|
||||
pipe.add('c');
|
||||
pipe.add('\x1b[1;1R', reply: true);
|
||||
pipe.add('d');
|
||||
pipe.add('${'x' * chatShellInputChunk}y');
|
||||
await pumpEventQueue();
|
||||
expect(sent, [
|
||||
('a', false),
|
||||
('bc', false),
|
||||
('\x1b[1;1R', true),
|
||||
('d${'x' * (chatShellInputChunk - 1)}', false),
|
||||
('xy', false),
|
||||
]);
|
||||
});
|
||||
|
||||
test('a refusal drops what was waiting and reports once', () async {
|
||||
final failures = <Object>[];
|
||||
final sent = <String>[];
|
||||
final pipe = ChatShellInputPipe((data, reply) async {
|
||||
sent.add(data);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
throw StateError('not running');
|
||||
}, failures.add);
|
||||
pipe.add('a');
|
||||
pipe.add('b');
|
||||
pipe.add('?', reply: true);
|
||||
await pumpEventQueue();
|
||||
expect(sent, ['a']);
|
||||
expect(failures, hasLength(1));
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user