2026-11-21 02:49:07 +08:00
|
|
|
// 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',
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-22 14:53:33 +08:00
|
|
|
/// 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;
|
|
|
|
|
|
|
|
|
|
const ServerTerminal({
|
|
|
|
|
required this.sessionId,
|
|
|
|
|
this.cwd = '',
|
|
|
|
|
this.status = 'running',
|
|
|
|
|
this.createdAt,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
factory ServerTerminal.fromJson(Map<String, dynamic> j) => ServerTerminal(
|
|
|
|
|
sessionId: j['sessionId'] as String? ?? '',
|
|
|
|
|
cwd: j['cwd'] as String? ?? '',
|
|
|
|
|
status: j['status'] as String? ?? 'running',
|
|
|
|
|
createdAt: (j['createdAt'] as num?)?.toInt(),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 02:49:07 +08:00
|
|
|
/// 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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|