The terminal session id lived only in memory, so the first time the panel opened after a launch it always created another PTY. The old shell stayed on the server (unattached shells live for half an hour) but the client could no longer find it. The id is now remembered per connection and directory. On first open the panel lists /api/terminal/sessions?cwd=<dir> and attaches to the remembered session while the server still has it, showing its replayed history. Without that id it adopts the newest running session of the directory, and only when the directory has nothing does it create one. An explicit "close terminal" forgets the id and forces a fresh shell, and a fatal SESSION_NOT_FOUND clears it and recovers, so a server restart cannot leave a dead panel. The panel is still one terminal per project, not a tab strip. 0.4.2 (402).
362 lines
11 KiB
Dart
362 lines
11 KiB
Dart
// The live terminal: the xterm model the view renders, and the socket that
|
|
// carries its bytes. Kept on AppState so closing the panel (or switching
|
|
// tabs) does not end the shell; reattaching replays the server's snapshot.
|
|
import 'dart:async';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:xterm/xterm.dart';
|
|
|
|
import 'api/terminal.dart';
|
|
import 'state.dart';
|
|
|
|
class TerminalSessionState extends ChangeNotifier {
|
|
final AppState app;
|
|
final String directory;
|
|
|
|
final Terminal model = Terminal(maxLines: 5000);
|
|
|
|
TerminalSocket? _socket;
|
|
TerminalLinkState link = TerminalLinkState.idle;
|
|
String? detail;
|
|
String? sessionId;
|
|
|
|
/// Key-bar modifiers. They apply to the next character, whichever keyboard
|
|
/// produced it: the on-screen bar or the phone's IME (which never sends
|
|
/// Ctrl itself).
|
|
bool ctrl = false;
|
|
bool alt = false;
|
|
bool shift = false;
|
|
|
|
int _cols = 80;
|
|
int _rows = 24;
|
|
Timer? _resizeTimer;
|
|
bool _opened = false;
|
|
bool _disposed = false;
|
|
bool _recovering = false;
|
|
|
|
TerminalSessionState(this.app, this.directory) {
|
|
model.onOutput = _onOutput;
|
|
model.onResize = (cols, rows, _, __) {
|
|
_cols = cols;
|
|
_rows = rows;
|
|
_scheduleResize();
|
|
};
|
|
}
|
|
|
|
void toggleCtrl() {
|
|
ctrl = !ctrl;
|
|
notifyListeners();
|
|
}
|
|
|
|
void toggleAlt() {
|
|
alt = !alt;
|
|
notifyListeners();
|
|
}
|
|
|
|
void toggleShift() {
|
|
shift = !shift;
|
|
notifyListeners();
|
|
}
|
|
|
|
/// Sends one typed character, with whatever modifiers are pending, then
|
|
/// drops them. Escape sequences (arrows, Home, …) arrive already complete
|
|
/// and pass through untouched.
|
|
void _onOutput(String data) {
|
|
var out = data;
|
|
if (out.isNotEmpty) {
|
|
final code = out.codeUnitAt(0);
|
|
final printable = out.length == 1 && code >= 0x20 && code != 0x7f;
|
|
if (printable && ctrl) {
|
|
if (code >= 0x61 && code <= 0x7a) {
|
|
out = String.fromCharCode(code - 0x60);
|
|
} else if (code >= 0x41 && code <= 0x5a) {
|
|
out = String.fromCharCode(code - 0x40);
|
|
} else if (code >= 0x5b && code <= 0x5f) {
|
|
out = String.fromCharCode(code - 0x40);
|
|
} else if (code == 0x20) {
|
|
out = '\x00';
|
|
}
|
|
}
|
|
// Alt is an ESC prefix on the character.
|
|
if (printable && alt) out = '\x1b$out';
|
|
}
|
|
_socket?.write(out);
|
|
if ((ctrl || alt || shift) && out.isNotEmpty) {
|
|
ctrl = false;
|
|
alt = false;
|
|
shift = false;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
bool get isOpen => link == TerminalLinkState.open;
|
|
bool get isRunning =>
|
|
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
|
|
|
|
/// Opens the terminal on first use; later calls just make sure the socket is
|
|
/// alive. Unless [fresh] is set, the previous session for this directory is
|
|
/// picked up again when the server still holds it (the app may have been
|
|
/// restarted since), so the same shell — and its history — comes back.
|
|
Future<void> ensureOpen({bool fresh = false}) async {
|
|
if (_disposed) return;
|
|
if (_opened) {
|
|
if (_socket == null && link != TerminalLinkState.exited) await _attach();
|
|
return;
|
|
}
|
|
_opened = true;
|
|
await _open(fresh: fresh);
|
|
}
|
|
|
|
Future<void> _open({required bool fresh}) async {
|
|
final client = app.client;
|
|
if (client == null) return;
|
|
_set(TerminalLinkState.creating);
|
|
if (!fresh && await _restore()) return;
|
|
await _create();
|
|
}
|
|
|
|
/// The session this panel should reattach to: the one remembered for the
|
|
/// directory while the server still lists it, else the newest running one,
|
|
/// else the newest one. Null means the server holds nothing for this
|
|
/// directory and a session has to be created.
|
|
static String? restoreCandidate(
|
|
String? saved, List<ServerTerminal> sessions) {
|
|
if (sessions.isEmpty) return null;
|
|
if (saved != null && sessions.any((s) => s.sessionId == saved)) {
|
|
return saved;
|
|
}
|
|
final running = sessions.where((s) => s.status == 'running').toList();
|
|
final pool = running.isNotEmpty ? running : sessions;
|
|
pool.sort((a, b) => (b.createdAt ?? 0).compareTo(a.createdAt ?? 0));
|
|
final id = pool.first.sessionId;
|
|
return id.isEmpty ? null : id;
|
|
}
|
|
|
|
Future<bool> _restore() async {
|
|
final client = app.client;
|
|
if (client == null) return false;
|
|
final saved = await _savedId();
|
|
final List<ServerTerminal> sessions;
|
|
try {
|
|
sessions = await client.listTerminals(cwd: directory);
|
|
} catch (_) {
|
|
// Let the create path report the failure; a listing error here should
|
|
// not be what the status bar shows.
|
|
return false;
|
|
}
|
|
final id = restoreCandidate(saved, sessions);
|
|
if (_disposed || id == null) return false;
|
|
sessionId = id;
|
|
await _remember(id);
|
|
await _attach();
|
|
return true;
|
|
}
|
|
|
|
Future<void> _create() async {
|
|
final client = app.client;
|
|
if (client == null) return;
|
|
_set(TerminalLinkState.creating);
|
|
try {
|
|
final info = await client.createTerminal(
|
|
cwd: directory, cols: _cols, rows: _rows);
|
|
if (_disposed) return;
|
|
sessionId = info.sessionId;
|
|
_cols = info.cols;
|
|
_rows = info.rows;
|
|
await _remember(info.sessionId);
|
|
await _attach();
|
|
} catch (error) {
|
|
_set(TerminalLinkState.error, detail: _message(error));
|
|
}
|
|
}
|
|
|
|
/// The connection a saved terminal id belongs to. A different saved server
|
|
/// has its own ids, and adopting one across servers would point at nothing.
|
|
String get _connectionId => app.conn?.id ?? '';
|
|
|
|
Future<String?> _savedId() async {
|
|
final id = _connectionId;
|
|
if (id.isEmpty) return null;
|
|
return app.storage.terminalSession(id, directory);
|
|
}
|
|
|
|
Future<void> _remember(String id) async {
|
|
final connection = _connectionId;
|
|
if (connection.isEmpty) return;
|
|
await app.storage.saveTerminalSession(connection, directory, id);
|
|
}
|
|
|
|
Future<void> _forget() async {
|
|
final connection = _connectionId;
|
|
if (connection.isEmpty) return;
|
|
await app.storage.clearTerminalSession(connection, directory);
|
|
}
|
|
|
|
Future<void> _attach() async {
|
|
final client = app.client;
|
|
final id = sessionId;
|
|
if (client == null || id == null || _disposed) return;
|
|
await _socket?.dispose();
|
|
final socket = TerminalSocket(
|
|
transport: client.transport,
|
|
headers: client.eventHeaders,
|
|
sessionId: id,
|
|
onEvent: _onEvent,
|
|
onState: (state, {detail}) => _set(state, detail: detail),
|
|
);
|
|
_socket = socket;
|
|
await socket.connect();
|
|
}
|
|
|
|
void _onEvent(TerminalEvent event) {
|
|
if (_disposed) return;
|
|
switch (event.type) {
|
|
case 'snapshot':
|
|
// Replay at the size the server drew the history for, then clear what
|
|
// this view already had: a reattach must not duplicate the screen.
|
|
if (event.cols != null && event.rows != null) {
|
|
model.resize(event.cols!, event.rows!);
|
|
}
|
|
_clear();
|
|
if (event.data.isNotEmpty) model.write(event.data);
|
|
if (event.status == 'exited') {
|
|
_set(TerminalLinkState.exited,
|
|
detail: event.exitCode == null
|
|
? '已退出'
|
|
: '退出码 ${event.exitCode}');
|
|
}
|
|
break;
|
|
case 'restarted':
|
|
_clear();
|
|
if (event.data.isNotEmpty) model.write(event.data);
|
|
_set(TerminalLinkState.open);
|
|
break;
|
|
case 'output':
|
|
model.write(event.data);
|
|
break;
|
|
case 'exit':
|
|
_set(TerminalLinkState.exited,
|
|
detail: event.exitCode == null
|
|
? '已退出'
|
|
: '退出码 ${event.exitCode}');
|
|
break;
|
|
case 'error':
|
|
if (event.fatal) {
|
|
if (event.code == 'SESSION_NOT_FOUND') {
|
|
// The remembered id outlived the server's session (a server
|
|
// restart, or the idle reaper won a race with the attach): open a
|
|
// new shell instead of leaving a dead panel.
|
|
_recoverMissing();
|
|
} else {
|
|
_set(TerminalLinkState.error,
|
|
detail: event.message ?? event.code ?? '终端连接失败');
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
/// Clears the screen and the scrollback, then homes the cursor.
|
|
void _clear() => model.write('\x1b[2J\x1b[3J\x1b[H');
|
|
|
|
void _set(TerminalLinkState state, {String? detail}) {
|
|
link = state;
|
|
if (detail != null) this.detail = detail;
|
|
if (state == TerminalLinkState.open) this.detail = null;
|
|
notifyListeners();
|
|
}
|
|
|
|
void _scheduleResize() {
|
|
_resizeTimer?.cancel();
|
|
_resizeTimer = Timer(const Duration(milliseconds: 250), () {
|
|
final client = app.client;
|
|
final id = sessionId;
|
|
if (client == null || id == null || _disposed) return;
|
|
client
|
|
.resizeTerminal(id, _cols, _rows, directory: directory)
|
|
.catchError((_) {});
|
|
});
|
|
}
|
|
|
|
/// Restarts the shell in place (the server keeps the session id).
|
|
Future<void> restart() async {
|
|
final client = app.client;
|
|
final id = sessionId;
|
|
if (client == null || id == null) return;
|
|
_set(TerminalLinkState.connecting);
|
|
try {
|
|
await client.restartTerminal(id,
|
|
cwd: directory, cols: _cols, rows: _rows);
|
|
if (_disposed) return;
|
|
_clear();
|
|
_set(TerminalLinkState.open);
|
|
} catch (error) {
|
|
_set(TerminalLinkState.error, detail: _message(error));
|
|
}
|
|
}
|
|
|
|
/// After the app returns from the background: the socket may be dead
|
|
/// without having reported it.
|
|
Future<void> reconnectIfNeeded() async {
|
|
if (_disposed) return;
|
|
if (link == TerminalLinkState.exited || link == TerminalLinkState.error) {
|
|
return;
|
|
}
|
|
if (_socket == null) await _attach();
|
|
}
|
|
|
|
/// Ends the shell on the server and drops the socket; the next
|
|
/// [ensureOpen] starts a fresh session.
|
|
Future<void> closeSession() async {
|
|
final client = app.client;
|
|
final id = sessionId;
|
|
sessionId = null;
|
|
_opened = false;
|
|
link = TerminalLinkState.idle;
|
|
detail = null;
|
|
await _forget();
|
|
await _socket?.dispose();
|
|
_socket = null;
|
|
if (!_disposed) notifyListeners();
|
|
if (client != null && id != null) {
|
|
try {
|
|
await client.closeTerminal(id, directory: directory);
|
|
} catch (_) {}
|
|
}
|
|
}
|
|
|
|
/// Drops a session the server no longer has and opens another one in its
|
|
/// place, so a stale remembered id does not leave the panel unusable.
|
|
Future<void> _recoverMissing() async {
|
|
if (_recovering || _disposed) return;
|
|
_recovering = true;
|
|
try {
|
|
sessionId = null;
|
|
await _forget();
|
|
await _socket?.dispose();
|
|
_socket = null;
|
|
if (_disposed) return;
|
|
_opened = true;
|
|
await _create();
|
|
} finally {
|
|
_recovering = false;
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_resizeTimer?.cancel();
|
|
_socket?.dispose();
|
|
_socket = null;
|
|
// The session is left for the server's idle reaper when the app goes
|
|
// away; [closeSession] handles an explicit disconnect.
|
|
super.dispose();
|
|
}
|
|
|
|
String _message(Object error) {
|
|
final text = '$error';
|
|
return text.startsWith('ApiError') ? text : text;
|
|
}
|
|
}
|