feat: built-in /compact and compaction rows in the transcript

- /compact is not one of the directory's commands: OpenChamber's own
  client supplies it and runs POST /api/session/:id/compact. The palette now
  starts with that local command (压缩), so picking it compacts without the
  model seeing anything.
- A compaction message (status running/completed/failed, reason, summary,
  tokens) is part of the timeline. It now shows as the official client's
  row: a scissors glyph and "正在压缩对话" / "对话已压缩", a 显示摘要 toggle,
  and the summary as Markdown (revealed with the same height animation as
  the other folds). Failed compactions keep the error block.
- Live compaction events are subscribed: started adds the running record
  (or refreshes the tail when it names no id), delta appends the streaming
  summary, ended/failed fetch the server's settled record.
- Version 0.3.8 (code 308).
This commit is contained in:
blumia committed 2026-11-20 12:26:15 +08:00
1 parent fbadf6f858
commit b9433c30cb
7 files changed
+214 -14

No files matched your search

+13
View File
@@ -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`) ## 0.3.7 工具输出被“壳”覆盖(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -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 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.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 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
+9
View File
@@ -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<String?> 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`). /// The commands this directory registers (`/api/command`).
Future<List<Map<String, String>>> commands({String? directory}) async { Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory); final r = await _json('GET', '/api/command', directory: directory);
+6 -2
View File
@@ -196,10 +196,12 @@ class Message {
final TokenUsage? tokens; final TokenUsage? tokens;
/// Set when the step (or compaction) failed. /// Set when the step (or compaction) failed.
final MessageError? error; final MessageError? error;
/// Compaction messages: 'failed' etc. /// Compaction messages: 'running' | 'completed' | 'failed'.
final String status; final String status;
/// Compaction messages: why it ran ('manual'). /// Compaction messages: why it ran ('manual' | 'auto').
final String reason; final String reason;
/// Compaction messages: the summary the model wrote for the new history.
final String summary;
Message({ Message({
required this.id, required this.id,
required this.type, required this.type,
@@ -216,6 +218,7 @@ class Message {
this.error, this.error,
this.status = '', this.status = '',
this.reason = '', this.reason = '',
this.summary = '',
}); });
factory Message.fromJson(Map<String, dynamic> j) { factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {}; final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -243,6 +246,7 @@ class Message {
: MessageError.fromJson(j['error'] as Map<String, dynamic>), : MessageError.fromJson(j['error'] as Map<String, dynamic>),
status: j['status'] as String? ?? '', status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '', reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
); );
} }
String get partText { String get partText {
+84 -5
View File
@@ -218,6 +218,8 @@ class _ChatScreenState extends State<ChatScreen> {
if (m.status == 'failed' || if (m.status == 'failed' ||
(m.error != null && !m.error!.isEmpty)) { (m.error != null && !m.error!.isEmpty)) {
out.add(_Row('error', m.id, -1)); out.add(_Row('error', m.id, -1));
} else {
out.add(_Row('compaction', m.id, -1));
} }
break; break;
case 'shell': case 'shell':
@@ -362,6 +364,8 @@ class _ChatScreenState extends State<ChatScreen> {
return _footerRow(r.msgId); return _footerRow(r.msgId);
case 'error': case 'error':
return _errorRow(r.msgId); return _errorRow(r.msgId);
case 'compaction':
return _compactionRow(r.msgId);
case 'shell': case 'shell':
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@@ -478,10 +482,13 @@ class _ChatScreenState extends State<ChatScreen> {
Widget _textRow(String id, int part) { Widget _textRow(String id, int part) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink(); if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final text = m.content[part].text;
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2), 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)), data: _mdTheme(Theme.of(context)),
child: GptMarkdown( child: GptMarkdown(
text, text,
@@ -489,9 +496,7 @@ class _ChatScreenState extends State<ChatScreen> {
isStreaming: false, isStreaming: false,
style: const TextStyle(fontSize: 15, height: 1.45), style: const TextStyle(fontSize: 15, height: 1.45),
), ),
), );
);
}
/// A run of steps: the header, then its rows revealed with an animation. /// A run of steps: the header, then its rows revealed with an animation.
/// Revealing grows the list below the header, so [_Reveal] reports the /// Revealing grows the list below the header, so [_Reveal] reports the
@@ -1022,6 +1027,80 @@ class _ChatScreenState extends State<ChatScreen> {
} }
} }
/// 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 /// A failed turn's error, as a quiet block under its last step: what went
/// wrong, and the provider's response behind a "详情" toggle. /// wrong, and the provider's response behind a "详情" toggle.
Widget _errorRow(String id) { Widget _errorRow(String id) {
+100 -5
View File
@@ -37,6 +37,10 @@ const _eventTypes = [
'session.tool.called', 'session.tool.called',
'session.tool.success', 'session.tool.success',
'session.tool.failed', 'session.tool.failed',
'session.compaction.started',
'session.compaction.delta',
'session.compaction.ended',
'session.compaction.failed',
'permission.asked', 'permission.asked',
'permission.replied', 'permission.replied',
]; ];
@@ -486,11 +490,15 @@ class SlashItem {
final String description; final String description;
final bool skill; final bool skill;
final String id; final String id;
/// A command the client runs itself (`compact`), rather than a prompt.
final String action;
const SlashItem({ const SlashItem({
required this.name, required this.name,
this.description = '', this.description = '',
this.skill = false, this.skill = false,
this.id = '', this.id = '',
this.action = '',
}); });
/// Commands whose description shows an argument form (`[commit|branch|pr]`) /// Commands whose description shows an argument form (`[commit|branch|pr]`)
@@ -568,9 +576,18 @@ class ChatState extends ChangeNotifier {
cl.commands(directory: dir), cl.commands(directory: dir),
cl.skills(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 = [ slashItems = [
...local,
for (final c in results[0]) for (final c in results[0])
if ((c['name'] ?? '').isNotEmpty) if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name']))
SlashItem( SlashItem(
name: c['name']!, name: c['name']!,
description: c['description'] ?? '', description: c['description'] ?? '',
@@ -639,6 +656,7 @@ class ChatState extends ChangeNotifier {
error: server.error, error: server.error,
status: server.status, status: server.status,
reason: server.reason, reason: server.reason,
summary: server.summary,
); );
} }
@@ -715,6 +733,30 @@ class ChatState extends ChangeNotifier {
final args = final args =
(RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim(); (RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim();
draft = ''; 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) { if (!item.skill) {
// A command is expanded by the server, which also writes the user // A command is expanded by the server, which also writes the user
// message; there is no id to show optimistically. // message; there is no id to show optimistically.
@@ -927,7 +969,8 @@ class ChatState extends ChangeNotifier {
? m.error ? m.error
: MessageError.fromJson(data['error'] as Map<String, dynamic>), : MessageError.fromJson(data['error'] as Map<String, dynamic>),
status: m.status, 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 // Live events name a tool only by id, so a streamed step would keep
// a generic label ("工具") until the session was reopened. The // a generic label ("工具") until the session was reopened. The
// finished message has the names, inputs and attachments. // finished message has the names, inputs and attachments.
@@ -956,6 +999,55 @@ class ChatState extends ChangeNotifier {
case 'session.tool.progress': case 'session.tool.progress':
if (mid != null) _applyTool(mid, type, data); if (mid != null) _applyTool(mid, type, data);
break; 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': case 'session.model.selected':
final model = data['model']; final model = data['model'];
if (model is Map<String, dynamic>) { if (model is Map<String, dynamic>) {
@@ -1026,7 +1118,8 @@ class ChatState extends ChangeNotifier {
tokens: m.tokens, tokens: m.tokens,
error: m.error, error: m.error,
status: m.status, status: m.status,
reason: m.reason); reason: m.reason,
summary: m.summary);
}); });
} }
@@ -1089,7 +1182,8 @@ class ChatState extends ChangeNotifier {
tokens: m.tokens, tokens: m.tokens,
error: m.error, error: m.error,
status: m.status, status: m.status,
reason: m.reason); reason: m.reason,
summary: m.summary);
} }
} }
content.add(part); content.add(part);
@@ -1108,7 +1202,8 @@ class ChatState extends ChangeNotifier {
tokens: m.tokens, tokens: m.tokens,
error: m.error, error: m.error,
status: m.status, status: m.status,
reason: m.reason); reason: m.reason,
summary: m.summary);
}); });
} }
+1 -1
View File
@@ -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.7+307 version: 0.3.8+308
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0