diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 8585f162..576b81d1 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -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 call(String type, [JsonMap fields = const {}]) { final completer = Completer(); final generation = _generation; final snapshot = Map.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 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 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 {}]) { diff --git a/app/lib/features/chat/shell/chat_shell_runs_repository.dart b/app/lib/features/chat/shell/chat_shell_runs_repository.dart index 5297c9be..3cce000d 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_repository.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_repository.dart @@ -15,6 +15,8 @@ class ChatShellRunsRepository { String? data, int? after, List? 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 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 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 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 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 stop(String sessionId, String runId) => gateway.call('chat_shell_stop', _body(sessionId, runId: runId)); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index b8cf5901..057483fe 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -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 diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index dad810eb..2dfc70c9 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -98,6 +98,7 @@ class _ChatShellTerminalViewState extends State { final ScrollController _scroll = ScrollController(); final Map _shortcuts = chatShellTerminalShortcuts(); + bool _focused = false; @override void initState() { @@ -105,10 +106,20 @@ class _ChatShellTerminalViewState extends State { // 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(); diff --git a/app/lib/features/chat/shell/chat_shell_terminals.dart b/app/lib/features/chat/shell/chat_shell_terminals.dart index 5ccb805b..fc40e233 100644 --- a/app/lib/features/chat/shell/chat_shell_terminals.dart +++ b/app/lib/features/chat/shell/chat_shell_terminals.dart @@ -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 Function(String data) _send; + final Future 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(); diff --git a/app/lib/features/terminal/terminal_tab.dart b/app/lib/features/terminal/terminal_tab.dart index 61b571c9..c2ca4004 100644 --- a/app/lib/features/terminal/terminal_tab.dart +++ b/app/lib/features/terminal/terminal_tab.dart @@ -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 {}; - }); + _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 {}; + }); + } + + void _failed(Object failure) { + error = '$failure'; + _notify(); + } + void _notify() { if (!_disposed) notifyListeners(); } diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index f61e21b0..07ac02f8 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -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 diff --git a/app/test/core/transport/pipelines_client_test.dart b/app/test/core/transport/pipelines_client_test.dart index e71b78f6..084c22fb 100644 --- a/app/test/core/transport/pipelines_client_test.dart +++ b/app/test/core/transport/pipelines_client_test.dart @@ -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 sent(int i) => + jsonDecode(channel.outgoing[i] as String) as Map; + // A terminal_open waiting for its login prompt. + final open = client.call('terminal_open'); + final later = client.call('terminal_list'); + await Future.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.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.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()), + ); + await client.dispose(); + }); + test('disconnect fails pending requests', () async { final channel = FakeChannel(); final client = PipelinesClient(channelFactory: (_) => channel); diff --git a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart index 55a1a335..d721616b 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart @@ -67,6 +67,35 @@ void main() { expect(sent, hasLength(2)); }); + test('query answers go to onReply; focus reports the laid out size', () { + final typed = []; + final replies = []; + 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'), diff --git a/app/test/features/chat/shell/chat_shell_terminal_test.dart b/app/test/features/chat/shell/chat_shell_terminal_test.dart index db5a9644..b6e6fd1c 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_test.dart @@ -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 { diff --git a/app/test/features/terminal/terminal_active_client_test.dart b/app/test/features/terminal/terminal_active_client_test.dart new file mode 100644 index 00000000..ec9af476 --- /dev/null +++ b/app/test/features/terminal/terminal_active_client_test.dart @@ -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.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 = []; + final sent = []; + final pipe = ChatShellInputPipe((data, reply) async { + sent.add(data); + await Future.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)); + }); +} diff --git a/docs/cli.md b/docs/cli.md index 2570615b..c649953b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1315,8 +1315,18 @@ app's terminal panel). Every request carries `terminal_request` pipelines`), never the operator's tmux. At most 8 running terminals per machine. - `terminal_list` replies with `terminals` (running and ended, oldest first). -- `terminal_input {terminal_id, data}` writes UTF-8 input (at most 16 KiB); - `terminal_resize {terminal_id, cols, rows}` resizes. Neither is logged. +- `terminal_input {terminal_id, data, reply?, cols?, rows?}` writes UTF-8 + input (at most 16 KiB); `terminal_resize {terminal_id, cols, rows, + activate?}` reports the size a client draws at. Neither is logged. With + several clients on one terminal, the *active* client (the opener, then + whichever most recently typed or sent `activate`, i.e. focused it) owns + the terminal's size, and only its emulator's automatic query answers + (`reply: true`) reach the shell; others' are acknowledged and dropped. + Typed input may carry the sender's `cols`/`rows`, applied first. When the + active connection closes, the next most recent client's size is applied. + `chat_shell_input`/`chat_shell_resize` follow the same rules. Input and + resize requests are handled on a lane of their own per connection, in + order, never behind a slow request read before them. - `terminal_output {terminal_id, after}` replies with the retained output (1 MiB tail) from byte `after` of the stream named `stream`. Opening or reading subscribes the connection to the terminal's output frames. diff --git a/internal/protocol/chat_shell_run.go b/internal/protocol/chat_shell_run.go index 90ae515d..88a93fb4 100644 --- a/internal/protocol/chat_shell_run.go +++ b/internal/protocol/chat_shell_run.go @@ -65,7 +65,8 @@ const ( // ChatShellRunRequest names one session and either a new command or a run. // OperationID is the optional retry identity of chat_shell_share's prompt. // Cols and Rows size a new run's terminal (chat_shell_run) or resize a running -// one (chat_shell_resize); Data is chat_shell_input's typed text; After is +// one (chat_shell_resize) and may accompany typed chat_shell_input (the size +// its client draws at); Data is chat_shell_input's typed text; After is // chat_shell_run_output's resume offset. type ChatShellRunRequest struct { SessionID string `json:"session_id"` @@ -78,6 +79,11 @@ type ChatShellRunRequest struct { After int64 `json:"after,omitempty"` // RunIDs names the runs of chat_shell_dismiss and chat_shell_restore. RunIDs []string `json:"run_ids,omitempty"` + // Reply marks chat_shell_input as an automatic answer of the client's + // emulator; Activate marks chat_shell_resize as the client focusing the + // terminal (see ChatShellInput and ChatShellResize). + Reply bool `json:"reply,omitempty"` + Activate bool `json:"activate,omitempty"` } // ChatShellRunRecord is one operator command and what it produced. Output is diff --git a/internal/protocol/chat_shell_terminal.go b/internal/protocol/chat_shell_terminal.go index 5e82c527..1b92c76d 100644 --- a/internal/protocol/chat_shell_terminal.go +++ b/internal/protocol/chat_shell_terminal.go @@ -13,10 +13,24 @@ const ( // (Ctrl-C is "\u0003", Enter is "\r", arrow keys are their escape // sequences); the bytes written are exactly its UTF-8 encoding. Input is // never persisted or logged; the reply carries no body. + // + // Several clients may draw one terminal; the one that most recently typed + // or focused it (marked activate on a resize), or else the first to + // attach, is its active client. Reply marks Data + // as the client emulator's automatic answer to a terminal query (cursor + // position, device attributes) rather than typing: it reaches the process + // only from the active client and is otherwise acknowledged and dropped, + // so a query gets one answer. Typed input makes its client active; it may + // carry Cols and Rows, the size that client draws at, which the terminal + // then takes before the input is written. ChatShellInput = "chat_shell_input" - // ChatShellResize sets a running terminal command's size (cols, rows); the - // process receives SIGWINCH. The last resize from any client wins. The - // reply echoes the run. + // ChatShellResize reports the size (cols, rows) a client draws a running + // terminal command at. The terminal takes the active client's size (the + // process receives SIGWINCH); a resize marked activate makes its client + // the active one (it focused the terminal). When the active client's + // connection closes, the next most recently active client's last size is + // applied. A client that does not set the fields behaves as before: its + // typing makes it active. The reply echoes the run with the size applied. ChatShellResize = "chat_shell_resize" ) diff --git a/internal/protocol/terminal.go b/internal/protocol/terminal.go index 70da0950..e330483c 100644 --- a/internal/protocol/terminal.go +++ b/internal/protocol/terminal.go @@ -20,10 +20,15 @@ const ( // oldest first, without output. The body is optional. TerminalList = "terminal_list" // TerminalInput writes Data (UTF-8, control characters included, at most - // ChatShellInputLimit bytes) to a running terminal. No reply body. + // ChatShellInputLimit bytes) to a running terminal. No reply body. Reply + // marks an automatic answer of the client's emulator, which reaches the + // terminal only from its active client; typed input may carry the size + // (cols, rows) the client draws at (as chat_shell_input). TerminalInput = "terminal_input" - // TerminalResize sets a running terminal's size (cols, rows); the reply - // echoes the terminal. + // TerminalResize reports the size (cols, rows) a client draws a running + // terminal at; the terminal takes its active client's size, and Activate + // makes the sender active (as chat_shell_resize). The opener of a + // terminal is its first active client. The reply echoes the terminal. TerminalResize = "terminal_resize" // TerminalOutput reads one terminal with its retained output from the // absolute byte After on (all of it when After precedes the retained @@ -68,6 +73,9 @@ type TerminalRequest struct { Rows int `json:"rows,omitempty"` Data string `json:"data,omitempty"` After int64 `json:"after,omitempty"` + // Reply (terminal_input) and Activate (terminal_resize): see above. + Reply bool `json:"reply,omitempty"` + Activate bool `json:"activate,omitempty"` } // TerminalRecord is one terminal. Output and OutputStart are set only on diff --git a/internal/server/chat_shell_run_handlers.go b/internal/server/chat_shell_run_handlers.go index 6abab624..19c1c34f 100644 --- a/internal/server/chat_shell_run_handlers.go +++ b/internal/server/chat_shell_run_handlers.go @@ -56,6 +56,7 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br fail(err) return } + runner.attachViewer(clientID, sessionID, record.ID, record.Cols, record.Rows) _ = write(protocol.Message{Type: protocol.ChatShellRun, ID: request.ID, ChatShellRun: &record}) case protocol.ChatShellStop: record, err := runner.Stop(sessionID, body.RunID) @@ -92,13 +93,13 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br } _ = write(protocol.Message{Type: protocol.ChatShellRestore, ID: request.ID, ChatShellRuns: runs}) case protocol.ChatShellInput: - if err := runner.Input(sessionID, body.RunID, body.Data); err != nil { + if err := runner.ClientInput(clientID, sessionID, body.RunID, body.Data, body.Reply, body.Cols, body.Rows); err != nil { fail(err) return } _ = write(protocol.Message{Type: protocol.ChatShellInput, ID: request.ID}) case protocol.ChatShellResize: - record, err := runner.Resize(sessionID, body.RunID, body.Cols, body.Rows) + record, err := runner.ClientResize(clientID, sessionID, body.RunID, body.Cols, body.Rows, body.Activate) if err != nil { fail(err) return diff --git a/internal/server/chat_shell_runner.go b/internal/server/chat_shell_runner.go index 1de83da0..abf72ad6 100644 --- a/internal/server/chat_shell_runner.go +++ b/internal/server/chat_shell_runner.go @@ -66,6 +66,8 @@ type chatShellProcess struct { // input feeds it in order (chat_shell_terminal.go). terminal *os.File input chan []byte + // viewers are the connections drawing the terminal (terminal_viewers.go). + viewers terminalViewers // closed is set once the reader is closed; a read still blocked on a // terminal a descendant holds open records nothing after it. closed bool diff --git a/internal/server/chat_shell_terminal_ws_test.go b/internal/server/chat_shell_terminal_ws_test.go index cf241f2a..afd71235 100644 --- a/internal/server/chat_shell_terminal_ws_test.go +++ b/internal/server/chat_shell_terminal_ws_test.go @@ -37,7 +37,9 @@ func TestChatShellTerminalOverWebsocket(t *testing.T) { resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "") resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33 writeChat(t, ctx, conns[1], resize) - if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 120 { + // The starter stays the active client until the watcher types: then the + // watcher's size applies (stty size below). + if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 80 { t.Fatalf("resize reply = %+v", got) } input := shellRequest(protocol.ChatShellInput, "in", run.ID, "") diff --git a/internal/server/terminal_active.go b/internal/server/terminal_active.go new file mode 100644 index 00000000..c1f4e382 --- /dev/null +++ b/internal/server/terminal_active.go @@ -0,0 +1,160 @@ +package server + +import ( + "errors" + "log" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// The active-client policy (terminal_viewers.go) applied to machine +// terminals and to chats' terminal commands: requests name their +// connection, and a connection that closes hands the terminal to the next. + +// ClientInput is Input from clientID: typing makes it the active client +// (its size, cols x rows when it sent one, else its last, is applied +// first); an automatic reply (reply) from any other client is acknowledged +// and dropped. +func (m *terminalManager) ClientInput(clientID, id, data string, reply bool, cols, rows int) error { + if p := m.process(id); p != nil && p.running() { + if reply && !p.viewers.answers(clientID) { + return nil + } + if !reply { + if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) { + if err := p.applySize(size.cols, size.rows); err != nil { + log.Printf("terminal %s resize: %v", id, err) + } + } + } + } + return m.Input(id, data) +} + +// ClientResize records the size clientID draws terminal id at and applies +// it when clientID is (or, with activate, becomes) the active client. The +// record carries the size the terminal has. +func (m *terminalManager) ClientResize(clientID, id string, cols, rows int, activate bool) (protocol.TerminalRecord, error) { + if cols <= 0 || rows <= 0 { + return protocol.TerminalRecord{}, errors.New("positive cols and rows are required") + } + p, err := m.live(id) + if err != nil { + return protocol.TerminalRecord{}, err + } + if size := p.viewers.resize(clientID, cols, rows, activate); size.ok { + return m.Resize(id, size.cols, size.rows) + } + return p.snapshot(false, 0), nil +} + +// attachViewer records clientID as drawing terminal id (it read it). +func (m *terminalManager) attachViewer(clientID, id string) { + if p := m.process(id); p != nil { + p.viewers.attach(clientID) + } +} + +// detach drops clientID's connection: its output frames, and its part in +// every terminal it drew; a terminal it was active in takes the next +// client's size. +func (m *terminalManager) detach(clientID string) { + m.clients.detach(clientID) + m.mu.Lock() + terms := make(map[string]*terminalProcess, len(m.terms)) + for id, p := range m.terms { + terms[id] = p + } + m.mu.Unlock() + for id, p := range terms { + if size := p.viewers.leave(clientID); size.ok && p.running() { + if err := p.applySize(size.cols, size.rows); err != nil { + log.Printf("terminal %s resize: %v", id, err) + } + } + } +} + +// ClientInput is Input from clientID, under the same policy as the machine +// terminals' ClientInput. +func (r *chatShellRunner) ClientInput(clientID, sessionID, runID, data string, reply bool, cols, rows int) error { + if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil { + if reply && !p.viewers.answers(clientID) { + return nil + } + if !reply { + if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) { + if _, err := r.Resize(sessionID, runID, size.cols, size.rows); err != nil { + log.Printf("chat shell %s resize: %v", runID, err) + } + } + } + } + return r.Input(sessionID, runID, data) +} + +// ClientResize is Resize from clientID, applied only when it is (or, with +// activate, becomes) the active client. +func (r *chatShellRunner) ClientResize(clientID, sessionID, runID string, cols, rows int, activate bool) (protocol.ChatShellRunRecord, error) { + if cols <= 0 || rows <= 0 { + return protocol.ChatShellRunRecord{}, errors.New("positive cols and rows are required") + } + p, err := r.terminalProcess(sessionID, runID) + if err != nil { + return protocol.ChatShellRunRecord{}, err + } + if size := p.viewers.resize(clientID, cols, rows, activate); size.ok { + return r.Resize(sessionID, runID, size.cols, size.rows) + } + p.mu.Lock() + defer p.mu.Unlock() + return p.record, nil +} + +// attachViewer makes clientID, which started runID at cols x rows, its +// active client. +func (r *chatShellRunner) attachViewer(clientID, sessionID, runID string, cols, rows int) { + if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil && cols > 0 && rows > 0 { + p.viewers.resize(clientID, cols, rows, true) + } +} + +// leave drops clientID's part in every running terminal command it drew. +func (r *chatShellRunner) leave(clientID string) { + if r == nil { + return + } + type run struct{ sessionID, runID string } + r.mu.Lock() + procs := make(map[run]*chatShellProcess, len(r.active)) + for id, p := range r.active { + procs[run{p.record.SessionID, id}] = p + } + r.mu.Unlock() + for key, p := range procs { + if p.terminal == nil { + continue + } + if size := p.viewers.leave(clientID); size.ok { + if _, err := r.Resize(key.sessionID, key.runID, size.cols, size.rows); err != nil { + log.Printf("chat shell %s resize: %v", key.runID, err) + } + } + } +} + +// sized reports whether the terminal already has size (clamped). +func (p *terminalProcess) sized(size terminalSize) bool { + cols, rows := chatShellTerminalSize(size.cols, size.rows) + p.mu.Lock() + defer p.mu.Unlock() + return p.record.Cols == cols && p.record.Rows == rows +} + +// sized reports whether the terminal command already has size (clamped). +func (p *chatShellProcess) sized(size terminalSize) bool { + cols, rows := chatShellTerminalSize(size.cols, size.rows) + p.mu.Lock() + defer p.mu.Unlock() + return p.record.Cols == cols && p.record.Rows == rows +} diff --git a/internal/server/terminal_active_test.go b/internal/server/terminal_active_test.go new file mode 100644 index 00000000..ce00ccc8 --- /dev/null +++ b/internal/server/terminal_active_test.go @@ -0,0 +1,189 @@ +//go:build darwin || linux + +package server + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/coder/websocket" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// readTerminalText reads conn's output frames of id, from wherever its +// subscription started, until the text contains want. +func readTerminalText(t *testing.T, ctx context.Context, conn *websocket.Conn, id, want string) string { + t.Helper() + var seen strings.Builder + for !strings.Contains(seen.String(), want) { + seen.WriteString(readShellFrame(t, ctx, conn, func(m protocol.Message) bool { + return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil + }).TerminalEvent.Output) + } + return seen.String() +} + +// Two clients draw one terminal: only the active client's emulator answers +// reach the shell, the terminal takes the active client's size, typing or +// focusing makes a client active, and when the active client leaves the +// next one's size comes back. +func TestTerminalTwoClientsActiveClient(t *testing.T) { + terminalHome(t) + ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2) + a, b := conns[0], conns[1] + term := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 156, Rows: 37})).Terminal + terminalLogIn(t, ctx, a, term.ID) + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalOutput, "read", protocol.TerminalRequest{TerminalID: term.ID})) + // b draws it smaller; the opener is active and keeps its size. + if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalResize, "small", protocol.TerminalRequest{TerminalID: term.ID, Cols: 121, Rows: 11})); got.Terminal == nil || got.Terminal.Cols != 156 || got.Terminal.Rows != 37 { + t.Fatalf("background resize = %+v", got) + } + // A query both emulators answer: only the active client's answer arrives. + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "ask", protocol.TerminalRequest{TerminalID: term.ID, Data: "read -r ans; echo got:$ans; stty size\r"})) + if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "b-answer\r", Reply: true})); got.Type != protocol.TerminalInput { + t.Fatalf("dropped reply is acknowledged: %+v", got) + } + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "a-answer\r", Reply: true})) + text := readTerminalText(t, ctx, a, term.ID, "37 156") + if !strings.Contains(text, "got:a-answer") || strings.Contains(text, "b-answer") { + t.Fatalf("output = %q", text) + } + // b types: it becomes active at its own size, before its keystrokes. + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) + readTerminalText(t, ctx, a, term.ID, "11 121") + // Now a's answers are the ones dropped. + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-late", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo a-late-$((1+1))\r", Reply: true})) + // a focuses its terminal: active again at its size. + if got := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalResize, "focus", protocol.TerminalRequest{TerminalID: term.ID, Cols: 150, Rows: 40, Activate: true})); got.Terminal.Cols != 150 || got.Terminal.Rows != 40 { + t.Fatalf("activate = %+v", got) + } + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) + if text := readTerminalText(t, ctx, a, term.ID, "40 150"); strings.Contains(text, "a-late-2") { + t.Fatalf("a background answer reached the shell: %q", text) + } + // a leaves: b, the next most recent, has its size back. + a.Close(websocket.StatusNormalClosure, "") + deadline := time.Now().Add(5 * time.Second) + for { + list := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{})) + if len(list.Terminals) == 1 && list.Terminals[0].Cols == 121 && list.Terminals[0].Rows == 11 { + break + } + if time.Now().After(deadline) { + t.Fatalf("size after the active client left = %+v", list.Terminals) + } + time.Sleep(20 * time.Millisecond) + } + // And b's emulator answers now reach the shell. + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-answers", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r", Reply: true})) + readTerminalText(t, ctx, b, term.ID, "11 121") +} + +// A chat's terminal command watched by two clients follows the same policy. +func TestChatShellTerminalTwoClientsActiveClient(t *testing.T) { + ctx, conns, _ := shellChat(t) + a, b := conns[0], conns[1] + start := shellRequest(protocol.ChatShellRun, "r1", "", `read -r first; echo got:$first; read -r second; stty size; echo done`) + start.ChatShellRunRequest.Cols, start.ChatShellRunRequest.Rows = 100, 30 + writeChat(t, ctx, a, start) + run := readShellFrame(t, ctx, a, func(m protocol.Message) bool { return m.ID == "r1" }).ChatShellRun + resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "") + resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33 + writeChat(t, ctx, b, resize) + if got := readShellFrame(t, ctx, b, func(m protocol.Message) bool { return m.ID == "size" }); got.ChatShellRun == nil || got.ChatShellRun.Cols != 100 { + t.Fatalf("background resize = %+v", got) + } + send := func(conn *websocket.Conn, id, data string, reply bool, cols, rows int) { + t.Helper() + input := shellRequest(protocol.ChatShellInput, id, run.ID, "") + input.ChatShellRunRequest.Data, input.ChatShellRunRequest.Reply = data, reply + input.ChatShellRunRequest.Cols, input.ChatShellRunRequest.Rows = cols, rows + writeChat(t, ctx, conn, input) + if got := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == id }); got.Type != protocol.ChatShellInput { + t.Fatalf("input %s = %+v", id, got) + } + } + send(b, "b-reply", "b-answer\r", true, 0, 0) + send(a, "a-reply", "a-answer\r", true, 0, 0) + // b types the second line carrying the size it now draws at: it becomes + // active at that size before the keystrokes are written. + send(b, "b-type", "next\r", false, 90, 20) + _, output := finishedShell(t, ctx, a, run.ID) + if !strings.Contains(output, "got:a-answer") || strings.Contains(output, "b-answer") || !strings.Contains(output, "20 90") { + t.Fatalf("output = %q", output) + } +} + +// Keystrokes take their own lane: they are answered, in order, while an +// ordinary request on the same connection is still being handled. +func TestTerminalInputDoesNotWaitBehindSlowRequest(t *testing.T) { + store := newOperatorStore(t) + gate := make(chan struct{}) + broker := scriptedChat() + broker.block = true + broker.createGate, broker.createStarted = gate, make(chan struct{}) + ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 1) + conn := conns[0] + dir := t.TempDir() + if err := store.RecordOperatorSession(ctx, "ses_1", dir, "Shell", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}) + readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == "sub" }) + run := runShell(t, ctx, conn, "r1", `for i in $(seq 1 40); do read -r line; echo "seen:$line"; done`) + defer close(gate) + writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "slow", ChatCreate: &protocol.ChatCreateRequest{Title: "slow", Directory: dir, OperationID: "slow-op"}}) + select { + case <-broker.createStarted: + case <-time.After(5 * time.Second): + t.Fatal("chat_create never reached the broker") + } + // Forty keystroke requests, written without waiting for replies. + started := time.Now() + for i := 1; i <= 40; i++ { + input := shellRequest(protocol.ChatShellInput, fmt.Sprintf("in-%d", i), run.ID, "") + input.ChatShellRunRequest.Data = fmt.Sprintf("k%02d\r", i) + writeChat(t, ctx, conn, input) + } + var output strings.Builder + replies := 0 + for replies < 40 || !strings.Contains(output.String(), "seen:k40") { + m := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { + return strings.HasPrefix(m.ID, "in-") || m.ID == "slow" || + m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent.RunID == run.ID && m.ChatShellRunEvent.Run == nil + }) + switch { + case m.ID == "slow": + t.Fatal("the slow request answered first; it should still be waiting") + case m.Type == protocol.Error: + t.Fatalf("input refused: %+v", m) + case strings.HasPrefix(m.ID, "in-"): + replies++ + if m.ID != fmt.Sprintf("in-%d", replies) { + t.Fatalf("reply %d is %s", replies, m.ID) + } + default: + output.WriteString(m.ChatShellRunEvent.Output) + } + } + t.Logf("40 keystrokes answered and echoed in %s behind a blocked request", time.Since(started)) + // The shell saw them in the order they were typed. + var want strings.Builder + for i := 1; i <= 40; i++ { + fmt.Fprintf(&want, "seen:k%02d\r\n", i) + } + got := output.String() + var seen strings.Builder + for _, line := range strings.Split(got, "\r\n") { + if strings.HasPrefix(line, "seen:") { + seen.WriteString(line + "\r\n") + } + } + if seen.String() != want.String() { + t.Fatalf("order = %q", seen.String()) + } +} diff --git a/internal/server/terminal_handlers.go b/internal/server/terminal_handlers.go index bd8bd219..f1af1053 100644 --- a/internal/server/terminal_handlers.go +++ b/internal/server/terminal_handlers.go @@ -45,11 +45,12 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter records, err = m.List(ctx) reply.Terminals = records case protocol.TerminalInput: - err = m.Input(body.TerminalID, body.Data) + err = m.ClientInput(clientID, body.TerminalID, body.Data, body.Reply, body.Cols, body.Rows) case protocol.TerminalResize: - record, err = m.Resize(body.TerminalID, body.Cols, body.Rows) + record, err = m.ClientResize(clientID, body.TerminalID, body.Cols, body.Rows, body.Activate) case protocol.TerminalOutput: m.clients.subscribe(clientID, body.TerminalID) + m.attachViewer(clientID, body.TerminalID) record, err = m.Output(ctx, body.TerminalID, body.After) case protocol.TerminalClose: record, err = m.Close(ctx, body.TerminalID) diff --git a/internal/server/terminal_lane.go b/internal/server/terminal_lane.go new file mode 100644 index 00000000..45516f0d --- /dev/null +++ b/internal/server/terminal_lane.go @@ -0,0 +1,75 @@ +package server + +import ( + "context" + "sync" + + "github.com/coder/websocket" + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// connectionQueue bounds the requests read ahead of their handling on one +// connection, per lane. The app sends one ordinary request at a time, so +// the ordinary lane rarely holds more than a few. +const connectionQueue = 256 + +// isTerminalLaneRequest reports the requests a connection handles on its +// terminal lane: what a terminal's keystrokes and size become. They are +// quick (a queued write, an ioctl) and ordered among themselves, and must +// never wait behind an ordinary request read before them on the same +// connection (an elevation's password check, a chat backend call). +func isTerminalLaneRequest(kind string) bool { + switch kind { + case protocol.TerminalInput, protocol.TerminalResize, protocol.ChatShellInput, protocol.ChatShellResize: + return true + } + return false +} + +// readConnectionRequests reads conn's requests until it fails or ctx ends. +// Terminal-lane requests are handled in arrival order by lane on a goroutine +// of their own; the others are returned, in arrival order, for the +// connection's ordinary loop, and the channel closes when reading stops. +// Order is kept within each lane, not across them: a client that needs a +// terminal request to follow an ordinary one (input after terminal_open) +// waits for its reply first. stop ends the reading and waits for the lane +// to finish what it took. +func readConnectionRequests(ctx context.Context, conn *websocket.Conn, lane func(context.Context, protocol.Message)) (requests <-chan protocol.Message, stop func()) { + ctx, cancel := context.WithCancel(ctx) + ordinary := make(chan protocol.Message, connectionQueue) + terminal := make(chan protocol.Message, connectionQueue) + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for request := range terminal { + lane(ctx, request) + } + }() + go func() { + defer wg.Done() + defer close(ordinary) + defer close(terminal) + for { + var request protocol.Message + if err := wsjson.Read(ctx, conn, &request); err != nil { + return + } + queue := ordinary + if isTerminalLaneRequest(request.Type) { + queue = terminal + } + select { + case queue <- request: + case <-ctx.Done(): + return + } + } + }() + return ordinary, func() { + cancel() + wg.Wait() + } +} diff --git a/internal/server/terminal_manager.go b/internal/server/terminal_manager.go index 91af233a..5ffcc3a3 100644 --- a/internal/server/terminal_manager.go +++ b/internal/server/terminal_manager.go @@ -125,6 +125,8 @@ func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, r m.terms[id] = p if clientID != "" { m.clients.subscribe(clientID, id) + // The opener draws it first: it is the active client. + p.viewers.resize(clientID, cols, rows, true) } m.wg.Add(1) go m.supervise(p, cmd, terminal) @@ -256,17 +258,23 @@ func (m *terminalManager) Resize(id string, cols, rows int) (protocol.TerminalRe if err != nil { return protocol.TerminalRecord{}, err } + if err := p.applySize(cols, rows); err != nil { + return protocol.TerminalRecord{}, err + } + return p.snapshot(false, 0), nil +} + +// applySize sets the terminal's PTY to cols x rows (clamped). +func (p *terminalProcess) applySize(cols, rows int) error { cols, rows = chatShellTerminalSize(cols, rows) p.mu.Lock() p.record.Cols, p.record.Rows = cols, rows terminal := p.pty p.mu.Unlock() if terminal != nil { - if err := resizeChatShellTerminal(terminal, cols, rows); err != nil { - return protocol.TerminalRecord{}, err - } + return resizeChatShellTerminal(terminal, cols, rows) } - return p.snapshot(false, 0), nil + return nil } // Output is one terminal with its retained output from byte after on. A diff --git a/internal/server/terminal_process.go b/internal/server/terminal_process.go index 2d7f2aec..506f888a 100644 --- a/internal/server/terminal_process.go +++ b/internal/server/terminal_process.go @@ -35,6 +35,8 @@ type terminalProcess struct { // refused: the login never asked for a password; the terminal is // forgotten without being listed. refused bool + // viewers are the connections drawing it (terminal_viewers.go). + viewers terminalViewers } func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess { diff --git a/internal/server/terminal_viewers.go b/internal/server/terminal_viewers.go new file mode 100644 index 00000000..865421f4 --- /dev/null +++ b/internal/server/terminal_viewers.go @@ -0,0 +1,155 @@ +package server + +import "sync" + +// terminalViewers is the set of client connections drawing one terminal (a +// machine terminal or a chat's terminal command), most recently active +// first. The first is the active client: the terminal's size is the size it +// draws at, and only its emulator's automatic answers to terminal queries +// (cursor position, device attributes) reach the process. Every client's +// emulator answers each query it draws, so without this a query got one +// answer per client, and the size was whichever client resized last, even +// after it left. +// +// A client becomes active by typing, by a resize marked activate (the +// client focused the terminal), or by being the first to attach or resize. +// When the active client leaves, the next most recent one becomes active +// and its last size is applied. The zero value is ready to use. +type terminalViewers struct { + mu sync.Mutex + list []terminalViewer +} + +type terminalViewer struct { + client string + cols, rows int +} + +// terminalSize is a size to apply to the terminal, when ok. +type terminalSize struct { + cols, rows int + ok bool +} + +func (v *terminalViewers) indexLocked(client string) int { + for i, viewer := range v.list { + if viewer.client == client { + return i + } + } + return -1 +} + +// frontLocked moves client to the front, adding it when absent, and +// returns its entry. +func (v *terminalViewers) frontLocked(client string) *terminalViewer { + viewer := terminalViewer{client: client} + if i := v.indexLocked(client); i >= 0 { + viewer = v.list[i] + v.list = append(v.list[:i], v.list[i+1:]...) + } + v.list = append([]terminalViewer{viewer}, v.list...) + return &v.list[0] +} + +// attach records client as drawing the terminal (it opened or read it): the +// active one when no client is. +func (v *terminalViewers) attach(client string) { + if client == "" { + return + } + v.mu.Lock() + defer v.mu.Unlock() + if v.indexLocked(client) < 0 { + v.list = append(v.list, terminalViewer{client: client}) + } +} + +// resize records the size client draws the terminal at and reports the +// size to apply: client's, when it is (or, with activate, becomes) the +// active client, or when the active client has not reported a size yet. +// An unknown client (empty) always applies its size, as before clients +// were told apart. +func (v *terminalViewers) resize(client string, cols, rows int, activate bool) terminalSize { + if client == "" { + return terminalSize{cols, rows, true} + } + v.mu.Lock() + defer v.mu.Unlock() + i := v.indexLocked(client) + switch { + case activate || len(v.list) == 0 || i == 0: + viewer := v.frontLocked(client) + viewer.cols, viewer.rows = cols, rows + return terminalSize{cols, rows, true} + case i < 0: + v.list = append(v.list, terminalViewer{client: client, cols: cols, rows: rows}) + default: + v.list[i].cols, v.list[i].rows = cols, rows + } + front := v.list[0] + return terminalSize{cols, rows, front.cols == 0 || front.rows == 0} +} + +// typedAt is typed from a client drawing the terminal at cols x rows +// (zero when it did not say): it becomes the active client at that size. +func (v *terminalViewers) typedAt(client string, cols, rows int) terminalSize { + if client != "" && cols > 0 && rows > 0 { + return v.resize(client, cols, rows, true) + } + return v.typed(client) +} + +// typed makes client, which typed into the terminal, the active client and +// reports its last size when that changes who is active. +func (v *terminalViewers) typed(client string) terminalSize { + if client == "" { + return terminalSize{} + } + v.mu.Lock() + defer v.mu.Unlock() + if len(v.list) > 0 && v.list[0].client == client { + return terminalSize{} + } + viewer := v.frontLocked(client) + return terminalSize{viewer.cols, viewer.rows, viewer.cols > 0 && viewer.rows > 0} +} + +// answers reports whether client's emulator's automatic answers reach the +// process: only the active client's do, or anyone's while no client is +// known. +func (v *terminalViewers) answers(client string) bool { + if client == "" { + return true + } + v.mu.Lock() + defer v.mu.Unlock() + return len(v.list) == 0 || v.list[0].client == client +} + +// leave forgets client (its connection closed) and, when it was the active +// client, reports the size of the next one, which becomes active. +func (v *terminalViewers) leave(client string) terminalSize { + v.mu.Lock() + defer v.mu.Unlock() + i := v.indexLocked(client) + if i < 0 { + return terminalSize{} + } + v.list = append(v.list[:i], v.list[i+1:]...) + if i != 0 || len(v.list) == 0 { + return terminalSize{} + } + next := v.list[0] + return terminalSize{next.cols, next.rows, next.cols > 0 && next.rows > 0} +} + +// active is the active client, or empty (tests). +func (v *terminalViewers) active() string { + v.mu.Lock() + defer v.mu.Unlock() + if len(v.list) == 0 { + return "" + } + return v.list[0].client +} diff --git a/internal/server/terminal_viewers_test.go b/internal/server/terminal_viewers_test.go new file mode 100644 index 00000000..95b279ff --- /dev/null +++ b/internal/server/terminal_viewers_test.go @@ -0,0 +1,60 @@ +package server + +import "testing" + +func TestTerminalViewersActiveClient(t *testing.T) { + var v terminalViewers + // The first client to resize is active and sizes the terminal. + if got := v.resize("a", 156, 37, false); got != (terminalSize{156, 37, true}) { + t.Fatalf("first resize = %+v", got) + } + v.attach("b") + // Another client's size is kept but not applied; its answers are dropped. + if got := v.resize("b", 121, 11, false); got.ok { + t.Fatalf("background resize applied: %+v", got) + } + if !v.answers("a") || v.answers("b") || v.answers("stranger") { + t.Fatal("only the active client answers") + } + // Typing hands the terminal to b, at b's size; typing again changes nothing. + if got := v.typed("b"); got != (terminalSize{121, 11, true}) { + t.Fatalf("typed = %+v", got) + } + if got := v.typed("b"); got.ok || v.active() != "b" || v.answers("a") { + t.Fatalf("typed again = %+v, active %q", got, v.active()) + } + // Focusing (activate) hands it back at a's new size. + if got := v.resize("a", 150, 40, true); got != (terminalSize{150, 40, true}) || v.active() != "a" { + t.Fatalf("activate = %+v", got) + } + // A background client leaving changes nothing; the active one leaving + // hands the terminal to the next most recent, at its last size. + v.attach("c") + if got := v.leave("c"); got.ok { + t.Fatalf("background leave = %+v", got) + } + if got := v.leave("a"); got != (terminalSize{121, 11, true}) || v.active() != "b" || !v.answers("b") { + t.Fatalf("leave = %+v, active %q", got, v.active()) + } + if got := v.leave("b"); got.ok || v.active() != "" || !v.answers("anyone") { + t.Fatalf("last leave = %+v", got) + } +} + +func TestTerminalViewersWithoutSizes(t *testing.T) { + var v terminalViewers + v.attach("reader") + // The active client has drawn nothing yet: another's size is applied. + if got := v.resize("other", 90, 20, false); !got.ok || v.active() != "reader" { + t.Fatalf("resize = %+v, active %q", got, v.active()) + } + // Typing from a client of unknown size makes it active without a resize. + if got := v.typed("typist"); got.ok || v.active() != "typist" { + t.Fatalf("typed = %+v", got) + } + // A connection that is not told apart (tests, internal callers) always + // applies and answers. + if got := v.resize("", 10, 5, false); !got.ok || !v.answers("") { + t.Fatalf("anonymous = %+v", got) + } +} diff --git a/internal/server/terminal_ws_test.go b/internal/server/terminal_ws_test.go index 3d76ebfb..78b24605 100644 --- a/internal/server/terminal_ws_test.go +++ b/internal/server/terminal_ws_test.go @@ -117,12 +117,14 @@ func TestTerminalOverWebsocket(t *testing.T) { t.Fatalf("input reply = %+v", got) } _, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42") + // The second client draws it larger; the opener stays the active client + // (terminal_active_test.go) until the second one types below. resized := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalResize, "size", protocol.TerminalRequest{TerminalID: term.ID, Cols: 120, Rows: 33})) - if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 120 || resized.Terminal.Rows != 33 { + if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 80 || resized.Terminal.Rows != 24 { t.Fatalf("resize reply = %+v", resized) } list := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{})) - if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 120 || list.Terminals[0].Output != "" { + if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 80 || list.Terminals[0].Output != "" { t.Fatalf("list = %+v", list.Terminals) } // The second client reads everything once, then only what follows. diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 9992cfa4..0aa9ed07 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -267,7 +267,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // Terminal lifecycle changes reach every connection; output only the // connections that opened or read that terminal. terminals.clients.attach(clientID, write) - defer terminals.clients.detach(clientID) + defer terminals.detach(clientID) + // A closed connection hands the chats' terminal commands it was + // active in to their next client. + defer func() { hub.shellRunner().leave(clientID) }() if notes != nil { defer notes.detach(clientID) } @@ -276,16 +279,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // previous, whose reply the client would discard as stale anyway. cancelChatSearch := func() {} defer func() { cancelChatSearch() }() - for { - var request protocol.Message - if err := wsjson.Read(connCtx, conn, &request); err != nil { + // Keystrokes and sizes take their own lane (terminal_lane.go), so + // they never wait behind a slow request read before them. The lane + // is drained before the deferred detaches above run. + requests, stopReading := readConnectionRequests(connCtx, conn, func(laneCtx context.Context, request protocol.Message) { + if elevation.refuse(request, elevationKey, write) { return } - if request.Type != protocol.ChatShellInput && request.Type != protocol.ChatShellResize && - request.Type != protocol.TerminalInput && request.Type != protocol.TerminalResize { - // Keystrokes would be one line each; their data is never logged. - log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version) + if isTerminalRequest(request.Type) { + handleTerminalRequest(laneCtx, request, terminals, clientID, write) + return } + handleChat(laneCtx, request, options.Chat, hub, registry, clientID, write) + }) + defer stopReading() + for request := range requests { + // Keystrokes take the terminal lane and are never logged. + log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version) if request.Type == protocol.Submit && !options.AllowAuthoring { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"}) continue @@ -327,9 +337,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin continue } if isTerminalRequest(request.Type) { - // Closing waits for the shell to go; it never delays input - // to the other terminals behind it. - if request.Type == protocol.TerminalClose { + // Opening waits up to the login's prompt wait and closing for + // the shell to go; neither delays the requests behind it. + if request.Type == protocol.TerminalClose || request.Type == protocol.TerminalOpen { go handleTerminalRequest(connCtx, request, terminals, clientID, write) } else { handleTerminalRequest(connCtx, request, terminals, clientID, write)