diff --git a/PLAN.md b/PLAN.md index 98e95dd..a3885b5 100644 --- a/PLAN.md +++ b/PLAN.md @@ -27,6 +27,19 @@ --- +## 0.3.8 内置 `/compact` 与压缩记录(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| `/compact` | 官方客户端的内置指令不在 `/api/command` 里,是客户端自己提供的;现在面板会先列出本地指令(`compact`,中文名「压缩」),选中即执行 `POST /api/session/:id/compact`,不需要模型参与 | +| 其它内置 | 看了 opencode 官方实现:`undo`/`redo`(撤回语义)、`timeline`(时间线视图)、`btw`(临时子会话)、`fork`、`handoff-review`,以及 `summary`/`workspace-review`/`plan-feature`/`craft-goal`/`schedule-task`/`catch-up`/`debug`/`weigh`/`explore`(成对的可见提示 + 隐藏指令)。本轮只做 `/compact`;其余需要对应 UI 或官方提示词文本,未加 | +| 压缩记录 | 消息列表里的 `compaction` 消息(`status` running/completed/failed、`reason`、`summary`、`tokens`)现在会显示成一行「正在压缩对话 / 对话已压缩」+「显示摘要」,展开是 Markdown 摘要;运行中有转圈,结束后自动换成完成态 | +| 实时 | 订阅 `session.compaction.started/delta/ended/failed`:开始时插入运行中的记录或拉一次尾部,delta 追加到摘要,结束/失败时拉一次服务端版本(摘要、token、错误都齐) | +| 失败 | 压缩失败仍用错误块显示(「压缩失败:…」+ 原始响应详情) | +| 版本 | **0.3.8(code 308)** | + +--- + ## 0.3.7 工具输出被“壳”覆盖(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 4674e88..9d65630 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.3.7 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.8 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live events, chat with streaming Markdown and full history paging, tool steps grouped per turn (icon, one-line summary, foldable run) with image previews, a diff --git a/lib/api/client.dart b/lib/api/client.dart index bc64d3a..688dbde 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -281,6 +281,15 @@ class Client { }); } + /// Asks the server to summarize the history into a compaction record. + /// Returns that record's message id, when the server names it. + Future compact(String sessionId, {String? directory}) async { + final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/compact', + directory: directory, body: const {}); + final data = r['data']; + return data is Map ? data['id'] as String? : null; + } + /// The commands this directory registers (`/api/command`). Future>> commands({String? directory}) async { final r = await _json('GET', '/api/command', directory: directory); diff --git a/lib/api/models.dart b/lib/api/models.dart index fcfe4f3..9df5a62 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -196,10 +196,12 @@ class Message { final TokenUsage? tokens; /// Set when the step (or compaction) failed. final MessageError? error; - /// Compaction messages: 'failed' etc. + /// Compaction messages: 'running' | 'completed' | 'failed'. final String status; - /// Compaction messages: why it ran ('manual'). + /// Compaction messages: why it ran ('manual' | 'auto'). final String reason; + /// Compaction messages: the summary the model wrote for the new history. + final String summary; Message({ required this.id, required this.type, @@ -216,6 +218,7 @@ class Message { this.error, this.status = '', this.reason = '', + this.summary = '', }); factory Message.fromJson(Map j) { final t = j['time'] as Map? ?? {}; @@ -243,6 +246,7 @@ class Message { : MessageError.fromJson(j['error'] as Map), status: j['status'] as String? ?? '', reason: j['reason'] as String? ?? '', + summary: j['summary'] as String? ?? '', ); } String get partText { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 0e34da2..5f67434 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -218,6 +218,8 @@ class _ChatScreenState extends State { if (m.status == 'failed' || (m.error != null && !m.error!.isEmpty)) { out.add(_Row('error', m.id, -1)); + } else { + out.add(_Row('compaction', m.id, -1)); } break; case 'shell': @@ -362,6 +364,8 @@ class _ChatScreenState extends State { return _footerRow(r.msgId); case 'error': return _errorRow(r.msgId); + case 'compaction': + return _compactionRow(r.msgId); case 'shell': return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), @@ -478,10 +482,13 @@ class _ChatScreenState extends State { Widget _textRow(String id, int part) { final m = chat.byId[id]!; if (part < 0 || part >= m.content.length) return const SizedBox.shrink(); - final text = m.content[part].text; return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2), - child: mui.Theme( + child: _markdown(m.content[part].text), + ); + } + + Widget _markdown(String text) => mui.Theme( data: _mdTheme(Theme.of(context)), child: GptMarkdown( text, @@ -489,9 +496,7 @@ class _ChatScreenState extends State { isStreaming: false, style: const TextStyle(fontSize: 15, height: 1.45), ), - ), - ); - } + ); /// A run of steps: the header, then its rows revealed with an animation. /// Revealing grows the list below the header, so [_Reveal] reports the @@ -1022,6 +1027,80 @@ class _ChatScreenState extends State { } } + /// A compaction in the timeline: one line ("对话已压缩") that opens into the + /// summary the model wrote to replace the older history. + Widget _compactionRow(String id) { + final m = chat.byId[id]; + if (m == null) return const SizedBox.shrink(); + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final running = m.status == 'running'; + final summary = m.summary.trim(); + final open = chat.expanded.contains('compaction/$id'); + final label = running ? '正在压缩对话' : '对话已压缩'; + final header = GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => setState(() { + final k = 'compaction/$id'; + open ? chat.expanded.remove(k) : chat.expanded.add(k); + }), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 12, 2), + child: Row( + children: [ + if (running) + const SizedBox( + width: 15, + height: 15, + child: CircularProgressIndicator(strokeWidth: 1.6)) + else + Icon(Icons.content_cut, size: 16, color: theme.hintColor), + const SizedBox(width: 8), + Expanded( + child: Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 13, color: theme.hintColor)), + ), + if (summary.isNotEmpty) + Text(open ? '隐藏摘要' : '显示摘要', + style: TextStyle(fontSize: 12, color: scheme.primary)), + const SizedBox(width: 4), + AnimatedRotation( + turns: open ? 0.5 : 0, + duration: const Duration(milliseconds: 180), + child: Icon(Icons.expand_more, size: 18, color: theme.hintColor), + ), + ], + ), + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + _Reveal( + open: open, + onGrow: _grow, + child: Container( + margin: const EdgeInsets.fromLTRB(22, 2, 16, 8), + padding: const EdgeInsets.fromLTRB(10, 8, 10, 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.5), + border: Border( + left: BorderSide(color: theme.dividerColor, width: 1)), + borderRadius: BorderRadius.circular(8), + ), + child: summary.isEmpty + ? Text(running ? '正在生成摘要…' : '(摘要为空)', + style: TextStyle(fontSize: 13, color: theme.hintColor)) + : _markdown(summary), + ), + ), + ], + ); + } + /// A failed turn's error, as a quiet block under its last step: what went /// wrong, and the provider's response behind a "详情" toggle. Widget _errorRow(String id) { diff --git a/lib/state.dart b/lib/state.dart index 9185397..05bfae8 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -37,6 +37,10 @@ const _eventTypes = [ 'session.tool.called', 'session.tool.success', 'session.tool.failed', + 'session.compaction.started', + 'session.compaction.delta', + 'session.compaction.ended', + 'session.compaction.failed', 'permission.asked', 'permission.replied', ]; @@ -486,11 +490,15 @@ class SlashItem { final String description; final bool skill; final String id; + + /// A command the client runs itself (`compact`), rather than a prompt. + final String action; const SlashItem({ required this.name, this.description = '', this.skill = false, this.id = '', + this.action = '', }); /// Commands whose description shows an argument form (`[commit|branch|pr]`) @@ -568,9 +576,18 @@ class ChatState extends ChangeNotifier { cl.commands(directory: dir), cl.skills(directory: dir), ]); + const local = [ + SlashItem( + name: 'compact', + description: '使用 AI 压缩会话历史以减少上下文大小', + action: 'compact', + ), + ]; + final localNames = {for (final c in local) c.name}; slashItems = [ + ...local, for (final c in results[0]) - if ((c['name'] ?? '').isNotEmpty) + if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name'])) SlashItem( name: c['name']!, description: c['description'] ?? '', @@ -639,6 +656,7 @@ class ChatState extends ChangeNotifier { error: server.error, status: server.status, reason: server.reason, + summary: server.summary, ); } @@ -715,6 +733,30 @@ class ChatState extends ChangeNotifier { final args = (RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim(); draft = ''; + if (item.action == 'compact') { + try { + final cid = await app.client!.compact(this.id, directory: dir); + error = null; + if (cid != null && byId[cid] == null) { + msgs.add(Message( + id: cid, + type: 'compaction', + status: 'running', + reason: 'manual', + created: DateTime.now().millisecondsSinceEpoch, + )); + _sortMsgs(); + } + notifyListeners(); + await reloadTail(); + return ''; + } catch (e) { + draft = t; + error = e.toString(); + notifyListeners(); + return null; + } + } if (!item.skill) { // A command is expanded by the server, which also writes the user // message; there is no id to show optimistically. @@ -927,7 +969,8 @@ class ChatState extends ChangeNotifier { ? m.error : MessageError.fromJson(data['error'] as Map), status: m.status, - reason: m.reason)); + reason: m.reason, + summary: m.summary)); // Live events name a tool only by id, so a streamed step would keep // a generic label ("工具") until the session was reopened. The // finished message has the names, inputs and attachments. @@ -956,6 +999,55 @@ class ChatState extends ChangeNotifier { case 'session.tool.progress': if (mid != null) _applyTool(mid, type, data); break; + case 'session.compaction.started': + final cid = data['inputID'] as String?; + if (cid != null && byId[cid] == null) { + msgs.add(Message( + id: cid, + type: 'compaction', + status: 'running', + reason: data['reason'] as String? ?? '', + created: created, + )); + _sortMsgs(); + } else if (cid == null) { + reloadTail(); + } + break; + case 'session.compaction.delta': + final text = data['text'] as String? ?? ''; + if (text.isNotEmpty) { + for (var i = msgs.length - 1; i >= 0; i--) { + final m = msgs[i]; + if (m.type == 'compaction' && m.status == 'running') { + msgs[i] = Message( + id: m.id, + type: m.type, + created: m.created, + completed: m.completed, + agent: m.agent, + model: m.model, + content: m.content, + text: m.text, + files: m.files, + finish: m.finish, + cost: m.cost, + tokens: m.tokens, + error: m.error, + status: m.status, + reason: m.reason, + summary: m.summary + text, + ); + _reindex(); + break; + } + } + } + break; + case 'session.compaction.ended': + case 'session.compaction.failed': + reloadTail(); + break; case 'session.model.selected': final model = data['model']; if (model is Map) { @@ -1026,7 +1118,8 @@ class ChatState extends ChangeNotifier { tokens: m.tokens, error: m.error, status: m.status, - reason: m.reason); + reason: m.reason, + summary: m.summary); }); } @@ -1089,7 +1182,8 @@ class ChatState extends ChangeNotifier { tokens: m.tokens, error: m.error, status: m.status, - reason: m.reason); + reason: m.reason, + summary: m.summary); } } content.add(part); @@ -1108,7 +1202,8 @@ class ChatState extends ChangeNotifier { tokens: m.tokens, error: m.error, status: m.status, - reason: m.reason); + reason: m.reason, + summary: m.summary); }); } diff --git a/pubspec.yaml b/pubspec.yaml index 27da456..55f0465 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.3.7+307 +version: 0.3.8+308 environment: sdk: ^3.14.0