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
+2346
-56
No files matched your search
@@ -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`)
|
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
|
||||||
|
|
||||||
| 项 | 结果 |
|
| 项 | 结果 |
|
||||||
|
|||||||
@@ -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
|
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
||||||
Flutter to compare mobile UI maturity.
|
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
|
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
|
events, chat with streaming Markdown and full history paging, tool steps
|
||||||
grouped per turn (icon, one-line summary, foldable run) with image previews, a
|
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,
|
context usage ring with a detail sheet, model/agent switching (Build/Plan only,
|
||||||
current one checked), copy / fork / revert, attachments (photos/files, kept
|
current one checked), copy / fork / revert, attachments (photos/files, kept
|
||||||
after a reload), the agent's native forms, permissions. A phone opens the
|
after a reload), the agent's native forms, permissions. The files sidebar also
|
||||||
session list as the left drawer and a wide window (tablet, desktop) shows it
|
carries the project knowledge (notes, todos, plans) and a full terminal with a
|
||||||
beside the chat. Android 7.0 (API 24)+, plus a Linux desktop target used for
|
Termux-style key bar; downloads show their progress and can be cancelled. A
|
||||||
local testing.
|
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
|
## 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/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/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/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 |
|
| `lib/widgets/` | The context usage ring |
|
||||||
|
|
||||||
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
|
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
|
||||||
|
|||||||
+237
-10
@@ -4,7 +4,10 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
import 'models.dart';
|
import 'models.dart';
|
||||||
|
import 'terminal.dart';
|
||||||
import 'transport.dart';
|
import 'transport.dart';
|
||||||
|
|
||||||
class ApiError implements Exception {
|
class ApiError implements Exception {
|
||||||
@@ -291,19 +294,51 @@ class Client {
|
|||||||
directory: directory, body: {'agent': agent});
|
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',
|
final res = await _request('GET', '/api/fs/raw',
|
||||||
query: {
|
query: {
|
||||||
'path': path,
|
'path': path,
|
||||||
'allowOutsideWorkspace': 'true',
|
'allowOutsideWorkspace': 'true',
|
||||||
},
|
},
|
||||||
directory: directory,
|
directory: directory,
|
||||||
rawDirectory: true);
|
rawDirectory: true,
|
||||||
final bytes = await res.collect();
|
// 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) {
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
throw ApiError(res.statusCode, utf8.decode(bytes, allowMalformed: true));
|
throw ApiError(
|
||||||
|
res.statusCode,
|
||||||
|
utf8.decode(bytes.takeBytes(), allowMalformed: true));
|
||||||
|
}
|
||||||
|
return bytes.takeBytes();
|
||||||
|
} finally {
|
||||||
|
cancel?.detach();
|
||||||
}
|
}
|
||||||
return bytes;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------ files
|
// ------------------------------------------------------------ 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
|
// --------------------------------------------------------------- transport
|
||||||
|
|
||||||
Future<Map<String, dynamic>> _json(String method, String path,
|
Future<Map<String, dynamic>> _json(String method, String path,
|
||||||
@@ -409,13 +630,15 @@ class Client {
|
|||||||
Map<String, dynamic>? body,
|
Map<String, dynamic>? body,
|
||||||
String? directory,
|
String? directory,
|
||||||
bool partShells = false,
|
bool partShells = false,
|
||||||
bool rawDirectory = false}) async {
|
bool rawDirectory = false,
|
||||||
|
bool noCompression = false}) async {
|
||||||
final res = await _request(method, path,
|
final res = await _request(method, path,
|
||||||
query: query,
|
query: query,
|
||||||
body: body,
|
body: body,
|
||||||
directory: directory,
|
directory: directory,
|
||||||
partShells: partShells,
|
partShells: partShells,
|
||||||
rawDirectory: rawDirectory);
|
rawDirectory: rawDirectory,
|
||||||
|
noCompression: noCompression);
|
||||||
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
||||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
String msg = text;
|
String msg = text;
|
||||||
@@ -438,7 +661,8 @@ class Client {
|
|||||||
Map<String, dynamic>? body,
|
Map<String, dynamic>? body,
|
||||||
String? directory,
|
String? directory,
|
||||||
bool partShells = false,
|
bool partShells = false,
|
||||||
bool rawDirectory = false}) async {
|
bool rawDirectory = false,
|
||||||
|
bool noCompression = false}) async {
|
||||||
final headers = <String, String>{
|
final headers = <String, String>{
|
||||||
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
|
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
|
||||||
'user-agent': 'openchamber-native/0.3',
|
'user-agent': 'openchamber-native/0.3',
|
||||||
@@ -452,6 +676,7 @@ class Client {
|
|||||||
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
|
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
|
||||||
}
|
}
|
||||||
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
|
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
|
||||||
|
if (noCompression) headers['accept-encoding'] = 'identity';
|
||||||
if (path == '/api/event') headers['cache-control'] = 'no-cache';
|
if (path == '/api/event') headers['cache-control'] = 'no-cache';
|
||||||
final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
|
final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
|
||||||
if (bodyBytes != null) headers['content-type'] = 'application/json';
|
if (bodyBytes != null) headers['content-type'] = 'application/json';
|
||||||
@@ -462,7 +687,7 @@ class Client {
|
|||||||
headers: headers,
|
headers: headers,
|
||||||
body: bodyBytes,
|
body: bodyBytes,
|
||||||
));
|
));
|
||||||
return _Response(res.status, res.body);
|
return _Response(res.status, res.headers, res.body, res.abort);
|
||||||
}
|
}
|
||||||
|
|
||||||
void close() => transport.close();
|
void close() => transport.close();
|
||||||
@@ -470,8 +695,10 @@ class Client {
|
|||||||
|
|
||||||
class _Response {
|
class _Response {
|
||||||
final int statusCode;
|
final int statusCode;
|
||||||
|
final Map<String, String> headers;
|
||||||
final Stream<List<int>> body;
|
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() =>
|
Future<List<int>> collect() =>
|
||||||
body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
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> {
|
class Page<T> {
|
||||||
final List<T> data;
|
final List<T> data;
|
||||||
final String? next;
|
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 int status;
|
||||||
final Map<String, String> headers;
|
final Map<String, String> headers;
|
||||||
final Stream<List<int>> body;
|
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.
|
/// The one seam every request goes through.
|
||||||
@@ -43,10 +47,45 @@ abstract class Transport {
|
|||||||
/// Sends [request], completing when the reply head arrives.
|
/// Sends [request], completing when the reply head arrives.
|
||||||
Future<TransportResponse> send(TransportRequest request);
|
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.
|
/// Releases whatever sockets the transport holds.
|
||||||
void close();
|
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.
|
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
|
||||||
class ProxyConfig {
|
class ProxyConfig {
|
||||||
final String scheme; // http | https | socks5 | socks5h
|
final String scheme; // http | https | socks5 | socks5h
|
||||||
@@ -166,7 +205,20 @@ class DirectTransport implements Transport {
|
|||||||
res.headers.forEach((name, values) {
|
res.headers.forEach((name, values) {
|
||||||
headers[name.toLowerCase()] = values.join(', ');
|
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
|
@override
|
||||||
|
|||||||
+132
-36
@@ -9,8 +9,11 @@ import 'package:flutter/material.dart';
|
|||||||
|
|
||||||
import '../api/client.dart';
|
import '../api/client.dart';
|
||||||
import '../api/models.dart';
|
import '../api/models.dart';
|
||||||
|
import '../api/transport.dart';
|
||||||
import '../state.dart';
|
import '../state.dart';
|
||||||
import '../widgets/markdown_view.dart';
|
import '../widgets/markdown_view.dart';
|
||||||
|
import 'knowledge_panel.dart';
|
||||||
|
import 'terminal_panel.dart';
|
||||||
|
|
||||||
Future<void> showFilesPanel(
|
Future<void> showFilesPanel(
|
||||||
BuildContext context, AppState app, Session session) {
|
BuildContext context, AppState app, Session session) {
|
||||||
@@ -289,16 +292,28 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
final client = _client;
|
final client = _client;
|
||||||
final path = _previewPath;
|
final path = _previewPath;
|
||||||
if (client == null || path == null) return;
|
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<Uint8List>(
|
||||||
|
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 {
|
try {
|
||||||
final bytes = _previewBytes ??
|
|
||||||
Uint8List.fromList(await client.rawFile(path, directory: _root));
|
|
||||||
final uri = await FilePicker.saveFile(
|
final uri = await FilePicker.saveFile(
|
||||||
fileName: _previewName,
|
fileName: _previewName,
|
||||||
bytes: bytes,
|
bytes: bytes,
|
||||||
);
|
);
|
||||||
if (uri != null) _toast('已保存');
|
if (uri != null) _toast('已保存');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_toast('下载失败:$e');
|
_toast('保存失败:$e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,46 +531,15 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
}
|
}
|
||||||
switch (_tab) {
|
switch (_tab) {
|
||||||
case 1:
|
case 1:
|
||||||
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
|
return KnowledgePanel(app: widget.app, directory: _root);
|
||||||
'笔记、待办与计划会在这里。');
|
|
||||||
case 2:
|
case 2:
|
||||||
return _placeholder(
|
return TerminalPanel(app: widget.app, directory: _root);
|
||||||
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
|
|
||||||
default:
|
default:
|
||||||
if (_previewPath != null) return _previewBody(theme);
|
if (_previewPath != null) return _previewBody(theme);
|
||||||
return _browser(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) {
|
Widget _browser(ThemeData theme) {
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
@@ -935,3 +919,115 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
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<Uint8List> 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<void> _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('关闭'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<KnowledgePanel> createState() => _KnowledgePanelState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _KnowledgePanelState extends State<KnowledgePanel> {
|
||||||
|
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<void> _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<String> 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<int>(
|
||||||
|
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<String>(
|
||||||
|
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<String>(
|
||||||
|
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<void> _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<String>(
|
||||||
|
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<void> _addNote() => _editNote(null);
|
||||||
|
|
||||||
|
Future<void> _editNote(ProjectNote? note) async {
|
||||||
|
final text = await showDialog<String>(
|
||||||
|
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<void> _addTodo() async {
|
||||||
|
final text = await showDialog<String>(
|
||||||
|
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<void> _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<void> _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<void>(
|
||||||
|
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<void> 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<void> _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('创建')),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<TerminalPanel> createState() => _TerminalPanelState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _TerminalPanelState extends State<TerminalPanel> {
|
||||||
|
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<String>(
|
||||||
|
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<void> _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<void> _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);
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import 'package:flutter/foundation.dart';
|
|||||||
import 'api/client.dart';
|
import 'api/client.dart';
|
||||||
import 'api/models.dart';
|
import 'api/models.dart';
|
||||||
import 'storage.dart';
|
import 'storage.dart';
|
||||||
|
import 'terminal_state.dart';
|
||||||
|
|
||||||
const _eventTypes = [
|
const _eventTypes = [
|
||||||
'session.created',
|
'session.created',
|
||||||
@@ -67,6 +68,13 @@ class AppState extends ChangeNotifier {
|
|||||||
|
|
||||||
ChatState? chat;
|
ChatState? chat;
|
||||||
|
|
||||||
|
/// Terminals by workspace directory: switching sessions or tabs keeps the
|
||||||
|
/// shell alive, and each directory gets its own.
|
||||||
|
final Map<String, TerminalSessionState> terminals = {};
|
||||||
|
|
||||||
|
TerminalSessionState terminalFor(String directory) => terminals.putIfAbsent(
|
||||||
|
directory, () => TerminalSessionState(this, directory));
|
||||||
|
|
||||||
/// Public way to signal UI changes (notifyListeners is protected).
|
/// Public way to signal UI changes (notifyListeners is protected).
|
||||||
void touch() => notifyListeners();
|
void touch() => notifyListeners();
|
||||||
|
|
||||||
@@ -178,6 +186,13 @@ class AppState extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> disconnect() async {
|
Future<void> 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?.close();
|
||||||
client = null;
|
client = null;
|
||||||
conn = null;
|
conn = null;
|
||||||
@@ -325,6 +340,9 @@ class AppState extends ChangeNotifier {
|
|||||||
_startStream();
|
_startStream();
|
||||||
await refreshSessions();
|
await refreshSessions();
|
||||||
if (chat != null) await chat!.reloadTail();
|
if (chat != null) await chat!.reloadTail();
|
||||||
|
for (final terminal in terminals.values) {
|
||||||
|
await terminal.reconnectIfNeeded();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _applyEvent(Map<String, dynamic> ev) {
|
void _applyEvent(Map<String, dynamic> ev) {
|
||||||
|
|||||||
@@ -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<void> ensureOpen() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (_opened) {
|
||||||
|
if (_socket == null && link != TerminalLinkState.exited) await _attach();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_opened = true;
|
||||||
|
await _create();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _create() async {
|
||||||
|
final client = app.client;
|
||||||
|
if (client == null) return;
|
||||||
|
_set(TerminalLinkState.creating);
|
||||||
|
try {
|
||||||
|
final info = await client.createTerminal(
|
||||||
|
cwd: directory, cols: _cols, rows: _rows);
|
||||||
|
if (_disposed) return;
|
||||||
|
sessionId = info.sessionId;
|
||||||
|
_cols = info.cols;
|
||||||
|
_rows = info.rows;
|
||||||
|
await _attach();
|
||||||
|
} catch (error) {
|
||||||
|
_set(TerminalLinkState.error, detail: _message(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _attach() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null || _disposed) return;
|
||||||
|
await _socket?.dispose();
|
||||||
|
final socket = TerminalSocket(
|
||||||
|
transport: client.transport,
|
||||||
|
headers: client.eventHeaders,
|
||||||
|
sessionId: id,
|
||||||
|
onEvent: _onEvent,
|
||||||
|
onState: (state, {detail}) => _set(state, detail: detail),
|
||||||
|
);
|
||||||
|
_socket = socket;
|
||||||
|
await socket.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onEvent(TerminalEvent event) {
|
||||||
|
if (_disposed) return;
|
||||||
|
switch (event.type) {
|
||||||
|
case 'snapshot':
|
||||||
|
// Replay at the size the server drew the history for, then clear what
|
||||||
|
// this view already had: a reattach must not duplicate the screen.
|
||||||
|
if (event.cols != null && event.rows != null) {
|
||||||
|
model.resize(event.cols!, event.rows!);
|
||||||
|
}
|
||||||
|
_clear();
|
||||||
|
if (event.data.isNotEmpty) model.write(event.data);
|
||||||
|
if (event.status == 'exited') {
|
||||||
|
_set(TerminalLinkState.exited,
|
||||||
|
detail: event.exitCode == null
|
||||||
|
? '已退出'
|
||||||
|
: '退出码 ${event.exitCode}');
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'restarted':
|
||||||
|
_clear();
|
||||||
|
if (event.data.isNotEmpty) model.write(event.data);
|
||||||
|
_set(TerminalLinkState.open);
|
||||||
|
break;
|
||||||
|
case 'output':
|
||||||
|
model.write(event.data);
|
||||||
|
break;
|
||||||
|
case 'exit':
|
||||||
|
_set(TerminalLinkState.exited,
|
||||||
|
detail: event.exitCode == null
|
||||||
|
? '已退出'
|
||||||
|
: '退出码 ${event.exitCode}');
|
||||||
|
break;
|
||||||
|
case 'error':
|
||||||
|
if (event.fatal) {
|
||||||
|
_set(TerminalLinkState.error,
|
||||||
|
detail: event.message ?? event.code ?? '终端连接失败');
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the screen and the scrollback, then homes the cursor.
|
||||||
|
void _clear() => model.write('\x1b[2J\x1b[3J\x1b[H');
|
||||||
|
|
||||||
|
void _set(TerminalLinkState state, {String? detail}) {
|
||||||
|
link = state;
|
||||||
|
if (detail != null) this.detail = detail;
|
||||||
|
if (state == TerminalLinkState.open) this.detail = null;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleResize() {
|
||||||
|
_resizeTimer?.cancel();
|
||||||
|
_resizeTimer = Timer(const Duration(milliseconds: 250), () {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null || _disposed) return;
|
||||||
|
client
|
||||||
|
.resizeTerminal(id, _cols, _rows, directory: directory)
|
||||||
|
.catchError((_) {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restarts the shell in place (the server keeps the session id).
|
||||||
|
Future<void> restart() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null) return;
|
||||||
|
_set(TerminalLinkState.connecting);
|
||||||
|
try {
|
||||||
|
await client.restartTerminal(id,
|
||||||
|
cwd: directory, cols: _cols, rows: _rows);
|
||||||
|
if (_disposed) return;
|
||||||
|
_clear();
|
||||||
|
_set(TerminalLinkState.open);
|
||||||
|
} catch (error) {
|
||||||
|
_set(TerminalLinkState.error, detail: _message(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After the app returns from the background: the socket may be dead
|
||||||
|
/// without having reported it.
|
||||||
|
Future<void> reconnectIfNeeded() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (link == TerminalLinkState.exited || link == TerminalLinkState.error) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_socket == null) await _attach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends the shell on the server and drops the socket; the next
|
||||||
|
/// [ensureOpen] starts a fresh session.
|
||||||
|
Future<void> closeSession() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
sessionId = null;
|
||||||
|
_opened = false;
|
||||||
|
link = TerminalLinkState.idle;
|
||||||
|
detail = null;
|
||||||
|
await _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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,11 +40,24 @@ class MarkdownView extends StatelessWidget {
|
|||||||
return mui.Theme(
|
return mui.Theme(
|
||||||
data: markdownThemeData(Theme.of(context)),
|
data: markdownThemeData(Theme.of(context)),
|
||||||
child: GptMarkdown(
|
child: GptMarkdown(
|
||||||
text,
|
_taskMarkers(text),
|
||||||
// The server already streams deltas; show them as they arrive.
|
// The server already streams deltas; show them as they arrive.
|
||||||
isStreaming: false,
|
isStreaming: false,
|
||||||
style: TextStyle(fontSize: fontSize, height: height, color: color),
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -73,6 +73,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
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:
|
cross_file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -113,6 +121,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.8.0"
|
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:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -525,6 +541,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.1"
|
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:
|
record_use:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -770,6 +794,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "7.0.1"
|
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:
|
yaml:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -778,6 +810,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.4"
|
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:
|
sdks:
|
||||||
dart: ">=3.14.0 <4.0.0"
|
dart: ">=3.14.0 <4.0.0"
|
||||||
flutter: ">=3.47.0"
|
flutter: ">=3.47.0"
|
||||||
+2
-1
@@ -2,7 +2,7 @@ name: openchamber
|
|||||||
description: "A lightweight OpenChamber client for phones."
|
description: "A lightweight OpenChamber client for phones."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 0.3.10+310
|
version: 0.3.11+311
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.14.0
|
sdk: ^3.14.0
|
||||||
@@ -16,6 +16,7 @@ dependencies:
|
|||||||
file_picker: ^13.0.0
|
file_picker: ^13.0.0
|
||||||
gpt_markdown: ^1.4.0
|
gpt_markdown: ^1.4.0
|
||||||
socks5_proxy: ^2.1.2
|
socks5_proxy: ^2.1.2
|
||||||
|
xterm: ^4.0.0
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
|
|||||||
Reference in new issue
Block a user