diff --git a/PLAN.md b/PLAN.md index 4365e20..4cbd17f 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,20 @@ --- +## 0.3.11 终端、项目知识与下载进度(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 终端 | 右侧栏「终端」页:`POST /api/terminal/create` 建 PTY(cwd = 会话目录),`/api/terminal/ws` 走二进制控制帧(`0x01` + JSON:hello/attach/write/ping,snapshot/output/restart/exit/error)。渲染用 **xterm 4.0.0**(`Terminal` 模型 + `TerminalView`),断线按 500ms 起指数退避重连、重连后按服务端快照重放(先 `resize` 到快照尺寸再写历史);`/api/terminal/:id/resize` 做 250ms 去抖;App 回前台时自动重连 | +| 底栏 | 仿 Termux 的按键条(横向滚动):CTRL / ALT / SHIFT 修饰键,ESC、TAB、方向键、HOME/END/PGUP/PGDN/DEL,以及 `/ - \| ~ * $ # _ = + : ; " ' ( ) [ ] { } < > ? ! & \ ^ % @`;修饰键对**手机输入法**输入的字符同样生效(在 `onOutput` 里把下一个可打印字符映射成控制字符/ESC 前缀),按一次即清除 | +| 状态 | 状态条显示「运行中 / 正在连接 / 已退出(退出码)/ 连接失败」,并提供键盘、重启、清屏、关闭终端;终端会话按目录保存在 `AppState.terminals`,关面板不断 shell,切换服务器时显式关闭 | +| 项目知识 | 右侧栏「项目知识」页:`/api/project-context/:projectId`(projectId = `path_` + 目录 base64url);笔记(新建/编辑/置顶/删除)、待办(勾选、新建、删除,完成项沉底)、计划(新建、置顶、删除、打开全文);搜索框跨三种记录即时过滤;计划详情是全屏页(Markdown 渲染 + 编辑原文 + 保存) | +| 下载进度 | `/api/fs/raw` 改为流式:`downloadFile` 带 `onProgress` 与 `CancelToken`,请求头 `accept-encoding: identity` 以拿到 `Content-Length`(gzip 会让响应变成 chunked,进度只能是不确定态);下载中弹「正在下载」对话框显示已下载/总量/百分比,取消即中止连接并丢弃结果;完成后才弹保存对话框 | +| 修复 | `MarkdownView` 里的任务列表不再用 `material_ui` 的 Checkbox(它会找 `material_ui` 的 Material 祖先,应用里没有),改为 `✅`/`⬜` 文本;对话框里的 `TextEditingController` 改由对话框自身持有,避免关闭动画期间 dispose 触发框架断言 | +| 版本 | **0.3.11(code 311)** | + +--- + ## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 748c9eb..bacaa35 100644 --- a/README.md +++ b/README.md @@ -5,16 +5,18 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.3.10 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.11 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live events, chat with streaming Markdown and full history paging, tool steps grouped per turn (icon, one-line summary, foldable run) with image previews, a context usage ring with a detail sheet, model/agent switching (Build/Plan only, current one checked), copy / fork / revert, attachments (photos/files, kept -after a reload), the agent's native forms, permissions. A phone opens the -session list as the left drawer and a wide window (tablet, desktop) shows it -beside the chat. Android 7.0 (API 24)+, plus a Linux desktop target used for -local testing. +after a reload), the agent's native forms, permissions. The files sidebar also +carries the project knowledge (notes, todos, plans) and a full terminal with a +Termux-style key bar; downloads show their progress and can be cancelled. A +phone opens the session list as the left drawer and a wide window (tablet, +desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop +target used for local testing. ## What is here @@ -23,7 +25,8 @@ local testing. | `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, forms, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; every request goes through `Transport` (today `DirectTransport`: HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback`), so a relay tunnel only adds an implementation | | `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) | | `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding | -| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar); the message list is reversed so older pages grow above without moving the viewport | +| `lib/terminal_state.dart` | The terminal session: an xterm model plus the `/api/terminal/ws` socket (binary control frames), kept per workspace so closing the panel keeps the shell | +| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport | | `lib/widgets/` | The context usage ring | Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer diff --git a/lib/api/client.dart b/lib/api/client.dart index 7427dea..4cf8c4f 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -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> rawFile(String path, {String? directory}) async { + Future> 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 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(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 r) { + final context = r['context']; + return ProjectContext.fromJson( + context is Map ? context : r); + } + + Future 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 get eventHeaders => { + 'user-agent': 'openchamber-native/0.3', + if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token', + }; + // --------------------------------------------------------------- transport Future> _json(String method, String path, @@ -409,13 +630,15 @@ class Client { Map? 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? body, String? directory, bool partShells = false, - bool rawDirectory = false}) async { + bool rawDirectory = false, + bool noCompression = false}) async { final headers = { '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 headers; final Stream> body; - _Response(this.statusCode, this.body); + final void Function()? abort; + _Response(this.statusCode, this.headers, this.body, [this.abort]); Future> collect() => body.fold>([], (a, b) => a..addAll(b)); diff --git a/lib/api/models.dart b/lib/api/models.dart index 9066cba..2f0be99 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -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 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 dependsOn; + + const ProjectTodo({ + required this.id, + required this.text, + this.completed = false, + this.createdAt = 0, + this.planId, + this.dependsOn = const [], + }); + + factory ProjectTodo.fromJson(Map 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 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 notes; + final List todos; + final List plans; + final String? sharedPlansDir; + + const ProjectContext({ + this.notes = const [], + this.todos = const [], + this.plans = const [], + this.sharedPlansDir, + }); + + factory ProjectContext.fromJson(Map j) => ProjectContext( + notes: [ + for (final n in (j['notes'] as List? ?? [])) + if (n is Map) ProjectNote.fromJson(n), + ], + todos: [ + for (final t in (j['todos'] as List? ?? [])) + if (t is Map) ProjectTodo.fromJson(t), + ], + plans: [ + for (final p in (j['plans'] as List? ?? [])) + if (p is Map) 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 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 { final List data; final String? next; diff --git a/lib/api/terminal.dart b/lib/api/terminal.dart new file mode 100644 index 0000000..0ca6272 --- /dev/null +++ b/lib/api/terminal.dart @@ -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 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 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 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 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 message) { + final socket = _socket; + if (socket == null) return; + final bytes = [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 || raw.isEmpty) return; + final Map message; + try { + final tag = raw.first; + final bytes = tag == 1 ? raw.sublist(1) : raw; + final decoded = jsonDecode(utf8.decode(bytes)); + if (decoded is! Map) 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; + } + } +} diff --git a/lib/api/transport.dart b/lib/api/transport.dart index 003002a..81d6556 100644 --- a/lib/api/transport.dart +++ b/lib/api/transport.dart @@ -35,7 +35,11 @@ class TransportResponse { final int status; final Map headers; final Stream> 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 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(String path, + {String? rawQuery, Map 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(String path, + {String? rawQuery, Map 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 diff --git a/lib/screens/files_panel.dart b/lib/screens/files_panel.dart index 4b3a96e..90aa016 100644 --- a/lib/screens/files_panel.dart +++ b/lib/screens/files_panel.dart @@ -9,8 +9,11 @@ import 'package:flutter/material.dart'; import '../api/client.dart'; import '../api/models.dart'; +import '../api/transport.dart'; import '../state.dart'; import '../widgets/markdown_view.dart'; +import 'knowledge_panel.dart'; +import 'terminal_panel.dart'; Future showFilesPanel( BuildContext context, AppState app, Session session) { @@ -289,16 +292,28 @@ class _FilesPanelState extends State { final client = _client; final path = _previewPath; if (client == null || path == null) return; + // A file already in memory needs no progress; the rest stream with one. + var bytes = _previewBytes; + if (bytes == null) { + bytes = await showDialog( + context: context, + barrierDismissible: false, + builder: (_) => _DownloadDialog( + name: _previewName, + start: (onProgress, cancel) => client.downloadFile(path, + directory: _root, onProgress: onProgress, cancel: cancel), + ), + ); + } + if (bytes == null || !mounted) return; try { - final bytes = _previewBytes ?? - Uint8List.fromList(await client.rawFile(path, directory: _root)); final uri = await FilePicker.saveFile( fileName: _previewName, bytes: bytes, ); if (uri != null) _toast('已保存'); } catch (e) { - _toast('下载失败:$e'); + _toast('保存失败:$e'); } } @@ -516,46 +531,15 @@ class _FilesPanelState extends State { } switch (_tab) { case 1: - return _placeholder(theme, Icons.menu_book_outlined, '项目知识', - '笔记、待办与计划会在这里。'); + return KnowledgePanel(app: widget.app, directory: _root); case 2: - return _placeholder( - theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。'); + return TerminalPanel(app: widget.app, directory: _root); default: if (_previewPath != null) return _previewBody(theme); return _browser(theme); } } - Widget _placeholder( - ThemeData theme, IconData icon, String title, String note) { - return Center( - child: Padding( - padding: const EdgeInsets.all(32), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icon, size: 40, color: theme.hintColor), - const SizedBox(height: 12), - Text(title, - style: const TextStyle( - fontSize: 16, fontWeight: FontWeight.w600)), - const SizedBox(height: 6), - Text(note, - textAlign: TextAlign.center, - style: TextStyle(fontSize: 13, color: theme.hintColor)), - const SizedBox(height: 10), - Chip( - label: const Text('即将支持'), - visualDensity: VisualDensity.compact, - side: BorderSide(color: theme.dividerColor), - ), - ], - ), - ), - ); - } - Widget _browser(ThemeData theme) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -935,3 +919,115 @@ class _FilesPanelState extends State { return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; } } + +/// Streams one download and shows its progress; 取消 aborts the request and +/// the dialog closes with no bytes, so nothing is saved. +class _DownloadDialog extends StatefulWidget { + final String name; + final Future Function( + void Function(int received, int? total) onProgress, + CancelToken cancel) start; + + const _DownloadDialog({required this.name, required this.start}); + + @override + State<_DownloadDialog> createState() => _DownloadDialogState(); +} + +class _DownloadDialogState extends State<_DownloadDialog> { + final CancelToken _cancel = CancelToken(); + int _received = 0; + int? _total; + bool _cancelling = false; + String? _error; + int _lastPaint = 0; + + @override + void initState() { + super.initState(); + _run(); + } + + Future _run() async { + try { + final bytes = await widget.start((received, total) { + if (!mounted) return; + // Chunks arrive every few dozen KB; repaint a few times a second at + // most, and always on the last one. + final now = DateTime.now().millisecondsSinceEpoch; + if (total != null && received < total && now - _lastPaint < 80) return; + _lastPaint = now; + setState(() { + _received = received; + _total = total; + }); + }, _cancel); + if (mounted) Navigator.of(context).pop(bytes); + } on DownloadCancelled { + if (mounted) Navigator.of(context).pop(); + } catch (error) { + if (!mounted) return; + setState(() => _error = error is ApiError ? error.message : '$error'); + } + } + + String _size(int bytes) { + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB'; + return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final total = _total; + final fraction = total != null && total > 0 + ? (_received / total).clamp(0.0, 1.0) + : null; + return AlertDialog( + title: const Text('正在下载'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 13)), + const SizedBox(height: 12), + if (_error == null) ...[ + LinearProgressIndicator(value: fraction), + const SizedBox(height: 8), + Text( + total != null + ? '${_size(_received)} / ${_size(total)}' + '(${(fraction! * 100).toStringAsFixed(0)}%)' + : '已下载 ${_size(_received)}', + style: TextStyle(fontSize: 12, color: theme.hintColor), + ), + ] else + Text(_error!, + style: + TextStyle(fontSize: 12.5, color: theme.colorScheme.error)), + ], + ), + actions: [ + if (_error == null) + TextButton( + onPressed: _cancelling + ? null + : () { + setState(() => _cancelling = true); + _cancel.cancel(); + }, + child: Text(_cancelling ? '正在取消…' : '取消'), + ) + else + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('关闭'), + ), + ], + ); + } +} diff --git a/lib/screens/knowledge_panel.dart b/lib/screens/knowledge_panel.dart new file mode 100644 index 0000000..d136ed6 --- /dev/null +++ b/lib/screens/knowledge_panel.dart @@ -0,0 +1,842 @@ +// The project knowledge tab: notes, todos and plans stored by the server in +// the project context (`/api/project-context`), with search across all three. +import 'package:flutter/material.dart'; + +import '../api/client.dart'; +import '../api/models.dart'; +import '../state.dart'; +import '../widgets/markdown_view.dart'; + +class KnowledgePanel extends StatefulWidget { + final AppState app; + final String directory; + const KnowledgePanel({super.key, required this.app, required this.directory}); + + @override + State createState() => _KnowledgePanelState(); +} + +class _KnowledgePanelState extends State { + ProjectContext? _context; + bool _loading = true; + String? _error; + int _section = 0; + String _query = ''; + final TextEditingController _search = TextEditingController(); + + String get _projectId => Client.projectIdFor(widget.directory); + Client? get _client => widget.app.client; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _search.dispose(); + super.dispose(); + } + + Future _load() async { + final client = _client; + if (client == null || _projectId.isEmpty) { + setState(() { + _loading = false; + _error = '这个会话没有关联目录'; + }); + return; + } + setState(() { + _loading = true; + _error = null; + }); + try { + final context = await client.projectContext(_projectId, + directory: widget.directory); + if (!mounted) return; + setState(() { + _context = context; + _loading = false; + }); + } catch (error) { + if (!mounted) return; + setState(() { + _loading = false; + _error = '$error'; + }); + } + } + + /// Applies a mutation's fresh context without a second round trip. + void _apply(ProjectContext context) { + if (!mounted) return; + setState(() => _context = context); + } + + void _fail(Object error) { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('$error'))); + } + + bool _matches(Iterable fields) { + final query = _query.trim().toLowerCase(); + if (query.isEmpty) return true; + return fields.any((field) => field.toLowerCase().contains(query)); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 4, 0), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _search, + onChanged: (value) => setState(() => _query = value), + style: const TextStyle(fontSize: 13), + decoration: InputDecoration( + isDense: true, + hintText: '搜索笔记、待办与计划', + prefixIcon: const Icon(Icons.search, size: 18), + suffixIcon: _query.isEmpty + ? null + : IconButton( + icon: const Icon(Icons.close, size: 16), + onPressed: () { + _search.clear(); + setState(() => _query = ''); + }, + ), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + IconButton( + tooltip: '刷新', + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.refresh, size: 20), + onPressed: _load, + ), + ], + ), + ), + _sections(theme), + Expanded(child: _body(theme)), + ], + ); + } + + Widget _sections(ThemeData theme) { + final context_ = _context; + final counts = [ + context_?.notes.length ?? 0, + context_?.todos.length ?? 0, + context_?.plans.length ?? 0, + ]; + const names = ['笔记', '待办', '计划']; + return Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 6), + child: SegmentedButton( + showSelectedIcon: false, + style: const ButtonStyle( + visualDensity: VisualDensity.compact, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + segments: [ + for (var i = 0; i < names.length; i++) + ButtonSegment(value: i, label: Text('${names[i]} ${counts[i]}')), + ], + selected: {_section}, + onSelectionChanged: (value) => setState(() => _section = value.first), + ), + ); + } + + Widget _body(ThemeData theme) { + if (_loading) return const Center(child: CircularProgressIndicator()); + if (_error != null) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_error!, + textAlign: TextAlign.center, + style: TextStyle(color: theme.colorScheme.error, fontSize: 13)), + const SizedBox(height: 8), + FilledButton(onPressed: _load, child: const Text('重试')), + ], + ), + ), + ); + } + switch (_section) { + case 1: + return _todos(theme); + case 2: + return _plans(theme); + default: + return _notes(theme); + } + } + + // --------------------------------------------------------------- notes + + Widget _notes(ThemeData theme) { + final notes = (_context?.notes ?? []) + .where((note) => _matches([note.body])) + .toList() + ..sort((a, b) { + if (a.pinned != b.pinned) return a.pinned ? -1 : 1; + return b.updatedAt.compareTo(a.updatedAt); + }); + return Column( + children: [ + _sectionHeader(theme, '${notes.length} 条笔记', '新建笔记', _addNote), + Expanded( + child: notes.isEmpty + ? _empty(theme, Icons.sticky_note_2_outlined, + _query.isEmpty ? '还没有笔记' : '没有匹配的笔记') + : ListView.builder( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + itemCount: notes.length, + itemBuilder: (context, index) { + final note = notes[index]; + return _noteCard(theme, note); + }, + ), + ), + ], + ); + } + + Widget _noteCard(ThemeData theme, ProjectNote note) { + final scheme = theme.colorScheme; + return Card( + margin: const EdgeInsets.only(bottom: 8), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () => _editNote(note), + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + note.body.trim(), + maxLines: 5, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 13.5, height: 1.35), + ), + const SizedBox(height: 4), + Row( + children: [ + if (note.pinned) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.push_pin, + size: 12, color: scheme.primary), + ), + Text( + _stamp(note.updatedAt), + style: + TextStyle(fontSize: 11, color: theme.hintColor), + ), + ], + ), + ], + ), + ), + PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + onSelected: (value) async { + final client = _client; + if (client == null) return; + try { + switch (value) { + case 'edit': + await _editNote(note); + break; + case 'pin': + _apply(await client.updateNote( + _projectId, note.id, + pinned: !note.pinned, directory: widget.directory)); + break; + case 'delete': + _apply(await client.deleteNote(_projectId, note.id, + directory: widget.directory)); + break; + } + } catch (error) { + _fail(error); + } + }, + itemBuilder: (_) => [ + const PopupMenuItem(value: 'edit', child: Text('编辑')), + PopupMenuItem( + value: 'pin', child: Text(note.pinned ? '取消置顶' : '置顶')), + const PopupMenuItem(value: 'delete', child: Text('删除')), + ], + ), + ], + ), + ), + ), + ); + } + + // --------------------------------------------------------------- todos + + Widget _todos(ThemeData theme) { + final todos = (_context?.todos ?? []) + .where((todo) => _matches([todo.text])) + .toList(); + final done = todos.where((todo) => todo.completed).length; + return Column( + children: [ + _sectionHeader(theme, '$done/${todos.length} 已完成', '新建待办', _addTodo), + Expanded( + child: todos.isEmpty + ? _empty(theme, Icons.checklist, + _query.isEmpty ? '还没有待办' : '没有匹配的待办') + : ListView.builder( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 12), + itemCount: todos.length, + itemBuilder: (context, index) { + final todo = todos[index]; + return CheckboxListTile( + dense: true, + value: todo.completed, + onChanged: (value) => _toggleTodo(todo, value ?? false), + controlAffinity: ListTileControlAffinity.leading, + title: Text( + todo.text, + style: TextStyle( + fontSize: 13.5, + decoration: todo.completed + ? TextDecoration.lineThrough + : null, + color: todo.completed ? theme.hintColor : null, + ), + ), + secondary: PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + onSelected: (value) async { + final client = _client; + if (client == null) return; + try { + if (value == 'delete') { + _apply(await client.deleteTodo( + _projectId, todo.id, + directory: widget.directory)); + } + } catch (error) { + _fail(error); + } + }, + itemBuilder: (_) => const [ + PopupMenuItem(value: 'delete', child: Text('删除')), + ], + ), + ); + }, + ), + ), + ], + ); + } + + Future _toggleTodo(ProjectTodo todo, bool completed) async { + final client = _client; + if (client == null) return; + try { + _apply(await client.updateTodo(_projectId, todo.id, + completed: completed, directory: widget.directory)); + } catch (error) { + _fail(error); + } + } + + // --------------------------------------------------------------- plans + + Widget _plans(ThemeData theme) { + final plans = (_context?.plans ?? []) + .where((plan) => _matches([plan.title, plan.file])) + .toList() + ..sort((a, b) { + if (a.pinned != b.pinned) return a.pinned ? -1 : 1; + return b.createdAt.compareTo(a.createdAt); + }); + return Column( + children: [ + _sectionHeader(theme, '${plans.length} 份计划', '新建计划', _newPlan), + Expanded( + child: plans.isEmpty + ? _empty(theme, Icons.description_outlined, + _query.isEmpty ? '还没有计划' : '没有匹配的计划') + : ListView.builder( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 12), + itemCount: plans.length, + itemBuilder: (context, index) => + _planTile(theme, plans[index]), + ), + ), + ], + ); + } + + Widget _planTile(ThemeData theme, ProjectPlanLink plan) { + final scheme = theme.colorScheme; + return Card( + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + dense: true, + title: Row( + children: [ + if (plan.pinned) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.push_pin, size: 13, color: scheme.primary), + ), + Expanded( + child: Text(plan.title.isEmpty ? plan.file : plan.title, + maxLines: 2, overflow: TextOverflow.ellipsis), + ), + ], + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (plan.hasProgress) ...[ + const SizedBox(height: 4), + Row( + children: [ + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(2), + child: LinearProgressIndicator( + value: plan.progressDone / plan.progressTotal, + minHeight: 4, + backgroundColor: scheme.surfaceContainerHighest, + ), + ), + ), + const SizedBox(width: 6), + Text('${plan.progressDone}/${plan.progressTotal}', + style: + TextStyle(fontSize: 11, color: theme.hintColor)), + ], + ), + ], + const SizedBox(height: 2), + Text( + plan.source == 'shared' ? '团队共享' : '个人', + style: TextStyle(fontSize: 11, color: theme.hintColor), + ), + ], + ), + trailing: PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + onSelected: (value) async { + final client = _client; + if (client == null) return; + try { + switch (value) { + case 'pin': + _apply(await client.setPlanPinned( + _projectId, plan.id, !plan.pinned, + directory: widget.directory)); + break; + case 'delete': + _apply(await client.deletePlan(_projectId, plan.id, + directory: widget.directory)); + break; + } + } catch (error) { + _fail(error); + } + }, + itemBuilder: (_) => [ + PopupMenuItem( + value: 'pin', child: Text(plan.pinned ? '取消置顶' : '置顶')), + const PopupMenuItem(value: 'delete', child: Text('删除')), + ], + ), + onTap: () => _viewPlan(plan), + ), + ); + } + + // -------------------------------------------------------------- dialogs + + Widget _sectionHeader( + ThemeData theme, String summary, String action, VoidCallback onTap) { + return Padding( + padding: const EdgeInsets.fromLTRB(14, 0, 8, 2), + child: Row( + children: [ + Expanded( + child: Text(summary, + style: TextStyle(fontSize: 12, color: theme.hintColor)), + ), + TextButton.icon( + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 32), + ), + onPressed: onTap, + icon: const Icon(Icons.add, size: 16), + label: Text(action, style: const TextStyle(fontSize: 12.5)), + ), + ], + ), + ); + } + + Widget _empty(ThemeData theme, IconData icon, String text) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 36, color: theme.hintColor), + const SizedBox(height: 8), + Text(text, style: TextStyle(fontSize: 13, color: theme.hintColor)), + ], + ), + ); + } + + Future _addNote() => _editNote(null); + + Future _editNote(ProjectNote? note) async { + final text = await showDialog( + context: context, + builder: (_) => _TextPromptDialog( + title: note == null ? '新建笔记' : '编辑笔记', + hint: '记点什么,供之后的会话参考', + initial: note?.body ?? '', + maxLength: 3000, + maxLines: 10, + minLines: 4, + action: '保存', + ), + ); + if (text == null || text.isEmpty) return; + final client = _client; + if (client == null) return; + try { + if (note == null) { + _apply(await client.createNote(_projectId, text, + directory: widget.directory)); + } else { + _apply(await client.updateNote(_projectId, note.id, + body: text, directory: widget.directory)); + } + } catch (error) { + _fail(error); + } + } + + Future _addTodo() async { + final text = await showDialog( + context: context, + builder: (_) => const _TextPromptDialog( + title: '新建待办', + hint: '要做什么', + maxLength: 1000, + maxLines: 1, + minLines: 1, + action: '保存', + ), + ); + if (text == null || text.isEmpty) return; + final client = _client; + if (client == null) return; + try { + _apply(await client.createTodo(_projectId, text, + directory: widget.directory)); + } catch (error) { + _fail(error); + } + } + + Future _newPlan() async { + final result = await showDialog<(String, String)>( + context: context, + builder: (_) => const _NewPlanDialog(), + ); + if (result == null || result.$2.trim().isEmpty) return; + final client = _client; + if (client == null) return; + try { + _apply(await client.createPlan(_projectId, + title: result.$1, body: result.$2, directory: widget.directory)); + } catch (error) { + _fail(error); + } + } + + Future _viewPlan(ProjectPlanLink plan) async { + final client = _client; + if (client == null) return; + ProjectPlanContent content; + try { + content = await client.planContent(_projectId, plan.id, + directory: widget.directory); + } catch (error) { + _fail(error); + return; + } + if (!mounted) return; + // A full page, not a dialog: a plan is long, and a page keeps the editor + // and the scroll view in their own hit-testable surface. + await Navigator.of(context).push(MaterialPageRoute( + builder: (context) => _PlanPage( + title: content.title.isEmpty ? plan.file : content.title, + raw: content.raw, + onSave: (raw) async { + _apply(await client.savePlan(_projectId, plan.id, raw, + directory: widget.directory)); + }, + ), + )); + } + + String _stamp(int millis) { + if (millis <= 0) return ''; + final time = DateTime.fromMillisecondsSinceEpoch(millis); + String two(int value) => value.toString().padLeft(2, '0'); + return '${time.year}-${two(time.month)}-${two(time.day)} ' + '${two(time.hour)}:${two(time.minute)}'; + } +} + +/// One plan, rendered; 编辑 swaps in the raw Markdown, 保存 writes it back. +class _PlanPage extends StatefulWidget { + final String title; + final String raw; + final Future Function(String raw) onSave; + + const _PlanPage({ + required this.title, + required this.raw, + required this.onSave, + }); + + @override + State<_PlanPage> createState() => _PlanPageState(); +} + +class _PlanPageState extends State<_PlanPage> { + late final TextEditingController _controller = + TextEditingController(text: widget.raw); + bool _editing = false; + bool _saving = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _save() async { + setState(() => _saving = true); + try { + await widget.onSave(_controller.text); + if (mounted) setState(() => _editing = false); + } catch (error) { + if (mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('$error'))); + } + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis), + actions: [ + if (_editing) + TextButton( + onPressed: _saving ? null : () => setState(() => _editing = false), + child: const Text('取消'), + ), + TextButton( + onPressed: _saving + ? null + : (_editing ? _save : () => setState(() => _editing = true)), + child: Text(_saving ? '保存中…' : (_editing ? '保存' : '编辑')), + ), + ], + ), + body: _editing + ? Padding( + padding: const EdgeInsets.all(12), + child: TextField( + controller: _controller, + expands: true, + maxLines: null, + minLines: null, + textAlignVertical: TextAlignVertical.top, + style: const TextStyle(fontFamily: 'monospace', fontSize: 13), + decoration: const InputDecoration( + border: OutlineInputBorder(), + contentPadding: EdgeInsets.all(10), + ), + ), + ) + : SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: MarkdownView(_controller.text, fontSize: 14.5), + ), + ); + } +} + +/// A one-field prompt that owns its controller (a controller created outside +/// a dialog is disposed while the dialog is still animating out, which trips a +/// framework assertion in debug builds). +class _TextPromptDialog extends StatefulWidget { + final String title; + final String hint; + final String initial; + final int maxLength; + final int maxLines; + final int minLines; + final String action; + + const _TextPromptDialog({ + required this.title, + required this.hint, + required this.maxLength, + required this.maxLines, + required this.minLines, + required this.action, + this.initial = '', + }); + + @override + State<_TextPromptDialog> createState() => _TextPromptDialogState(); +} + +class _TextPromptDialogState extends State<_TextPromptDialog> { + late final TextEditingController _controller = + TextEditingController(text: widget.initial); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(widget.title), + content: SizedBox( + width: double.maxFinite, + child: TextField( + controller: _controller, + autofocus: true, + maxLength: widget.maxLength, + maxLines: widget.maxLines, + minLines: widget.minLines, + decoration: InputDecoration( + hintText: widget.hint, + border: const OutlineInputBorder(), + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消')), + FilledButton( + onPressed: () => Navigator.pop(context, _controller.text.trim()), + child: Text(widget.action)), + ], + ); + } +} + +/// Title plus Markdown body, as one dialog. +class _NewPlanDialog extends StatefulWidget { + const _NewPlanDialog(); + + @override + State<_NewPlanDialog> createState() => _NewPlanDialogState(); +} + +class _NewPlanDialogState extends State<_NewPlanDialog> { + final TextEditingController _title = TextEditingController(); + final TextEditingController _body = TextEditingController(); + + @override + void dispose() { + _title.dispose(); + _body.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('新建计划'), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _title, + autofocus: true, + maxLength: 160, + decoration: const InputDecoration( + labelText: '标题', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 8), + TextField( + controller: _body, + maxLines: 10, + minLines: 6, + decoration: const InputDecoration( + alignLabelWithHint: true, + labelText: '计划正文(Markdown)', + border: OutlineInputBorder(), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消')), + FilledButton( + onPressed: () => Navigator.pop( + context, (_title.text.trim(), _body.text)), + child: const Text('创建')), + ], + ); + } +} diff --git a/lib/screens/terminal_panel.dart b/lib/screens/terminal_panel.dart new file mode 100644 index 0000000..2b8b4c5 --- /dev/null +++ b/lib/screens/terminal_panel.dart @@ -0,0 +1,279 @@ +// The terminal tab: xterm renders the PTY, a status bar offers restart and +// close, and the key bar below sends what a phone keyboard cannot (Esc, Tab, +// Ctrl, arrows, punctuation), the way Termux does. +import 'package:flutter/material.dart'; +import 'package:xterm/xterm.dart'; + +import '../api/terminal.dart'; +import '../state.dart'; +import '../terminal_state.dart'; + +/// A light palette, so the terminal does not turn into a black hole in the +/// light theme. (xterm ships only dark ones.) +const _lightTheme = TerminalTheme( + cursor: Color(0xFF3A3A3A), + selection: Color(0x553A6EA5), + foreground: Color(0xFF1F1F1F), + background: Color(0xFFFFFFFF), + black: Color(0xFF000000), + red: Color(0xFFCD3131), + green: Color(0xFF0D7A44), + yellow: Color(0xFF7A6200), + blue: Color(0xFF1B5FA6), + magenta: Color(0xFFA626A4), + cyan: Color(0xFF0E7490), + white: Color(0xFFBDBDBD), + brightBlack: Color(0xFF666666), + brightRed: Color(0xFFD73A49), + brightGreen: Color(0xFF1A8A4E), + brightYellow: Color(0xFF8A6D00), + brightBlue: Color(0xFF2E6FBF), + brightMagenta: Color(0xFFB23BB0), + brightCyan: Color(0xFF12859B), + brightWhite: Color(0xFFEEEEEE), + searchHitBackground: Color(0xFFFFF176), + searchHitBackgroundCurrent: Color(0xFFAED581), + searchHitForeground: Color(0xFF000000), +); + +class TerminalPanel extends StatefulWidget { + final AppState app; + final String directory; + const TerminalPanel({super.key, required this.app, this.directory = ''}); + + @override + State createState() => _TerminalPanelState(); +} + +class _TerminalPanelState extends State { + TerminalSessionState? _terminal; + final FocusNode _focus = FocusNode(); + + @override + void initState() { + super.initState(); + _terminal = widget.app.terminalFor(widget.directory); + _terminal!.ensureOpen(); + } + + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + TerminalSessionState get _t => _terminal!; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return ListenableBuilder( + listenable: _t, + builder: (context, _) { + return Column( + children: [ + _statusBar(theme), + Expanded( + child: ColoredBox( + color: theme.brightness == Brightness.dark + ? const Color(0xFF1E1E1E) + : Colors.white, + child: TerminalView( + _t.model, + focusNode: _focus, + theme: theme.brightness == Brightness.dark + ? TerminalThemes.defaultTheme + : _lightTheme, + textStyle: const TerminalStyle( + fontSize: 13, + height: 1.25, + fontFamily: 'monospace', + ), + padding: const EdgeInsets.fromLTRB(8, 6, 8, 6), + keyboardType: TextInputType.text, + deleteDetection: true, + backgroundOpacity: 1, + ), + ), + ), + _keyBar(theme), + ], + ); + }, + ); + } + + Widget _statusBar(ThemeData theme) { + final scheme = theme.colorScheme; + final (label, color) = switch (_t.link) { + TerminalLinkState.idle => ('未启动', theme.hintColor), + TerminalLinkState.creating => ('正在创建…', theme.hintColor), + TerminalLinkState.connecting => ('正在连接…', theme.hintColor), + TerminalLinkState.reconnecting => ('连接中断,正在重连…', scheme.error), + TerminalLinkState.open => ('运行中', scheme.primary), + TerminalLinkState.exited => (_t.detail ?? '已退出', theme.hintColor), + TerminalLinkState.error => (_t.detail ?? '连接失败', scheme.error), + }; + return Container( + padding: const EdgeInsets.fromLTRB(12, 2, 4, 2), + child: Row( + children: [ + Icon(Icons.circle, size: 8, color: color), + const SizedBox(width: 6), + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: color), + ), + ), + IconButton( + tooltip: '键盘', + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.keyboard_outlined, size: 18), + onPressed: () => _focus.requestFocus(), + ), + IconButton( + tooltip: '重新启动', + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.restart_alt, size: 18), + onPressed: _t.link == TerminalLinkState.exited || + _t.link == TerminalLinkState.error + ? _restart + : _t.isRunning + ? _restart + : null, + ), + PopupMenuButton( + tooltip: '更多', + icon: const Icon(Icons.more_vert, size: 18), + onSelected: (value) { + switch (value) { + case 'clear': + _t.model.write('\x1b[2J\x1b[H'); + break; + case 'close': + _closeSession(); + break; + } + }, + itemBuilder: (_) => const [ + PopupMenuItem(value: 'clear', child: Text('清屏')), + PopupMenuItem(value: 'close', child: Text('关闭终端')), + ], + ), + ], + ), + ); + } + + Future _restart() async { + if (_t.link == TerminalLinkState.exited || + _t.link == TerminalLinkState.error) { + // A dead session cannot restart in place; a fresh one replaces it. + await _t.closeSession(); + await _t.ensureOpen(); + return; + } + await _t.restart(); + } + + Future _closeSession() async { + await _t.closeSession(); + if (mounted) await _t.ensureOpen(); + } + + // ------------------------------------------------------------- key bar + + static const _symbols = [ + '/', '-', '|', '~', '*', r'$', '#', '_', '=', '+', ':', ';', + '"', "'", '(', ')', '[', ']', '{', '}', '<', '>', '?', '!', + '&', r'\', '^', '%', '@', + ]; + + Widget _keyBar(ThemeData theme) { + return Container( + height: 46, + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHigh, + border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)), + ), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Row( + children: [ + _key('CTRL', active: _t.ctrl, onTap: _t.toggleCtrl), + _key('ALT', active: _t.alt, onTap: _t.toggleAlt), + _key('SHIFT', active: _t.shift, onTap: _t.toggleShift), + _divider(theme), + _key('ESC', onTap: () => _sendKey(TerminalKey.escape)), + _key('TAB', onTap: () => _sendKey(TerminalKey.tab)), + _divider(theme), + _key('←', onTap: () => _sendKey(TerminalKey.arrowLeft)), + _key('↑', onTap: () => _sendKey(TerminalKey.arrowUp)), + _key('↓', onTap: () => _sendKey(TerminalKey.arrowDown)), + _key('→', onTap: () => _sendKey(TerminalKey.arrowRight)), + _divider(theme), + _key('HOME', onTap: () => _sendKey(TerminalKey.home)), + _key('END', onTap: () => _sendKey(TerminalKey.end)), + _key('PGUP', onTap: () => _sendKey(TerminalKey.pageUp)), + _key('PGDN', onTap: () => _sendKey(TerminalKey.pageDown)), + _key('DEL', onTap: () => _sendKey(TerminalKey.delete)), + _divider(theme), + for (final symbol in _symbols) + _key(symbol, onTap: () => _sendText(symbol)), + ], + ), + ), + ); + } + + Widget _divider(ThemeData theme) => Container( + width: 1, + height: 20, + margin: const EdgeInsets.symmetric(horizontal: 4), + color: theme.dividerColor, + ); + + Widget _key(String label, + {bool active = false, required VoidCallback onTap}) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 8), + padding: const EdgeInsets.symmetric(horizontal: 10), + alignment: Alignment.center, + constraints: const BoxConstraints(minWidth: 34), + decoration: BoxDecoration( + color: active + ? scheme.primary.withValues(alpha: 0.22) + : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(7), + border: Border.all( + color: active ? scheme.primary : Colors.transparent, width: 1), + ), + child: Text( + label, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 12, + fontWeight: active ? FontWeight.w700 : FontWeight.w500, + color: active ? scheme.primary : scheme.onSurface, + ), + ), + ), + ); + } + + // The terminal state applies the pending modifiers (and clears them) as the + // text leaves for the PTY, so both the bar and the phone keyboard take them. + void _sendKey(TerminalKey key) => + _t.model.keyInput(key, ctrl: _t.ctrl, alt: _t.alt, shift: _t.shift); + + void _sendText(String text) => _t.model.textInput(text); +} diff --git a/lib/state.dart b/lib/state.dart index 739ac94..be820f5 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -10,6 +10,7 @@ import 'package:flutter/foundation.dart'; import 'api/client.dart'; import 'api/models.dart'; import 'storage.dart'; +import 'terminal_state.dart'; const _eventTypes = [ 'session.created', @@ -67,6 +68,13 @@ class AppState extends ChangeNotifier { ChatState? chat; + /// Terminals by workspace directory: switching sessions or tabs keeps the + /// shell alive, and each directory gets its own. + final Map terminals = {}; + + TerminalSessionState terminalFor(String directory) => terminals.putIfAbsent( + directory, () => TerminalSessionState(this, directory)); + /// Public way to signal UI changes (notifyListeners is protected). void touch() => notifyListeners(); @@ -178,6 +186,13 @@ class AppState extends ChangeNotifier { } Future disconnect() async { + for (final terminal in terminals.values) { + // Closing the shell on the server is right when the connection itself + // goes away; a panel close only detaches. + await terminal.closeSession(); + terminal.dispose(); + } + terminals.clear(); client?.close(); client = null; conn = null; @@ -325,6 +340,9 @@ class AppState extends ChangeNotifier { _startStream(); await refreshSessions(); if (chat != null) await chat!.reloadTail(); + for (final terminal in terminals.values) { + await terminal.reconnectIfNeeded(); + } } void _applyEvent(Map ev) { diff --git a/lib/terminal_state.dart b/lib/terminal_state.dart new file mode 100644 index 0000000..e6d09ad --- /dev/null +++ b/lib/terminal_state.dart @@ -0,0 +1,264 @@ +// 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; + + 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; + + /// Creates the session and attaches on first use; later calls just make sure + /// the socket is alive. + Future ensureOpen() async { + if (_disposed) return; + if (_opened) { + if (_socket == null && link != TerminalLinkState.exited) await _attach(); + return; + } + _opened = true; + await _create(); + } + + Future _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 _attach(); + } catch (error) { + _set(TerminalLinkState.error, detail: _message(error)); + } + } + + Future _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) { + _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 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 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 closeSession() async { + final client = app.client; + final id = sessionId; + sessionId = null; + _opened = false; + link = TerminalLinkState.idle; + detail = null; + await _socket?.dispose(); + _socket = null; + if (!_disposed) notifyListeners(); + if (client != null && id != null) { + try { + await client.closeTerminal(id, directory: directory); + } catch (_) {} + } + } + + @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; + } +} diff --git a/lib/widgets/markdown_view.dart b/lib/widgets/markdown_view.dart index e68ba57..9e518a5 100644 --- a/lib/widgets/markdown_view.dart +++ b/lib/widgets/markdown_view.dart @@ -40,11 +40,24 @@ class MarkdownView extends StatelessWidget { return mui.Theme( data: markdownThemeData(Theme.of(context)), child: GptMarkdown( - text, + _taskMarkers(text), // The server already streams deltas; show them as they arrive. isStreaming: false, style: TextStyle(fontSize: fontSize, height: height, color: color), ), ); } + + /// gpt_markdown draws task lists with `material_ui`'s Checkbox, which wants + /// a `material_ui` Material ancestor the app never provides (its Scaffold is + /// Flutter's). Boxed emoji read the same and cost no widget tree. + static String _taskMarkers(String source) { + var out = source.replaceAllMapped( + RegExp(r'^(\s*)[-*+]\s+\[[xX]\]\s+', multiLine: true), + (match) => '${match[1]}- ✅ '); + out = out.replaceAllMapped( + RegExp(r'^(\s*)[-*+]\s+\[\s?\]\s+', multiLine: true), + (match) => '${match[1]}- ⬜ '); + return out; + } } diff --git a/pubspec.lock b/pubspec.lock index d51d773..84a2053 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -73,6 +73,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.2" cross_file: dependency: transitive description: @@ -113,6 +121,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "0.8.0" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.0" fake_async: dependency: transitive description: @@ -525,6 +541,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.2.1" + quiver: + dependency: transitive + description: + name: quiver + sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.2.2" record_use: dependency: transitive description: @@ -770,6 +794,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "7.0.1" + xterm: + dependency: "direct main" + description: + name: xterm + sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.0" yaml: dependency: transitive description: @@ -778,6 +810,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "3.1.4" + zmodem: + dependency: transitive + description: + name: zmodem + sha256: "3b7e5b29f3a7d8aee472029b05165a68438eff2f3f7766edf13daba1e297adbf" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.0.6" sdks: dart: ">=3.14.0 <4.0.0" flutter: ">=3.47.0" diff --git a/pubspec.yaml b/pubspec.yaml index 4f26486..01d2bd0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.3.10+310 +version: 0.3.11+311 environment: sdk: ^3.14.0 @@ -16,6 +16,7 @@ dependencies: file_picker: ^13.0.0 gpt_markdown: ^1.4.0 socks5_proxy: ^2.1.2 + xterm: ^4.0.0 dev_dependencies: flutter_test: sdk: flutter