Files
pipelines/app/lib/features/terminal/terminal_hub.dart
T
alan 30934aa71c Toggle the terminal with Alt/Ctrl/Cmd+T, animate it, focus it, and cycle its tabs with Ctrl+Tab
Alt+T, Ctrl+T and Cmd+T join Ctrl+` as early focus-manager key handlers, so
they toggle the panel, window or narrow page from anywhere without reaching
the shell or a text field. Opening with no terminal starts one. The shown
terminal takes the keyboard (also on reload and tab changes) and hiding gives
it back. The panel slides from the bottom edge as the app shrinks, the window
scales and fades, both on Motion.standard and off under reduced motion.
While shown, Ctrl+Tab/Ctrl+Shift+Tab move between terminal tabs instead of
chat panes. The tooltip and menu list the shortcuts the platform delivers.
2026-11-09 23:43:56 +00:00

259 lines
7.9 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../core/api_gateway.dart';
import 'terminal_info.dart';
import 'terminal_listing.dart';
import 'terminal_machines.dart';
import 'terminal_tab.dart';
/// Every machine terminal the app shows, across the connected machines:
/// the tabs, the selected one, and their link to each machine's socket.
///
/// The hub belongs to the app, not to a view: terminals keep running and
/// keep their output while the panel is hidden or the window is minimised.
/// When a machine connects (first, or again after a drop or a server
/// restart) its terminals are listed, new ones get a tab, and every tab
/// resumes its output from the last byte it holds.
class TerminalHub extends ChangeNotifier {
TerminalHub(this.machines);
final TerminalMachines machines;
final Map<String, _Link> _links = {};
bool _active = false;
final List<TerminalTab> _tabs = [];
String? _selected;
bool _disposed = false;
/// The last refusal of an open or close, in the server's words.
String? error;
List<TerminalTab> get tabs => List.unmodifiable(_tabs);
List<TerminalMachine> get connected => machines.value;
TerminalTab? get selected =>
_tabs.where((tab) => tab.key == _selected).firstOrNull ??
_tabs.firstOrNull;
/// Whether the tabs come from more than one machine (or more than one
/// is connected), so each names its machine.
bool get multiMachine =>
connected.length > 1 ||
_tabs.map((tab) => tab.machineId).toSet().length > 1;
/// Starts following the machines: their terminals are listed now and on
/// every reconnect. The surface calls it the first time the terminal is
/// shown, so an app that never shows it sends no terminal requests (each
/// connection sends one request at a time; the first screen's read goes
/// first).
void activate() {
if (_active || _disposed) return;
_active = true;
machines.addListener(_machinesChanged);
_machinesChanged();
}
bool get active => _active;
void select(TerminalTab tab) {
if (_selected == tab.key) return;
_selected = tab.key;
_notify();
}
/// Selects the tab [step] places after the selected one, wrapping round.
void step(int step) {
final current = selected;
if (current == null) return;
final index = _tabs.indexOf(current);
select(_tabs[(index + step) % _tabs.length]);
}
final TerminalListing _listing = TerminalListing();
/// Completes once no machine's terminal list is still being read.
Future<void> listed() => _listing.idle();
/// The machine [gateway] belongs to, if it is connected.
TerminalMachine? machineFor(String? id) =>
connected.where((machine) => machine.id == id).firstOrNull;
/// Opens a shell on [machineId] (the first connected machine when null)
/// in [cwd] (home when empty) and selects its tab. Returns the refusal.
Future<String?> open({String? machineId, String cwd = ''}) async {
activate();
final machine = machineId == null
? connected.firstOrNull
: machineFor(machineId);
if (machine == null) {
return error = 'No machine is connected to open a terminal on.';
}
try {
final reply = await machine.gateway.call('terminal_open', {
'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)},
});
final record = reply['terminal'];
if (record is! Map) throw StateError('The server sent no terminal.');
final tab = _adopt(machine, TerminalInfo.fromJson(record));
_selected = tab.key;
error = null;
_notify();
return null;
} catch (failure) {
error = '$failure';
_notify();
return error;
}
}
/// Ends [tab]'s shell (and its tmux session) and removes the tab. A tab
/// whose machine is not connected cannot be closed yet.
Future<String?> close(TerminalTab tab) async {
if (!tab.connected) {
return error = '${tab.machineName} is not connected.';
}
try {
await tab.gateway.call('terminal_close', {
'terminal_request': {'terminal_id': tab.info.id},
});
_remove(tab.key);
error = null;
return null;
} catch (failure) {
error = '$failure';
_notify();
return error;
}
}
TerminalTab _adopt(TerminalMachine machine, TerminalInfo info) {
final key = terminalKey(machine.id, info.id);
final existing = _tabs.where((tab) => tab.key == key).firstOrNull;
if (existing != null) {
existing.machineName = machine.name;
existing.attach(machine.gateway, info);
return existing;
}
final tab = TerminalTab(
machineId: machine.id,
machineName: machine.name,
gateway: machine.gateway,
info: info,
)..addListener(_notify);
_tabs.add(tab);
unawaited(tab.resume());
return tab;
}
void _remove(String key) {
final index = _tabs.indexWhere((tab) => tab.key == key);
if (index < 0) return;
final tab = _tabs.removeAt(index);
if (_selected == key) {
_selected = _tabs.isEmpty
? null
: _tabs[index.clamp(0, _tabs.length - 1)].key;
}
tab
..removeListener(_notify)
..dispose();
_notify();
}
void _machinesChanged() {
if (_disposed) return;
final ids = {for (final machine in connected) machine.id};
for (final id in _links.keys.where((id) => !ids.contains(id)).toList()) {
_links.remove(id)!.cancel();
for (final tab in _tabs.where((tab) => tab.machineId == id)) {
tab.disconnected();
}
}
for (final machine in connected) {
final link = _links[machine.id];
if (link != null && identical(link.gateway, machine.gateway)) continue;
link?.cancel();
_links[machine.id] = _Link(
machine.gateway,
machine.gateway.frames.listen((frame) => _frame(machine, frame)),
);
unawaited(_sync(machine));
}
_notify();
}
/// Lists [machine]'s terminals: each gets (or keeps) a tab, which then
/// resumes its output; tabs of terminals the machine no longer has go.
Future<void> _sync(TerminalMachine machine) =>
_listing.track(() => _list(machine));
Future<void> _list(TerminalMachine machine) async {
final List<TerminalInfo> infos;
try {
infos = terminalInfos(await machine.gateway.call('terminal_list'));
} catch (failure) {
// A server without terminals answers with an error; its tabs stay.
error = '$failure';
_notify();
return;
}
if (_disposed || !identical(_links[machine.id]?.gateway, machine.gateway)) {
return;
}
final listed = <String>{};
for (final info in infos.where((info) => !info.closed)) {
listed.add(_adopt(machine, info).key);
}
for (final tab in _tabs.toList()) {
if (tab.machineId == machine.id && !listed.contains(tab.key)) {
_remove(tab.key);
}
}
_notify();
}
void _frame(TerminalMachine machine, JsonMap frame) {
if (frame['type'] != 'terminal_event') return;
final event = frame['terminal_event'];
if (event is! Map) return;
final key = terminalKey(machine.id, '${event['terminal_id'] ?? ''}');
final record = event['terminal'];
if (record is Map) {
final info = TerminalInfo.fromJson(record);
if (info.closed) return _remove(key);
// A terminal another client opened appears here too.
if (!_tabs.any((tab) => tab.key == key)) {
_adopt(machine, info);
_notify();
return;
}
}
_tabs.where((tab) => tab.key == key).firstOrNull?.frame(event);
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
if (_active) machines.removeListener(_machinesChanged);
for (final link in _links.values) {
link.cancel();
}
for (final tab in _tabs) {
tab.dispose();
}
super.dispose();
}
}
class _Link {
_Link(this.gateway, this.frames);
final ApiGateway gateway;
final StreamSubscription<JsonMap> frames;
void cancel() => unawaited(frames.cancel());
}