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

+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`).
Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory);
+6 -2
View File
@@ -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<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -243,6 +246,7 @@ class Message {
: MessageError.fromJson(j['error'] as Map<String, dynamic>),
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
);
}
String get partText {
+84 -5
View File
@@ -218,6 +218,8 @@ class _ChatScreenState extends State<ChatScreen> {
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<ChatScreen> {
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<ChatScreen> {
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<ChatScreen> {
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<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
/// wrong, and the provider's response behind a "详情" toggle.
Widget _errorRow(String id) {
+100 -5
View File
@@ -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<String, dynamic>),
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<String, dynamic>) {
@@ -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);
});
}