feat: the terminal, project knowledge, and downloads that can be cancelled
- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and the /api/terminal/ws binary control frames) with a reconnecting socket that replays the server snapshot at the size it was drawn for. - lib/terminal_state.dart: an xterm model plus that socket, kept per workspace on AppState, so closing the panel or switching tabs keeps the shell; the app reattaches when it returns from the background. - lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard, restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT modifiers also apply to what the phone keyboard types. - lib/screens/knowledge_panel.dart: notes, todos and plans from /api/project-context, searchable, with a full page for a plan's Markdown and its raw editor. - Downloads stream with a progress dialog (bytes, total, percent) and a cancel that aborts the request; the save dialog only opens on success. The request asks for `accept-encoding: identity` so Content-Length exists. - MarkdownView renders task lists as ✅/⬜ instead of material_ui's Checkbox, which wants a material_ui Material ancestor the app lacks. - Dialogs own their TextEditingControllers, so closing one no longer trips a framework assertion in debug builds. - 0.3.11 (311).
This commit is contained in:
1 parent
60d02083d3
commit
5f95e2da97
14 files changed
+2347
-57
No files matched your search
+238
-11
@@ -4,7 +4,10 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'models.dart';
|
||||
import 'terminal.dart';
|
||||
import 'transport.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
@@ -291,19 +294,51 @@ class Client {
|
||||
directory: directory, body: {'agent': agent});
|
||||
}
|
||||
|
||||
Future<List<int>> rawFile(String path, {String? directory}) async {
|
||||
Future<List<int>> rawFile(String path, {String? directory}) =>
|
||||
downloadFile(path, directory: directory);
|
||||
|
||||
/// Downloads a file, reporting bytes as they arrive and letting the caller
|
||||
/// cancel. A cancelled download throws [DownloadCancelled] and drops the
|
||||
/// connection instead of reading it to the end.
|
||||
Future<Uint8List> downloadFile(String path,
|
||||
{String? directory,
|
||||
void Function(int received, int? total)? onProgress,
|
||||
CancelToken? cancel}) async {
|
||||
final res = await _request('GET', '/api/fs/raw',
|
||||
query: {
|
||||
'path': path,
|
||||
'allowOutsideWorkspace': 'true',
|
||||
},
|
||||
directory: directory,
|
||||
rawDirectory: true);
|
||||
final bytes = await res.collect();
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, utf8.decode(bytes, allowMalformed: true));
|
||||
rawDirectory: true,
|
||||
// Gzip would leave the response chunked (no total to show) and count
|
||||
// compressed bytes; a download wants the file as it is.
|
||||
noCompression: true);
|
||||
final total = int.tryParse(res.headers['content-length'] ?? '');
|
||||
cancel?.attach(() => res.abort?.call());
|
||||
try {
|
||||
final bytes = BytesBuilder(copy: false);
|
||||
try {
|
||||
await for (final chunk in res.body) {
|
||||
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
|
||||
bytes.add(chunk);
|
||||
onProgress?.call(bytes.length, total);
|
||||
}
|
||||
} catch (error) {
|
||||
// Aborting the request surfaces as a socket error; the caller only
|
||||
// asked to stop.
|
||||
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
|
||||
rethrow;
|
||||
}
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(
|
||||
res.statusCode,
|
||||
utf8.decode(bytes.takeBytes(), allowMalformed: true));
|
||||
}
|
||||
return bytes.takeBytes();
|
||||
} finally {
|
||||
cancel?.detach();
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ files
|
||||
@@ -402,6 +437,192 @@ class Client {
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------ project knowledge
|
||||
|
||||
/// The project id the server derives from a checkout path: `path_` + the
|
||||
/// path base64url-encoded, both ends agreeing on the encoding.
|
||||
static String projectIdFor(String directory) {
|
||||
final normalized = directory
|
||||
.replaceAll('\\', '/')
|
||||
.replaceAll(RegExp(r'/+$'), '')
|
||||
.trim();
|
||||
if (normalized.isEmpty) return '';
|
||||
final encoded = base64Url
|
||||
.encode(utf8.encode(normalized))
|
||||
.replaceAll('=', '');
|
||||
return 'path_$encoded';
|
||||
}
|
||||
|
||||
Future<ProjectContext> projectContext(String projectId,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'GET', '/api/project-context/${Uri.encodeComponent(projectId)}',
|
||||
directory: directory);
|
||||
return ProjectContext.fromJson(r);
|
||||
}
|
||||
|
||||
/// Every mutation answers with the whole context beside the record it
|
||||
/// changed, so the panel refreshes from one reply.
|
||||
static ProjectContext _contextOf(Map<String, dynamic> r) {
|
||||
final context = r['context'];
|
||||
return ProjectContext.fromJson(
|
||||
context is Map<String, dynamic> ? context : r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> createNote(String projectId, String body,
|
||||
{String? planId, String? directory}) async {
|
||||
final r = await _json(
|
||||
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/notes',
|
||||
body: {
|
||||
'body': body,
|
||||
if (planId != null) 'planId': planId,
|
||||
},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> updateNote(
|
||||
String projectId, String noteId,
|
||||
{String? body, bool? pinned, String? directory}) async {
|
||||
final r = await _json(
|
||||
'PATCH',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
|
||||
body: {
|
||||
if (body != null) 'body': body,
|
||||
if (pinned != null) 'pinned': pinned,
|
||||
},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> deleteNote(String projectId, String noteId,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'DELETE',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> createTodo(String projectId, String text,
|
||||
{String? planId, String? directory}) async {
|
||||
final r = await _json(
|
||||
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/todos',
|
||||
body: {
|
||||
'text': text,
|
||||
if (planId != null) 'planId': planId,
|
||||
},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> updateTodo(String projectId, String todoId,
|
||||
{String? text, bool? completed, String? directory}) async {
|
||||
final r = await _json(
|
||||
'PATCH',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
|
||||
body: {
|
||||
if (text != null) 'text': text,
|
||||
if (completed != null) 'completed': completed,
|
||||
},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> deleteTodo(String projectId, String todoId,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'DELETE',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> createPlan(String projectId,
|
||||
{required String title, required String body, String? directory}) async {
|
||||
final r = await _json(
|
||||
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/plans',
|
||||
body: {'title': title, 'body': body},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> savePlan(String projectId, String planId, String raw,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'PUT',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
||||
body: {'raw': raw},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> setPlanPinned(
|
||||
String projectId, String planId, bool pinned,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'PATCH',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
||||
body: {'pinned': pinned},
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectContext> deletePlan(String projectId, String planId,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'DELETE',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
||||
directory: directory);
|
||||
return _contextOf(r);
|
||||
}
|
||||
|
||||
Future<ProjectPlanContent> planContent(String projectId, String planId,
|
||||
{String? directory}) async {
|
||||
final r = await _json(
|
||||
'GET',
|
||||
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
||||
directory: directory);
|
||||
return ProjectPlanContent.fromJson(r);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- terminal
|
||||
|
||||
Future<TerminalSessionInfo> createTerminal(
|
||||
{required String cwd, int cols = 80, int rows = 24}) async {
|
||||
final r = await _json('POST', '/api/terminal/create',
|
||||
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
|
||||
return TerminalSessionInfo.fromJson(r);
|
||||
}
|
||||
|
||||
Future<void> resizeTerminal(String sessionId, int cols, int rows,
|
||||
{String? directory}) async {
|
||||
await _json('POST',
|
||||
'/api/terminal/${Uri.encodeComponent(sessionId)}/resize',
|
||||
body: {'cols': cols, 'rows': rows}, directory: directory);
|
||||
}
|
||||
|
||||
Future<TerminalSessionInfo> restartTerminal(String sessionId,
|
||||
{required String cwd, int cols = 80, int rows = 24}) async {
|
||||
final r = await _json('POST',
|
||||
'/api/terminal/${Uri.encodeComponent(sessionId)}/restart',
|
||||
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
|
||||
return TerminalSessionInfo.fromJson(r);
|
||||
}
|
||||
|
||||
Future<void> closeTerminal(String sessionId, {String? directory}) async {
|
||||
await _json(
|
||||
'DELETE', '/api/terminal/${Uri.encodeComponent(sessionId)}',
|
||||
directory: directory);
|
||||
}
|
||||
|
||||
/// The headers the terminal socket needs (auth, and the workspace the
|
||||
/// server routes the upgrade by).
|
||||
Map<String, String> get eventHeaders => {
|
||||
'user-agent': 'openchamber-native/0.3',
|
||||
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
|
||||
};
|
||||
|
||||
// --------------------------------------------------------------- transport
|
||||
|
||||
Future<Map<String, dynamic>> _json(String method, String path,
|
||||
@@ -409,13 +630,15 @@ class Client {
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false,
|
||||
bool rawDirectory = false}) async {
|
||||
bool rawDirectory = false,
|
||||
bool noCompression = false}) async {
|
||||
final res = await _request(method, path,
|
||||
query: query,
|
||||
body: body,
|
||||
directory: directory,
|
||||
partShells: partShells,
|
||||
rawDirectory: rawDirectory);
|
||||
rawDirectory: rawDirectory,
|
||||
noCompression: noCompression);
|
||||
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
String msg = text;
|
||||
@@ -438,7 +661,8 @@ class Client {
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false,
|
||||
bool rawDirectory = false}) async {
|
||||
bool rawDirectory = false,
|
||||
bool noCompression = false}) async {
|
||||
final headers = <String, String>{
|
||||
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
|
||||
'user-agent': 'openchamber-native/0.3',
|
||||
@@ -452,6 +676,7 @@ class Client {
|
||||
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
|
||||
}
|
||||
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
|
||||
if (noCompression) headers['accept-encoding'] = 'identity';
|
||||
if (path == '/api/event') headers['cache-control'] = 'no-cache';
|
||||
final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
|
||||
if (bodyBytes != null) headers['content-type'] = 'application/json';
|
||||
@@ -462,7 +687,7 @@ class Client {
|
||||
headers: headers,
|
||||
body: bodyBytes,
|
||||
));
|
||||
return _Response(res.status, res.body);
|
||||
return _Response(res.status, res.headers, res.body, res.abort);
|
||||
}
|
||||
|
||||
void close() => transport.close();
|
||||
@@ -470,8 +695,10 @@ class Client {
|
||||
|
||||
class _Response {
|
||||
final int statusCode;
|
||||
final Map<String, String> headers;
|
||||
final Stream<List<int>> body;
|
||||
_Response(this.statusCode, this.body);
|
||||
final void Function()? abort;
|
||||
_Response(this.statusCode, this.headers, this.body, [this.abort]);
|
||||
|
||||
Future<List<int>> collect() =>
|
||||
body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
||||
|
||||
@@ -440,6 +440,185 @@ class FormInfo {
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------- project knowledge
|
||||
|
||||
/// A saved note, as `/api/project-context` stores it.
|
||||
class ProjectNote {
|
||||
final String id;
|
||||
final String body;
|
||||
final int createdAt;
|
||||
final int updatedAt;
|
||||
final String source; // manual | selection | agent
|
||||
final bool pinned;
|
||||
final String? planId;
|
||||
|
||||
const ProjectNote({
|
||||
required this.id,
|
||||
required this.body,
|
||||
this.createdAt = 0,
|
||||
this.updatedAt = 0,
|
||||
this.source = 'manual',
|
||||
this.pinned = false,
|
||||
this.planId,
|
||||
});
|
||||
|
||||
factory ProjectNote.fromJson(Map<String, dynamic> j) => ProjectNote(
|
||||
id: j['id'] as String? ?? '',
|
||||
body: j['body'] as String? ?? '',
|
||||
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
|
||||
source: j['source'] as String? ?? 'manual',
|
||||
pinned: j['pinned'] as bool? ?? false,
|
||||
planId: j['planId'] as String?,
|
||||
);
|
||||
|
||||
String get firstLine {
|
||||
final line = body.split('\n').firstWhere((l) => l.trim().isNotEmpty,
|
||||
orElse: () => '');
|
||||
return line.trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// A todo item. [planId] links it to a plan; [dependsOn] lists the todos of
|
||||
/// the same plan that must be completed first.
|
||||
class ProjectTodo {
|
||||
final String id;
|
||||
final String text;
|
||||
final bool completed;
|
||||
final int createdAt;
|
||||
final String? planId;
|
||||
final List<String> dependsOn;
|
||||
|
||||
const ProjectTodo({
|
||||
required this.id,
|
||||
required this.text,
|
||||
this.completed = false,
|
||||
this.createdAt = 0,
|
||||
this.planId,
|
||||
this.dependsOn = const [],
|
||||
});
|
||||
|
||||
factory ProjectTodo.fromJson(Map<String, dynamic> j) => ProjectTodo(
|
||||
id: j['id'] as String? ?? '',
|
||||
text: j['text'] as String? ?? '',
|
||||
completed: j['completed'] as bool? ?? false,
|
||||
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||
planId: j['planId'] as String?,
|
||||
dependsOn: [
|
||||
for (final d in (j['dependsOn'] as List? ?? []))
|
||||
if (d is String) d,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A plan the project lists: a manifest entry (personal) or a file from the
|
||||
/// team's shared folder.
|
||||
class ProjectPlanLink {
|
||||
final String id;
|
||||
final String file;
|
||||
final String title;
|
||||
final int createdAt;
|
||||
final bool pinned;
|
||||
final String source; // personal | shared
|
||||
final int progressDone;
|
||||
final int progressTotal;
|
||||
final String? sessionId;
|
||||
|
||||
const ProjectPlanLink({
|
||||
required this.id,
|
||||
required this.file,
|
||||
required this.title,
|
||||
this.createdAt = 0,
|
||||
this.pinned = false,
|
||||
this.source = 'personal',
|
||||
this.progressDone = 0,
|
||||
this.progressTotal = 0,
|
||||
this.sessionId,
|
||||
});
|
||||
|
||||
factory ProjectPlanLink.fromJson(Map<String, dynamic> j) {
|
||||
final progress = j['progress'];
|
||||
final session = j['session'];
|
||||
return ProjectPlanLink(
|
||||
id: j['id'] as String? ?? '',
|
||||
file: j['file'] as String? ?? '',
|
||||
title: j['title'] as String? ?? '',
|
||||
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||
pinned: j['pinned'] as bool? ?? false,
|
||||
source: j['source'] as String? ?? 'personal',
|
||||
progressDone:
|
||||
progress is Map ? (progress['done'] as num?)?.toInt() ?? 0 : 0,
|
||||
progressTotal:
|
||||
progress is Map ? (progress['total'] as num?)?.toInt() ?? 0 : 0,
|
||||
sessionId: session is Map ? session['sessionId'] as String? : null,
|
||||
);
|
||||
}
|
||||
|
||||
bool get hasProgress => progressTotal > 0;
|
||||
}
|
||||
|
||||
/// Everything the project knowledge panel shows for one directory.
|
||||
class ProjectContext {
|
||||
final List<ProjectNote> notes;
|
||||
final List<ProjectTodo> todos;
|
||||
final List<ProjectPlanLink> plans;
|
||||
final String? sharedPlansDir;
|
||||
|
||||
const ProjectContext({
|
||||
this.notes = const [],
|
||||
this.todos = const [],
|
||||
this.plans = const [],
|
||||
this.sharedPlansDir,
|
||||
});
|
||||
|
||||
factory ProjectContext.fromJson(Map<String, dynamic> j) => ProjectContext(
|
||||
notes: [
|
||||
for (final n in (j['notes'] as List? ?? []))
|
||||
if (n is Map<String, dynamic>) ProjectNote.fromJson(n),
|
||||
],
|
||||
todos: [
|
||||
for (final t in (j['todos'] as List? ?? []))
|
||||
if (t is Map<String, dynamic>) ProjectTodo.fromJson(t),
|
||||
],
|
||||
plans: [
|
||||
for (final p in (j['plans'] as List? ?? []))
|
||||
if (p is Map<String, dynamic>) ProjectPlanLink.fromJson(p),
|
||||
],
|
||||
sharedPlansDir: j['sharedPlansDir'] as String?,
|
||||
);
|
||||
|
||||
bool get isEmpty => notes.isEmpty && todos.isEmpty && plans.isEmpty;
|
||||
}
|
||||
|
||||
/// A plan as the server reads it back: the link plus its Markdown.
|
||||
class ProjectPlanContent {
|
||||
final String id;
|
||||
final String title;
|
||||
final String body;
|
||||
final String raw;
|
||||
final String? path;
|
||||
final String source;
|
||||
|
||||
const ProjectPlanContent({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.body,
|
||||
this.raw = '',
|
||||
this.path,
|
||||
this.source = 'personal',
|
||||
});
|
||||
|
||||
factory ProjectPlanContent.fromJson(Map<String, dynamic> j) =>
|
||||
ProjectPlanContent(
|
||||
id: j['id'] as String? ?? '',
|
||||
title: j['title'] as String? ?? '',
|
||||
body: j['body'] as String? ?? '',
|
||||
raw: j['raw'] as String? ?? '',
|
||||
path: j['path'] as String?,
|
||||
source: j['source'] as String? ?? 'personal',
|
||||
);
|
||||
}
|
||||
|
||||
class Page<T> {
|
||||
final List<T> data;
|
||||
final String? next;
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
// 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',
|
||||
);
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
-2
@@ -35,7 +35,11 @@ class TransportResponse {
|
||||
final int status;
|
||||
final Map<String, String> headers;
|
||||
final Stream<List<int>> body;
|
||||
const TransportResponse(this.status, this.headers, this.body);
|
||||
|
||||
/// Drops the connection while the body is still being read (a download the
|
||||
/// user cancelled); null when the reply already finished.
|
||||
final void Function()? abort;
|
||||
const TransportResponse(this.status, this.headers, this.body, {this.abort});
|
||||
}
|
||||
|
||||
/// The one seam every request goes through.
|
||||
@@ -43,10 +47,45 @@ abstract class Transport {
|
||||
/// Sends [request], completing when the reply head arrives.
|
||||
Future<TransportResponse> send(TransportRequest request);
|
||||
|
||||
/// Opens a WebSocket on [path] (the terminal stream). Through the same
|
||||
/// sockets as [send], so proxies and certificates keep working.
|
||||
Future<WebSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}});
|
||||
|
||||
/// Releases whatever sockets the transport holds.
|
||||
void close();
|
||||
}
|
||||
|
||||
/// Lets a caller abandon a download: [cancel] aborts the request and makes the
|
||||
/// reader stop at its next chunk.
|
||||
class CancelToken {
|
||||
bool _cancelled = false;
|
||||
void Function()? _abort;
|
||||
|
||||
bool get isCancelled => _cancelled;
|
||||
|
||||
/// Called by the downloader once the request is in flight.
|
||||
void attach(void Function() abort) {
|
||||
_abort = abort;
|
||||
if (_cancelled) abort();
|
||||
}
|
||||
|
||||
void detach() => _abort = null;
|
||||
|
||||
void cancel() {
|
||||
if (_cancelled) return;
|
||||
_cancelled = true;
|
||||
_abort?.call();
|
||||
}
|
||||
}
|
||||
|
||||
/// Thrown by a download the user cancelled.
|
||||
class DownloadCancelled implements Exception {
|
||||
const DownloadCancelled();
|
||||
@override
|
||||
String toString() => '下载已取消';
|
||||
}
|
||||
|
||||
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
|
||||
class ProxyConfig {
|
||||
final String scheme; // http | https | socks5 | socks5h
|
||||
@@ -166,7 +205,20 @@ class DirectTransport implements Transport {
|
||||
res.headers.forEach((name, values) {
|
||||
headers[name.toLowerCase()] = values.join(', ');
|
||||
});
|
||||
return TransportResponse(res.statusCode, headers, res);
|
||||
return TransportResponse(res.statusCode, headers, res,
|
||||
abort: req.abort);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<WebSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}}) {
|
||||
// ws:// is http:// with the upgrade; wss:// checks the same certificates,
|
||||
// so the configured client is reused as it stands.
|
||||
final base = this.base.replace(
|
||||
scheme: this.base.scheme == 'https' ? 'wss' : 'ws');
|
||||
final query = rawQuery ?? '';
|
||||
final uri = base.resolve(path).replace(query: query.isEmpty ? null : query);
|
||||
return WebSocket.connect(uri.toString(), headers: headers, customClient: _http);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
Reference in new issue
Block a user