A directory now has a TerminalWorkspace holding a list of tabs instead of a
single session. The status bar's left side became a dropdown: it shows the
active tab and its state ("终端 2 · 运行中") and lists the other tabs (the
active one checked) plus "新建终端". New tabs take the smallest free number,
so closing one frees its name.
Only the active tab keeps a socket: switching detaches the old tab and
attaches the new one, whose screen is replayed from the server snapshot; the
shell itself keeps running. The tab's model stays in memory, so switching
back is immediate.
The tab list (ids, labels, active one) is saved per connection and directory.
On the first open the server's sessions for the directory are reconciled with
it: saved labels and order are kept for sessions that still exist, sessions
opened elsewhere (web UI) are appended in creation order, and tabs whose
session is gone are dropped. Project-action command runners are not shown as
tabs. The 0.4.2 single-session value is read as one tab.
0.4.3 (403).
302 lines
8.6 KiB
Dart
302 lines
8.6 KiB
Dart
// The OpenChamber terminal protocol: HTTP commands (create, resize, restart,
|
|
// close) plus one WebSocket per host carrying binary control frames (a 0x01
|
|
// tag, then JSON). A socket can attach to several terminals; we attach to one.
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'transport.dart';
|
|
|
|
/// What `POST /api/terminal/create` (and restart) answers.
|
|
class TerminalSessionInfo {
|
|
final String sessionId;
|
|
final int cols;
|
|
final int rows;
|
|
final String status;
|
|
|
|
const TerminalSessionInfo({
|
|
required this.sessionId,
|
|
this.cols = 80,
|
|
this.rows = 24,
|
|
this.status = 'running',
|
|
});
|
|
|
|
factory TerminalSessionInfo.fromJson(Map<String, dynamic> j) =>
|
|
TerminalSessionInfo(
|
|
sessionId: j['sessionId'] as String? ?? '',
|
|
cols: (j['cols'] as num?)?.toInt() ?? 80,
|
|
rows: (j['rows'] as num?)?.toInt() ?? 24,
|
|
status: j['status'] as String? ?? 'running',
|
|
);
|
|
}
|
|
|
|
/// A terminal the server still holds, from `GET /api/terminal/sessions`.
|
|
/// The id outlives this app process, so a restart can attach to the same
|
|
/// shell instead of making another one.
|
|
class ServerTerminal {
|
|
final String sessionId;
|
|
final String cwd;
|
|
final String status; // running | exited
|
|
final int? createdAt;
|
|
final String mode; // interactive | command
|
|
final String purpose; // terminal | project-action (or empty)
|
|
|
|
const ServerTerminal({
|
|
required this.sessionId,
|
|
this.cwd = '',
|
|
this.status = 'running',
|
|
this.createdAt,
|
|
this.mode = 'interactive',
|
|
this.purpose = '',
|
|
});
|
|
|
|
/// A terminal a person opened. A project action's command runner is also a
|
|
/// PTY, but it is not one of the user's tabs.
|
|
bool get interactive => mode != 'command' && purpose != 'project-action';
|
|
|
|
factory ServerTerminal.fromJson(Map<String, dynamic> j) {
|
|
final purposeJson = j['purpose'];
|
|
return ServerTerminal(
|
|
sessionId: j['sessionId'] as String? ?? '',
|
|
cwd: j['cwd'] as String? ?? '',
|
|
status: j['status'] as String? ?? 'running',
|
|
createdAt: (j['createdAt'] as num?)?.toInt(),
|
|
mode: j['mode'] as String? ?? 'interactive',
|
|
purpose: purposeJson is Map
|
|
? purposeJson['type'] as String? ?? ''
|
|
: '',
|
|
);
|
|
}
|
|
}
|
|
|
|
/// One frame from the server: a snapshot (the authoritative screen), output,
|
|
/// an exit notice, or an error.
|
|
class TerminalEvent {
|
|
final String type; // snapshot | output | restarted | exit | error
|
|
final String data; // snapshot history / output text
|
|
final int sequence;
|
|
final int? cols;
|
|
final int? rows;
|
|
final String? status;
|
|
final int? exitCode;
|
|
final int? signal;
|
|
final String? code;
|
|
final String? message;
|
|
final bool fatal;
|
|
|
|
const TerminalEvent(
|
|
this.type, {
|
|
this.data = '',
|
|
this.sequence = 0,
|
|
this.cols,
|
|
this.rows,
|
|
this.status,
|
|
this.exitCode,
|
|
this.signal,
|
|
this.code,
|
|
this.message,
|
|
this.fatal = false,
|
|
});
|
|
}
|
|
|
|
/// The socket's life, for the status bar.
|
|
enum TerminalLinkState { idle, creating, connecting, open, reconnecting, exited, error }
|
|
|
|
/// One attached terminal. Writes made while the socket is down wait in a
|
|
/// buffer; a dropped socket reconnects with backoff and reattaches, which
|
|
/// begins with a fresh snapshot.
|
|
class TerminalSocket {
|
|
final Transport transport;
|
|
final Map<String, String> headers;
|
|
final String sessionId;
|
|
final void Function(TerminalEvent event) onEvent;
|
|
final void Function(TerminalLinkState state, {String? detail}) onState;
|
|
|
|
WebSocket? _socket;
|
|
Timer? _keepAlive;
|
|
Timer? _reconnect;
|
|
final StringBuffer _pending = StringBuffer();
|
|
int _failures = 0;
|
|
int _generation = 0;
|
|
bool _disposed = false;
|
|
bool _opened = false;
|
|
|
|
TerminalSocket({
|
|
required this.transport,
|
|
required this.headers,
|
|
required this.sessionId,
|
|
required this.onEvent,
|
|
required this.onState,
|
|
});
|
|
|
|
Future<void> connect() async {
|
|
if (_disposed) return;
|
|
final generation = ++_generation;
|
|
onState(_opened ? TerminalLinkState.reconnecting : TerminalLinkState.connecting);
|
|
try {
|
|
final socket = await transport.webSocket(
|
|
'/api/terminal/ws',
|
|
headers: headers,
|
|
);
|
|
if (_disposed || generation != _generation) {
|
|
await socket.close();
|
|
return;
|
|
}
|
|
_socket = socket;
|
|
_failures = 0;
|
|
socket.listen(
|
|
_handle,
|
|
onError: (_) => _drop(generation),
|
|
onDone: () => _drop(generation),
|
|
);
|
|
_send({'t': 'hello', 'v': 3});
|
|
_send({'t': 'attach', 'v': 3, 's': sessionId});
|
|
_opened = true;
|
|
_keepAlive?.cancel();
|
|
_keepAlive = Timer.periodic(
|
|
const Duration(seconds: 45), (_) => _send({'t': 'ping', 'v': 3}));
|
|
onState(TerminalLinkState.open);
|
|
_flushPending();
|
|
} catch (error) {
|
|
if (_disposed) return;
|
|
onState(TerminalLinkState.error, detail: '$error');
|
|
_scheduleReconnect();
|
|
}
|
|
}
|
|
|
|
void write(String data) {
|
|
if (data.isEmpty) return;
|
|
if (_socket == null) {
|
|
_pending.write(data);
|
|
return;
|
|
}
|
|
_send({'t': 'write', 'v': 3, 's': sessionId, 'd': data});
|
|
}
|
|
|
|
Future<void> dispose() async {
|
|
_disposed = true;
|
|
_generation++;
|
|
_reconnect?.cancel();
|
|
_keepAlive?.cancel();
|
|
final socket = _socket;
|
|
_socket = null;
|
|
// Detaching leaves the session running on the server; closing the socket
|
|
// is enough for a panel that is going away.
|
|
try {
|
|
await socket?.close();
|
|
} catch (_) {}
|
|
}
|
|
|
|
// ------------------------------------------------------------- internals
|
|
|
|
void _send(Map<String, Object?> message) {
|
|
final socket = _socket;
|
|
if (socket == null) return;
|
|
final bytes = <int>[1, ...utf8.encode(jsonEncode(message))];
|
|
try {
|
|
socket.add(bytes);
|
|
} catch (_) {
|
|
_drop(_generation);
|
|
}
|
|
}
|
|
|
|
void _flushPending() {
|
|
if (_pending.isEmpty) return;
|
|
final data = _pending.toString();
|
|
_pending.clear();
|
|
write(data);
|
|
}
|
|
|
|
void _drop(int generation) {
|
|
if (_disposed || generation != _generation) return;
|
|
_generation++;
|
|
_keepAlive?.cancel();
|
|
_keepAlive = null;
|
|
final socket = _socket;
|
|
_socket = null;
|
|
try {
|
|
socket?.close();
|
|
} catch (_) {}
|
|
onState(TerminalLinkState.reconnecting);
|
|
_scheduleReconnect();
|
|
}
|
|
|
|
void _scheduleReconnect() {
|
|
if (_disposed || _reconnect != null) return;
|
|
_failures += 1;
|
|
final delay = Duration(
|
|
milliseconds: 500 * (1 << (_failures - 1).clamp(0, 4)));
|
|
_reconnect = Timer(delay, () {
|
|
_reconnect = null;
|
|
if (!_disposed) connect();
|
|
});
|
|
}
|
|
|
|
void _handle(dynamic raw) {
|
|
if (_disposed || raw is! List<int> || raw.isEmpty) return;
|
|
final Map<String, dynamic> message;
|
|
try {
|
|
final tag = raw.first;
|
|
final bytes = tag == 1 ? raw.sublist(1) : raw;
|
|
final decoded = jsonDecode(utf8.decode(bytes));
|
|
if (decoded is! Map<String, dynamic>) return;
|
|
message = decoded;
|
|
} catch (_) {
|
|
return;
|
|
}
|
|
final type = message['t'] as String? ?? '';
|
|
final sequence = (message['q'] as num?)?.toInt() ?? 0;
|
|
switch (type) {
|
|
case 'snapshot':
|
|
onEvent(TerminalEvent(
|
|
'snapshot',
|
|
data: message['history'] as String? ?? '',
|
|
sequence: sequence,
|
|
cols: (message['cols'] as num?)?.toInt(),
|
|
rows: (message['rows'] as num?)?.toInt(),
|
|
status: message['status'] as String?,
|
|
exitCode: (message['exitCode'] as num?)?.toInt(),
|
|
signal: (message['signal'] as num?)?.toInt(),
|
|
));
|
|
break;
|
|
case 'output':
|
|
// `r` is the replay-safe text (terminal queries removed); `d` the raw
|
|
// bytes. Replay text is what the official client renders.
|
|
onEvent(TerminalEvent(
|
|
'output',
|
|
data: (message['r'] ?? message['d'] ?? '') as String,
|
|
sequence: sequence,
|
|
));
|
|
break;
|
|
case 'restarted':
|
|
onEvent(TerminalEvent(
|
|
'restarted',
|
|
data: message['history'] as String? ?? '',
|
|
sequence: sequence,
|
|
));
|
|
break;
|
|
case 'exit':
|
|
onState(TerminalLinkState.exited,
|
|
detail: '${(message['exitCode'] as num?)?.toInt() ?? ''}');
|
|
onEvent(TerminalEvent(
|
|
'exit',
|
|
sequence: sequence,
|
|
exitCode: (message['exitCode'] as num?)?.toInt(),
|
|
signal: (message['signal'] as num?)?.toInt(),
|
|
));
|
|
break;
|
|
case 'error':
|
|
onEvent(TerminalEvent(
|
|
'error',
|
|
sequence: sequence,
|
|
code: message['code'] as String?,
|
|
message: message['message'] as String?,
|
|
fatal: message['fatal'] as bool? ?? false,
|
|
));
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|