Files
openchamber-android-native/lib/screens/chat_screen.dart
T

2364 lines
81 KiB
Dart
Raw Normal View History

2026-11-18 19:08:06 +08:00
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
2026-11-18 19:08:06 +08:00
import 'package:flutter/services.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
// gpt_markdown renders through its own Material port; its colours come from
// that port's theme, so the chat has to hand it ours.
import 'package:material_ui/material_ui.dart' as mui;
2026-11-18 19:08:06 +08:00
import '../api/client.dart';
2026-11-18 19:08:06 +08:00
import '../api/models.dart';
import '../state.dart';
import '../widgets/usage_ring.dart';
/// The chat: streaming Markdown, tool rows, composer and sheets.
class ChatScreen extends StatefulWidget {
final AppState app;
final Session session;
const ChatScreen({super.key, required this.app, required this.session});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
ChatState get chat => widget.app.chat!;
final TextEditingController _draftCtrl = TextEditingController();
final FocusNode _inputFocus = FocusNode();
2026-11-18 19:08:06 +08:00
final ScrollController _scroll = ScrollController();
bool _stick = true;
bool _pickerOpen = false;
String _pickerKind = 'model';
String _pickerFilter = '';
List<_Attach> _attachments = [];
bool _attaching = false;
/// `/` palette: the highlighted row, and the draft Esc closed it at.
int _slashIndex = 0;
String? _slashDismissed;
/// Assistant turns show their reasoning/tool parts as a run of steps; the
/// header of each run folds it away (key: message id and start part).
/// These are the runs the person folded or unfolded, overriding the
/// default (finished folded, running open).
final Set<String> _collapsedSteps = {};
final Set<String> _expandedSteps = {};
2026-11-18 19:08:06 +08:00
@override
void initState() {
super.initState();
chat.addListener(_onChat);
// The list is reversed: offset 0 is the newest message (the bottom), and
// older pages grow above without moving what is on screen.
2026-11-18 19:08:06 +08:00
_scroll.addListener(() {
final atBottom = _scroll.position.pixels <= 40;
if (_stick != atBottom) setState(() => _stick = atBottom);
final remaining =
_scroll.position.maxScrollExtent - _scroll.position.pixels;
if (remaining < 240 && chat.hasMore && !chat.loadingOlder) {
_loadOlder();
}
2026-11-18 19:08:06 +08:00
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(0);
2026-11-18 19:08:06 +08:00
});
}
void _onChat() {
if (mounted) setState(() {});
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(0);
2026-11-18 19:08:06 +08:00
});
}
}
@override
void dispose() {
chat.removeListener(_onChat);
_draftCtrl.dispose();
_inputFocus.dispose();
2026-11-18 19:08:06 +08:00
_scroll.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.session.title.isEmpty ? '会话' : widget.session.title,
maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
2026-11-18 20:48:12 +08:00
Padding(
padding: const EdgeInsets.only(right: 4),
child: ActionChip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.smart_toy_outlined, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 120),
child: Text(_modelLabel(),
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onPressed: () => _openPicker('model'),
),
2026-11-18 19:08:06 +08:00
),
IconButton(
icon: const Icon(Icons.more_vert),
tooltip: '更多操作',
onPressed: _footerMenu,
),
],
),
body: Column(
children: [
if (chat.error != null)
Container(
color: theme.colorScheme.errorContainer,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Row(
children: [
Expanded(
child: Text(chat.error!,
style: TextStyle(
color: theme.colorScheme.onErrorContainer, fontSize: 13))),
TextButton(onPressed: chat.load, child: const Text('重试')),
],
),
),
Expanded(child: _messageList()),
_permissions(),
_composer(),
],
),
);
}
// --------------------------------------------------------------- messages
Widget _messageList() {
if (chat.loading && chat.msgs.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
2026-11-18 19:08:06 +08:00
return ListView.builder(
controller: _scroll,
reverse: true,
itemCount: rows.length + olderSlot,
2026-11-18 19:08:06 +08:00
itemBuilder: (context, i) {
// i counts from the newest row up.
if (i < rows.length) return _row(rows[rows.length - 1 - i]);
if (chat.loadingOlder) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Center(
child: SizedBox(
width: 22, height: 22, child: CircularProgressIndicator(strokeWidth: 2)),
),
);
}
return Center(
child: TextButton(
onPressed: _loadOlder,
child: const Text('载入更早的消息'),
),
);
2026-11-18 19:08:06 +08:00
},
);
}
/// Loads an older page; the reversed list keeps the viewport in place.
Future<void> _loadOlder() async {
if (!chat.hasMore || chat.loadingOlder) return;
await chat.loadOlder();
}
2026-11-18 19:08:06 +08:00
List<_Row> _rows() {
final out = <_Row>[];
for (var mi = 0; mi < chat.msgs.length; mi++) {
final m = chat.msgs[mi];
switch (m.type) {
case 'user':
out.add(_Row('user', m.id, -1));
out.add(_Row('useractions', m.id, -1));
break;
case 'assistant':
// A turn is one or more assistant messages: the server writes a
// message per step, so the whole turn is shown as one run.
var end = mi;
while (end + 1 < chat.msgs.length &&
chat.msgs[end + 1].type == 'assistant') {
end++;
2026-11-18 19:08:06 +08:00
}
_turnRows(out, mi, end);
mi = end;
2026-11-18 19:08:06 +08:00
break;
case 'idle':
// A failed turn also records its error on the idle message. The
// step that failed already prints it, so do not repeat it.
final err = m.error;
if (err != null && !err.isEmpty) {
final prev = mi > 0 ? chat.msgs[mi - 1] : null;
final same = prev?.error;
if (same == null ||
same.message != err.message ||
same.type != err.type) {
out.add(_Row('error', m.id, -1));
}
}
break;
case 'compaction':
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;
2026-11-18 19:08:06 +08:00
case 'shell':
out.add(_Row('shell', m.id, -1));
break;
case 'synthetic':
out.add(_Row('note', m.id, -1));
break;
}
}
return out;
}
void _turnRows(List<_Row> out, int from, int to) {
final pending = <_Step>[];
void flush() {
if (pending.isEmpty) return;
final first = pending.first;
// A lone thought needs no foldable header above it.
if (pending.length == 1 && first.part.type == 'reasoning') {
out.add(_Row('step', first.msgId, first.index));
pending.clear();
return;
}
out.add(_Row('steps', first.msgId, first.index));
pending.clear();
}
for (var i = from; i <= to; i++) {
final m = chat.msgs[i];
if (m.content.isEmpty && m.completed == 0) {
flush();
out.add(_Row('thinking', m.id, -1));
continue;
}
for (var p = 0; p < m.content.length; p++) {
final part = m.content[p];
if (part.type == 'reasoning' || part.type == 'tool') {
pending.add(_Step(m.id, p, part));
} else if (part.type == 'text') {
flush();
out.add(_Row('text', m.id, p));
}
}
}
flush();
final last = chat.msgs[to];
// Only the step that ended the turn speaks for it: a step that failed and
// was followed by another one is not the turn's outcome.
if (last.error != null && !last.error!.isEmpty) {
out.add(_Row('error', last.id, -1));
}
if (last.completed > 0 && _turnEndsAt(to)) {
out.add(_Row('footer', last.id, -1));
}
}
/// A finished run is folded (as in dsh-Go), a running one is open so its
/// steps show while they happen. A tap overrides either default.
bool _groupCollapsed(String id, int start, bool running) {
final k = '$id/$start';
if (_expandedSteps.contains(k)) return false;
if (_collapsedSteps.contains(k)) return true;
return !running;
}
void _toggleGroup(String id, int start, bool collapsed) {
final k = '$id/$start';
setState(() {
if (collapsed) {
_collapsedSteps.remove(k);
_expandedSteps.add(k);
} else {
_expandedSteps.remove(k);
_collapsedSteps.add(k);
}
});
}
/// Whether a step of this run is still going: its own state says so, or the
/// message that carries it has not finished yet.
bool _groupRunning(List<_Step> steps) => steps.any((s) {
final m = chat.byId[s.msgId];
final st = s.part.state?.status ?? '';
return (m != null && m.completed == 0) ||
st == 'running' ||
st == 'streaming' ||
st == 'pending';
});
/// The steps of the run that begins at [msgId]/[index]: consecutive
/// reasoning/tool parts, continuing into the following assistant messages.
List<_Step> _collectGroup(String msgId, int index) {
final out = <_Step>[];
var i = chat.msgs.indexWhere((m) => m.id == msgId);
var p = index;
while (i >= 0 && i < chat.msgs.length) {
final m = chat.msgs[i];
if (p >= m.content.length) {
if (i + 1 < chat.msgs.length &&
chat.msgs[i + 1].type == 'assistant') {
i++;
p = 0;
continue;
}
break;
}
final part = m.content[p];
if (part.type != 'reasoning' && part.type != 'tool') break;
out.add(_Step(m.id, p, part));
p++;
}
return out;
}
2026-11-18 19:08:06 +08:00
bool _turnEndsAt(int i) {
for (var j = i + 1; j < chat.msgs.length; j++) {
if (chat.msgs[j].type == 'assistant') return false;
if (chat.msgs[j].type == 'user' || chat.msgs[j].type == 'synthetic') return true;
}
return true;
}
Widget _row(_Row r) {
switch (r.kind) {
case 'user':
return _userRow(r.msgId);
case 'useractions':
return _userActions(r.msgId);
case 'thinking':
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Text('正在思考…', style: TextStyle(color: Colors.grey, fontSize: 13)),
);
case 'text':
return _textRow(r.msgId, r.part);
case 'steps':
return _stepsBlock(r.msgId, r.part);
case 'step':
return _stepRow(r.msgId, r.part);
2026-11-18 19:08:06 +08:00
case 'footer':
return _footerRow(r.msgId);
case 'error':
return _errorRow(r.msgId);
case 'compaction':
return _compactionRow(r.msgId);
2026-11-18 19:08:06 +08:00
case 'shell':
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(chat.byId[r.msgId]?.text ?? '',
style: const TextStyle(color: Colors.grey, fontSize: 13)),
);
default:
return const SizedBox.shrink();
}
}
Widget _userRow(String id) {
final m = chat.byId[id]!;
final images = chat.imagePaths[id] ?? [];
final theme = Theme.of(context);
return Align(
alignment: Alignment.centerRight,
child: Container(
constraints: const BoxConstraints(maxWidth: 320),
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (m.text.isNotEmpty)
Text(m.text, style: TextStyle(color: theme.colorScheme.onPrimary)),
for (final p in images)
Padding(
padding: const EdgeInsets.only(top: 4),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(File(p), width: 200, height: 150, fit: BoxFit.cover),
),
),
if (m.files.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
m.files.map((f) => '📎 ${f.name}').join('\n'),
style: TextStyle(color: theme.colorScheme.onPrimary, fontSize: 13),
),
),
],
),
),
);
}
Widget _userActions(String id) {
final m = chat.byId[id]!;
final stamp = m.created > 0
? '${DateTime.fromMillisecondsSinceEpoch(m.created).hour.toString().padLeft(2, '0')}:'
'${DateTime.fromMillisecondsSinceEpoch(m.created).minute.toString().padLeft(2, '0')}'
: '';
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (stamp.isNotEmpty)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(stamp, style: const TextStyle(color: Colors.grey, fontSize: 12)),
),
TextButton(
onPressed: () => _copyText(m.text),
child: const Text('复制'),
),
PopupMenuButton<String>(
onSelected: (v) => _userAction(v, m),
itemBuilder: (_) => const [
PopupMenuItem(value: 'copy', child: Text('复制消息')),
PopupMenuItem(value: 'revert', child: Text('撤回此消息及之后')),
PopupMenuItem(value: 'fork', child: Text('从这里分叉')),
],
),
],
);
}
void _userAction(String v, Message m) {
switch (v) {
case 'copy':
_copyText(m.text);
break;
case 'revert':
_confirm(
title: '撤回消息?',
message: '这条消息及其之后的内容会从会话中删除,且无法恢复。',
confirm: '撤回',
onConfirm: () => chat.revert(m.id),
);
break;
case 'fork':
chat.fork(before: m.id);
break;
}
}
/// gpt_markdown builds its widgets with `material_ui`, whose Theme.of has a
/// light fallback: without this the code panel and inline chips stayed light
/// (and their text dark) in the dark theme.
static mui.ThemeData _mdTheme(ThemeData theme) => mui.ThemeData(
useMaterial3: true,
brightness: theme.brightness,
colorScheme: mui.ColorScheme.fromSeed(
seedColor: theme.colorScheme.primary,
brightness: theme.brightness,
),
);
2026-11-18 19:08:06 +08:00
Widget _textRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: _markdown(m.content[part].text),
);
}
Widget _markdown(String text) => mui.Theme(
data: _mdTheme(Theme.of(context)),
child: GptMarkdown(
text,
// The server already streams deltas; show them as they arrive.
isStreaming: false,
style: const TextStyle(fontSize: 15, height: 1.45),
),
);
2026-11-18 19:08:06 +08:00
/// A run of steps: the header, then its rows revealed with an animation.
/// Revealing grows the list below the header, so [_Reveal] reports the
/// height it just added and the list scrolls by it, keeping the header
/// under the finger instead of throwing it off screen.
Widget _stepsBlock(String id, int start) {
final steps = _collectGroup(id, start);
final running = _groupRunning(steps);
final failed = steps.any((s) => s.part.state?.status == 'error');
final collapsed = _groupCollapsed(id, start, running);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_stepsHeader(id, start, steps, collapsed, running, failed),
_Reveal(
open: !collapsed,
onGrow: _grow,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final step in steps) _stepRow(step.msgId, step.index),
],
),
),
],
);
}
/// Keeps the list under a growing run: the reversed list would otherwise
/// push the header up by exactly the height that was just revealed.
void _grow(double delta) {
if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
final p = _scroll.position;
final target = (p.pixels + delta).clamp(p.minScrollExtent, p.maxScrollExtent);
if ((target - p.pixels).abs() > 0.01) _scroll.jumpTo(target);
}
/// "已完成 · 3 次工具调用", with a chevron that folds the whole run.
Widget _stepsHeader(String id, int start, List<_Step> steps, bool collapsed,
bool running, bool failed) {
final theme = Theme.of(context);
final tools = steps.where((s) => s.part.type == 'tool').length;
final label = tools == 0
? (running ? '思考中…' : '思考过程')
: failed
? '有步骤失败 · $tools 次工具调用'
: running
? '执行中 · $tools 次工具调用'
: '已完成 · $tools 次工具调用';
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => _toggleGroup(id, start, collapsed),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row(
children: [
if (running)
const SizedBox(
width: 15,
height: 15,
child: CircularProgressIndicator(strokeWidth: 1.6))
else
Icon(failed ? Icons.error_outline : Icons.check_circle_outline,
size: 16,
color: failed ? theme.colorScheme.error : theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
),
AnimatedRotation(
turns: collapsed ? 0 : 0.5,
duration: const Duration(milliseconds: 180),
child: Icon(Icons.expand_more, size: 18, color: theme.hintColor),
),
],
2026-11-18 19:08:06 +08:00
),
),
2026-11-18 19:08:06 +08:00
);
}
/// One step: a rounded icon, a label, the one-line summary, and details
/// when opened.
Widget _stepRow(String id, int part) {
2026-11-18 19:08:06 +08:00
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final p = m.content[part];
final theme = Theme.of(context);
final reasoning = p.type == 'reasoning';
2026-11-18 19:08:06 +08:00
final status = p.state?.status ?? '';
final busy = status == 'running' || status == 'streaming' || status == 'pending';
final key = 'step/$id/$part';
final open = chat.expanded.contains(key);
final label = _stepLabel(p);
final summary = _stepSummary(p);
// A read of an image is a link to the picture, not a fold.
final image = _imageArg(p);
final refs = reasoning || image != null
? const <_ImageRef>[]
: toolImages(p, chat.dir);
return Container(
margin: const EdgeInsets.only(left: 22),
decoration: BoxDecoration(
border: Border(left: BorderSide(color: theme.dividerColor, width: 1)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: image != null
? () => _openPreview(_ImageRef(image, summary.split('/').last))
: () {
setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
});
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 3, 10, 3),
2026-11-18 19:08:06 +08:00
child: Row(
children: [
Container(
width: 26,
height: 26,
decoration: BoxDecoration(
color: status == 'error'
? theme.colorScheme.errorContainer
: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(7),
),
child: busy
? const Padding(
padding: EdgeInsets.all(6),
child: CircularProgressIndicator(strokeWidth: 1.6),
)
: Icon(_stepIcon(p),
size: 15,
color: status == 'error'
? theme.colorScheme.onErrorContainer
: theme.colorScheme.onSurfaceVariant),
2026-11-18 19:08:06 +08:00
),
const SizedBox(width: 10),
Text(label,
style: TextStyle(
fontSize: 13.5, color: theme.colorScheme.onSurface)),
if (summary.isEmpty)
const Spacer()
else ...[
const SizedBox(width: 6),
Text('·', style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(width: 6),
Expanded(
child: Text(summary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: image != null
? theme.colorScheme.primary
: theme.hintColor)),
),
],
if (image != null)
Icon(Icons.open_in_full,
size: 14, color: theme.colorScheme.primary)
else
Icon(open ? Icons.expand_less : Icons.expand_more,
size: 16, color: theme.hintColor),
2026-11-18 19:08:06 +08:00
],
),
),
),
for (final ref in refs)
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 2),
child: InkWell(
onTap: () => _openPreview(ref),
child: Row(
children: [
const Text('🖼', style: TextStyle(fontSize: 12)),
const SizedBox(width: 6),
Flexible(
child: Text(ref.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: theme.colorScheme.primary)),
),
],
),
2026-11-18 19:08:06 +08:00
),
),
if (image == null)
_Reveal(
open: open,
onGrow: _grow,
child: _stepDetails(p, reasoning),
),
],
),
2026-11-18 19:08:06 +08:00
);
}
static const _imageExts = {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif',
};
/// The file a read/write/edit step points at, when it is an image.
String? _imageArg(ContentPart p) {
if (p.type != 'tool') return null;
// A failed read has no picture to show; it stays a normal, foldable step.
if (p.state?.status == 'error') return null;
final name = p.name ?? '';
if (name != 'read' && name != 'write' && name != 'edit') return null;
final input = p.state?.input ?? const <String, dynamic>{};
final v = input['filePath'] ?? input['path'] ?? input['file'];
if (v is! String || v.isEmpty) return null;
final ext = v.contains('.') ? v.split('.').last.toLowerCase() : '';
if (!_imageExts.contains(ext)) return null;
if (v.startsWith('/') || chat.dir.isEmpty) return v;
return '${chat.dir}/$v';
}
/// The input field already shown by the row's summary.
static String? _primaryInput(ContentPart p) {
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return 'command';
case 'read':
case 'write':
case 'edit':
return 'filePath';
case 'grep':
case 'glob':
case 'find':
return 'pattern';
case 'webfetch':
case 'web_fetch':
return 'url';
case 'task':
return 'description';
case 'skill':
return 'id';
default:
return null;
}
}
static bool _isShell(ContentPart p) =>
const {'bash', 'shell', 'execute'}.contains(p.name ?? '');
/// What the step actually did: the command or path, the rest of the input,
/// and the result — never the request JSON as a blob.
Widget _stepDetails(ContentPart p, bool reasoning) {
final theme = Theme.of(context);
if (reasoning) {
if (p.text.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: SelectableText(p.text,
style: TextStyle(
fontSize: 12.5, height: 1.45, color: theme.hintColor)),
);
}
final input = p.state?.input ?? const <String, dynamic>{};
final primary = _primaryInput(p);
final extras = <MapEntry<String, String>>[
for (final e in input.entries)
if (e.key != primary && '${e.value}'.trim().isNotEmpty)
MapEntry(e.key, '${e.value}'),
];
final shell = _isShell(p);
final command = shell ? '${input['command'] ?? ''}'.trim() : '';
final output = toolOutput(p);
// A big output arrives as an empty shell until the message is fetched;
// that is not the same as a command that printed nothing.
final shelled = shell &&
(p.state?.metadata?.containsKey('openchamberContentShell') ?? false);
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (command.isNotEmpty)
SelectableText(command,
style: mono.copyWith(color: theme.colorScheme.onSurface)),
if (command.isNotEmpty) const SizedBox(height: 6),
for (final e in extras)
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Text('${e.key}: ${e.value}',
style: mono.copyWith(
fontSize: 11.5, color: theme.hintColor)),
),
if (extras.isNotEmpty) const SizedBox(height: 4),
SelectableText(
output.isNotEmpty
? output
: shelled
? '输出较大,正在载入…'
: (shell ? '无输出' : '无内容'),
style: mono.copyWith(
color: p.state?.error != null
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
);
}
static IconData _stepIcon(ContentPart p) {
if (p.type == 'reasoning') return Icons.psychology_outlined;
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return Icons.terminal;
case 'read':
return Icons.description_outlined;
case 'write':
return Icons.note_add_outlined;
case 'edit':
return Icons.edit_outlined;
case 'patch':
case 'apply_patch':
return Icons.difference_outlined;
case 'grep':
return Icons.search;
case 'glob':
case 'find':
return Icons.travel_explore;
case 'list':
return Icons.format_list_bulleted;
case 'webfetch':
case 'web_fetch':
return Icons.language;
case 'todowrite':
return Icons.checklist_rtl;
case 'task':
return Icons.smart_toy_outlined;
case 'skill':
return Icons.extension_outlined;
default:
return Icons.handyman_outlined;
}
}
static String _stepLabel(ContentPart p) {
if (p.type == 'reasoning') return '思考';
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return '运行';
case 'read':
return '读取';
case 'write':
return '写入';
case 'edit':
return '编辑';
case 'patch':
case 'apply_patch':
return '补丁';
case 'grep':
case 'glob':
case 'find':
return '搜索';
case 'list':
return '列出';
case 'webfetch':
case 'web_fetch':
return '抓取';
case 'todowrite':
return '任务';
case 'task':
return '子任务';
case 'skill':
return '技能';
default:
return p.name == null || p.name!.isEmpty ? '工具' : p.name!;
}
}
/// One line that says what the step is about, so a folded run stays useful.
static String _stepSummary(ContentPart p) {
if (p.type == 'reasoning') return _firstLine(p.text);
final input = p.state?.input ?? const <String, dynamic>{};
String one(Object? v) =>
(v ?? '').toString().replaceAll(RegExp(r'\s+'), ' ').trim();
switch (p.name ?? '') {
case 'bash':
case 'shell':
case 'execute':
return one(input['command']);
case 'read':
case 'write':
case 'edit':
return one(input['filePath'] ?? input['path'] ?? input['file']);
case 'grep':
case 'glob':
case 'find':
return one(input['pattern']);
case 'webfetch':
case 'web_fetch':
return one(input['url']);
case 'task':
return one(input['description'] ?? input['prompt']);
case 'skill':
return one(input['id'] ?? input['name']);
default:
for (final k in const [
'description', 'filePath', 'path', 'command', 'query', 'url',
'pattern', 'name', 'id',
]) {
final v = one(input[k]);
if (v.isNotEmpty) return v;
}
if (input.isEmpty) return '';
return one(const JsonEncoder().convert(input));
}
}
static String _firstLine(String text) {
for (final line in const LineSplitter().convert(text)) {
final t = line.replaceAll(RegExp(r'^[\s#>*\-]+'), '').trim();
if (t.isNotEmpty) return t;
}
return '';
}
2026-11-18 19:08:06 +08:00
Widget _footerRow(String id) {
final m = chat.byId[id]!;
final parts = <String>[];
if (m.model != null) parts.add(widget.app.modelName(m.model));
if (m.agent.isNotEmpty) parts.add(m.agent);
if (m.completed > 0) parts.add(_turnDuration(m));
return Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(parts.join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: Colors.grey, fontSize: 13)),
),
),
PopupMenuButton<String>(
onSelected: (v) => _footerAction(v, m),
itemBuilder: (_) => const [
PopupMenuItem(value: 'copy', child: Text('复制回答')),
PopupMenuItem(value: 'fork', child: Text('从这里分叉')),
],
),
],
);
}
/// Whether an error detail looks like an authentication failure (the same
/// reading the official client does, so the sentence matches).
static bool _isAuthError(String detail) {
final d = detail.toLowerCase().trim();
if (d.isEmpty) return false;
if (d.contains('token refresh failed') ||
d.contains('unauthorized') ||
d.contains('invalid token') ||
d.contains('expired token')) {
return true;
}
if (d.contains('oauth') &&
(d.contains('failed') || d.contains('invalid') || d.contains('expired'))) {
return true;
}
final has401 = RegExp(r'\b401\b').hasMatch(d);
return has401 &&
(d.contains('auth') || d.contains('token') || d.contains('unauthorized'));
}
/// What a failed step says in the transcript, close to the official
/// client's wording; the provider's raw response is kept for details.
static ({String text, String? body}) _errorNotice(Message m) {
final e = m.error;
final detail = (e != null && e.message.isNotEmpty)
? e.message
: (e != null && e.type.isNotEmpty ? e.type : '未知错误');
final type = (e?.type ?? '').toLowerCase();
final plain = detail.trim().toLowerCase().replaceFirst(RegExp(r'\.$'), '');
if (m.type == 'compaction') {
return (text: '压缩失败:$detail', body: e?.body);
}
if (type == 'sessionretry') {
return (text: 'OpenCode 发送消息失败,正在重试:$detail', body: e?.body);
}
if (_isAuthError(detail)) {
return (
text: '模型的认证失败,请在服务端重新登录或检查 API Key。',
body: e?.body
);
}
if (type == 'messageabortederror' ||
plain == 'aborted' ||
plain == 'step interrupted') {
return (text: '本轮已停止。', body: null);
}
return (text: 'OpenCode 发送消息失败:$detail', body: e?.body);
}
static String _prettyBody(String raw) {
try {
return const JsonEncoder.withIndent(' ').convert(jsonDecode(raw));
} catch (_) {
return raw;
}
}
/// 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) {
final m = chat.byId[id];
if (m == null) return const SizedBox.shrink();
final notice = _errorNotice(m);
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final key = 'error/$id';
final open = chat.expanded.contains(key);
final raw = notice.body?.trim() ?? '';
final body = raw.isEmpty ? null : _prettyBody(raw);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
child: Container(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
decoration: BoxDecoration(
color: scheme.error.withValues(alpha: 0.08),
border: Border.all(color: scheme.error.withValues(alpha: 0.28)),
borderRadius: BorderRadius.circular(14),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.error_outline, size: 18, color: scheme.error),
const SizedBox(width: 8),
Expanded(
child: SelectableText(notice.text,
style: const TextStyle(fontSize: 13.5, height: 1.45)),
),
],
),
if (body != null) ...[
Padding(
padding: const EdgeInsets.only(left: 26),
child: TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
minimumSize: const Size(0, 30),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
foregroundColor: scheme.onSurfaceVariant,
),
onPressed: () => setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
}),
child: Text(open ? '收起详情' : '显示详情',
style: const TextStyle(fontSize: 12.5)),
),
),
if (open)
Container(
width: double.infinity,
margin: const EdgeInsets.only(left: 26, top: 4),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: SelectableText(body,
style: const TextStyle(
fontSize: 11.5, height: 1.45, fontFamily: 'monospace')),
),
],
],
),
),
);
}
2026-11-18 19:08:06 +08:00
String _turnDuration(Message m) {
var start = 0;
final idx = chat.msgs.indexWhere((x) => x.id == m.id);
for (var i = idx - 1; i >= 0; i--) {
if (chat.msgs[i].type == 'user') {
start = chat.msgs[i].created;
break;
}
}
if (start <= 0) return '';
final secs = ((m.completed - start) / 1000).round();
if (secs <= 0) return '';
2026-11-18 19:08:06 +08:00
if (secs < 60) return '$secs 秒';
return '${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';
}
void _footerAction(String v, Message m) {
switch (v) {
case 'copy':
_copyText(m.partText);
break;
case 'fork':
chat.fork();
break;
}
}
void _footerMenu() {
final chat_ = chat;
Message? last;
for (var i = chat_.msgs.length - 1; i >= 0; i--) {
if (chat_.msgs[i].type == 'assistant' && chat_.msgs[i].completed > 0) {
last = chat_.msgs[i];
break;
}
}
if (last == null) return;
showModalBottomSheet(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: const Text('复制回答'),
onTap: () {
Navigator.pop(context);
_copyText(last!.partText);
},
),
ListTile(
title: const Text('从这里分叉'),
onTap: () {
Navigator.pop(context);
chat_.fork();
},
),
const SizedBox(height: 8),
],
),
),
);
}
Future<void> _copyText(String text) async {
if (text.trim().isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('没有可复制的文字')));
return;
}
await Clipboard.setData(ClipboardData(text: text));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已复制')));
}
}
// ------------------------------------------------------------ composer
2026-11-18 20:48:12 +08:00
// The composer follows dsh-Go's input bar: a rounded capsule holding a
// leading key, an auto-growing borderless field, the usage ring and a
// trailing send/stop key, all 36px round keys (MIT, app/lib/ui/chat/
// composer.dart, referenced rather than copied).
/// Chinese faces for the first-party commands, as dsh-Go shows them; the
/// registry's name is what is sent.
static const _slashLabels = {
'compact': '压缩',
'init': '初始化',
'review': '审查',
'goal': '目标',
'new-extension': '新建扩展',
'permission': '权限',
'plan': '计划',
'feedback': '反馈',
};
static String? _slashLabel(SlashItem item) =>
item.skill ? null : _slashLabels[item.name];
/// Rows for the current draft, or null when the palette is closed. It
/// stays up while the command name is being typed and closes once an
/// argument has started.
List<SlashItem>? _slashMatches() {
final text = _draftCtrl.text;
if (_slashDismissed == text) return null;
final t = text.trimLeft();
if (!t.startsWith('/')) return null;
if (t.length > 1 && RegExp(r'\s').hasMatch(t.substring(1))) return null;
final q = t.substring(1).toLowerCase().trim();
final all = chat.slashItems;
if (q.isEmpty) return all;
bool hit(SlashItem e) {
final label = _slashLabel(e) ?? '';
return e.name.toLowerCase().contains(q) ||
label.toLowerCase().contains(q) ||
e.description.toLowerCase().contains(q);
}
final matches = all.where(hit).toList()
..sort((a, b) {
final ap = a.name.toLowerCase().startsWith(q) ? 0 : 1;
final bp = b.name.toLowerCase().startsWith(q) ? 0 : 1;
if (ap != bp) return ap - bp;
if (a.skill != b.skill) return a.skill ? 1 : -1;
return a.name.compareTo(b.name);
});
return matches;
}
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() {
setState(() => _slashDismissed = _draftCtrl.text);
}
/// A row was picked. Commands that take no argument run right away (as in
/// dsh-Go); the rest complete the name and wait for the arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _draftCtrl.text;
final lead = text.length - text.trimLeft().length;
final rest = text.trimLeft();
final match = RegExp(r'\s').firstMatch(rest);
final suffix = match == null ? '' : rest.substring(match.start);
final completes = item.skill || item.takesArgs;
if (!completes) {
final command = '/${item.name}';
_draftCtrl.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
chat.draft = command;
setState(() {});
_send();
return;
}
final prefix = '${text.substring(0, lead)}/${item.name}';
final separator =
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
final next = '$prefix$separator$suffix';
_draftCtrl.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
chat.draft = next;
_inputFocus.requestFocus();
setState(() {});
}
/// The palette above the composer: dsh-Go's `/` menu, on the app's theme.
Widget _slashPalette(List<SlashItem> items) {
final scheme = Theme.of(context).colorScheme;
final typed = _draftCtrl.text.trimLeft().length > 1;
final index = items.isEmpty ? 0 : _slashIndex.clamp(0, items.length - 1);
Widget row(IconData icon, String title, String subtitle) => Padding(
padding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(icon, size: 20, color: scheme.onSurfaceVariant),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: TextStyle(
fontSize: 14, color: scheme.onSurface)),
if (subtitle.isNotEmpty)
Text(subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: scheme.onSurfaceVariant)),
],
),
),
],
),
);
return Container(
constraints: const BoxConstraints(maxHeight: 56 * 5.5),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: scheme.outlineVariant.withValues(alpha: 0.6)),
),
child: items.isEmpty
? (chat.slashLoading
? const Padding(
padding: EdgeInsets.all(18),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
: row(Icons.search_off, '没有可用的指令', '这个目录还没有注册指令或技能'))
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
itemCount: items.length,
itemBuilder: (context, i) {
final item = items[i];
final label = _slashLabel(item);
final selected = i == index;
final scheme = Theme.of(context).colorScheme;
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => _pickSlash(item),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color:
selected ? scheme.primary.withValues(alpha: 0.10) : null,
borderRadius: BorderRadius.circular(14),
),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(
item.skill
? Icons.extension_outlined
: Icons.terminal,
size: 20,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (label != null) ...[
Text(label,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500)),
const SizedBox(width: 8),
],
Flexible(
child: Text('/${item.name}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
color: scheme.onSurfaceVariant)),
),
if (item.skill) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: scheme.secondaryContainer,
borderRadius:
BorderRadius.circular(6),
),
child: Text('技能',
style: TextStyle(
fontSize: 10.5,
color:
scheme.onSecondaryContainer)),
),
],
],
),
if (item.description.isNotEmpty)
Text(item.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
if (selected && typed)
Icon(Icons.keyboard_return,
size: 16, color: scheme.onSurfaceVariant),
],
),
),
);
},
),
);
}
2026-11-18 19:08:06 +08:00
Widget _composer() {
final usage = chat.usageReading();
2026-11-18 20:48:12 +08:00
final scheme = Theme.of(context).colorScheme;
final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty;
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = Padding(
2026-11-18 20:48:12 +08:00
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
2026-11-18 19:08:06 +08:00
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
2026-11-18 20:48:12 +08:00
if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('slash-palette'),
child: _slashPalette(slashRows),
),
const SizedBox(height: 6),
],
2026-11-18 20:48:12 +08:00
Container(
key: const ValueKey('composer-bar'),
2026-11-18 20:48:12 +08:00
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(26),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_roundKey(
icon: Icons.attach_file,
label: '添加附件',
onTap: _pickFiles,
busy: _attaching,
),
const SizedBox(width: 4),
Expanded(
child: TextField(
controller: _draftCtrl,
focusNode: _inputFocus,
2026-11-18 20:48:12 +08:00
minLines: 1,
maxLines: 5,
keyboardType: TextInputType.multiline,
// While the palette is up, the keyboard's action key
// picks the highlighted row instead of writing a
// newline.
textInputAction: slash != null
? TextInputAction.send
: TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
2026-11-18 20:48:12 +08:00
onChanged: (v) {
chat.draft = v;
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) chat.ensureSlash();
2026-11-18 20:48:12 +08:00
setState(() {});
// A soft keyboard whose action key still writes a
// newline commits the highlighted row instead of
// leaving a stray blank line in the draft.
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_draftCtrl.value = TextEditingValue(
text: trimmed,
selection:
TextSelection.collapsed(offset: trimmed.length),
);
chat.draft = trimmed;
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
2026-11-18 20:48:12 +08:00
},
style: const TextStyle(fontSize: 15, height: 1.45),
decoration: InputDecoration(
hintText: chat.running ? '生成中,仍可输入…' : '发消息…',
hintMaxLines: 1,
isDense: true,
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 8),
),
),
),
if (usage.$5)
InkWell(
onTap: () => _usageSheet(context),
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
UsageRing(pct: usage.$4, size: 16, accent: scheme.primary),
const SizedBox(width: 3),
Text('${usage.$4.round()}%',
style: TextStyle(fontSize: 12, color: scheme.onSurfaceVariant)),
],
2026-11-18 19:08:06 +08:00
),
),
2026-11-18 20:48:12 +08:00
),
const SizedBox(width: 2),
_roundKey(
icon: chat.running ? Icons.stop_rounded : Icons.arrow_upward_rounded,
label: chat.running ? '停止' : '发送',
filled: true,
enabled: chat.running || canSend,
onTap: chat.running ? chat.stop : _send,
),
],
2026-11-18 19:08:06 +08:00
),
),
],
),
);
// Always wrapped: re-parenting the field when the palette opens would
// drop its focus, and with it the characters typed after `/`.
return SafeArea(
top: false,
child: CallbackShortcuts(
bindings: slash == null
? const {}
: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSlash(slashRows, 1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSlash(slashRows, -1),
const SingleActivator(LogicalKeyboardKey.enter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.escape): _dismissSlash,
},
child: body,
2026-11-18 19:08:06 +08:00
),
);
}
2026-11-18 20:48:12 +08:00
/// One 36px round key of the input bar.
Widget _roundKey({
required IconData icon,
required String label,
required VoidCallback onTap,
bool filled = false,
bool enabled = true,
bool busy = false,
}) {
final scheme = Theme.of(context).colorScheme;
final on = enabled && !busy;
final bg = filled
? (on ? scheme.primary : scheme.onSurface.withValues(alpha: 0.12))
: scheme.onSurface.withValues(alpha: 0.06);
final fg = filled
? (on ? scheme.onPrimary : scheme.onSurface.withValues(alpha: 0.38))
: scheme.onSurface;
return Semantics(
button: true,
enabled: on,
label: label,
child: Material(
color: bg,
shape: const CircleBorder(),
child: InkWell(
customBorder: const CircleBorder(),
onTap: on ? onTap : null,
child: SizedBox(
width: 36,
height: 36,
child: Center(
child: busy
? SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2, color: fg),
)
: Icon(icon, size: 20, color: fg),
),
),
),
),
);
}
/// Attachment chips with a thumbnail, unfolded above the input bar.
Widget _attachmentTray() {
return SizedBox(
height: 46,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (var i = 0; i < _attachments.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: InputChip(
avatar: _attachments[i].path != null
? CircleAvatar(
backgroundImage: FileImage(File(_attachments[i].path!)),
)
: const Icon(Icons.insert_drive_file, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 160),
child: Text(_attachments[i].name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onDeleted: () => setState(() => _attachments.removeAt(i)),
),
),
],
),
);
}
String _modelLabel() {
final m = chat.selectedModel ?? widget.session.model;
2026-11-18 20:48:12 +08:00
final model = m == null ? '模型' : widget.app.modelName(m);
final agent = chat.selectedAgent;
2026-11-18 20:48:12 +08:00
return agent.isEmpty ? model : '$model · $agent';
}
2026-11-18 19:08:06 +08:00
Future<void> _send() async {
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// Files ride with the prompt as data URLs.
final files = <Map<String, String>>[];
final images = <String>[];
for (final a in _attachments) {
files.add({'uri': a.dataUrl, 'name': a.name});
if (a.mime.startsWith('image/') && a.path != null) {
images.add(a.path!);
}
}
final id = await chat.send(text: text, files: files);
if (id == null) {
// The prompt failed: keep the text for a retry.
_draftCtrl.text = chat.draft;
return;
}
2026-11-18 19:08:06 +08:00
_draftCtrl.clear();
setState(() => _attachments = []);
if (images.isNotEmpty && id.isNotEmpty) {
2026-11-18 19:08:06 +08:00
chat.imagePaths[id] = images;
chat.touch();
}
2026-11-18 20:48:12 +08:00
HapticFeedback.lightImpact();
2026-11-18 19:08:06 +08:00
}
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final files = await FilePicker.pickFiles();
if (files.isEmpty) return;
for (final f in files) {
final bytes = await f.readAsBytes();
if (bytes.length > 10 * 1024 * 1024) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('附件不能超过 10MB')));
continue;
}
final name = f.name;
final mime = _mime(name);
final dataUrl = 'data:$mime;base64,${base64Encode(bytes)}';
String? keptPath;
if (mime.startsWith('image/') && f.path != null) {
keptPath = await _keepImage(f.path!, name);
}
setState(() {
if (_attachments.length >= 5) return;
_attachments.add(_Attach(name: name, mime: mime, dataUrl: dataUrl, path: keptPath));
});
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('选择失败:$e')));
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
Future<String?> _keepImage(String src, String name) async {
try {
// No plugin needed: a cache copy is enough for the message being sent.
final d = Directory('${Directory.systemTemp.path}/openchamber-attachments');
2026-11-18 19:08:06 +08:00
await d.create(recursive: true);
final dst = '${d.path}/${DateTime.now().microsecondsSinceEpoch}-${name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}';
await File(src).copy(dst);
return dst;
} catch (_) {
return null;
}
}
static String _mime(String name) {
final ext = name.contains('.') ? name.split('.').last.toLowerCase() : '';
switch (ext) {
case 'png': return 'image/png';
case 'jpg': case 'jpeg': return 'image/jpeg';
case 'gif': return 'image/gif';
case 'webp': return 'image/webp';
case 'pdf': return 'application/pdf';
case 'txt': return 'text/plain';
case 'json': return 'application/json';
default: return 'application/octet-stream';
}
}
// ---------------------------------------------------------- permissions
Widget _permissions() {
final perms = widget.app.perms
.where((p) => p.sessionId.isEmpty || p.sessionId == chat.id)
.toList();
if (perms.isEmpty) return const SizedBox.shrink();
return Column(
children: [
for (final p in perms)
Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('请求权限: ${p.action}',
style: const TextStyle(fontWeight: FontWeight.w600)),
Text(p.resources.join('、'),
style: const TextStyle(color: Colors.grey, fontSize: 13)),
const SizedBox(height: 6),
Row(
children: [
TextButton(
onPressed: () => chat.replyPermission(p.id, 'once'),
child: const Text('允许一次')),
TextButton(
onPressed: () => chat.replyPermission(p.id, 'always'),
child: const Text('总是允许')),
TextButton(
onPressed: () => chat.replyPermission(p.id, 'reject'),
child: const Text('拒绝')),
],
),
],
),
),
),
],
);
}
// -------------------------------------------------------------- sheets
void _openPicker(String kind) {
widget.app.refreshModels();
setState(() {
_pickerOpen = true;
_pickerKind = kind;
_pickerFilter = '';
});
_pickerSheet(context);
}
void _pickerSheet(BuildContext context) {
if (!_pickerOpen) return;
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.8,
maxChildSize: 0.92,
builder: (context, controller) => ListenableBuilder(
listenable: chat,
builder: (context, _) {
final title = _pickerKind == 'agent' ? '选择智能体' : '选择模型';
return Column(
children: [
Padding(
2026-11-18 20:48:12 +08:00
padding: const EdgeInsets.fromLTRB(12, 12, 12, 4),
2026-11-18 19:08:06 +08:00
child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
2026-11-18 20:48:12 +08:00
child: SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'model', label: Text('模型')),
ButtonSegment(value: 'agent', label: Text('智能体')),
],
selected: {_pickerKind},
showSelectedIcon: false,
onSelectionChanged: (s) {
setState(() => _pickerKind = s.first);
widget.app.refreshModels();
},
),
),
Padding(
padding: const EdgeInsets.all(12),
2026-11-18 19:08:06 +08:00
child: TextField(
onChanged: (v) => setState(() => _pickerFilter = v),
decoration: const InputDecoration(hintText: '搜索', border: OutlineInputBorder(), isDense: true),
),
),
Expanded(
child: _pickerItems(controller),
),
],
);
},
),
),
).then((_) => _pickerOpen = false);
}
Widget _pickerItems(ScrollController controller) {
final filter = _pickerFilter.toLowerCase();
// (key, title, modelOrAgent, selected)
final items = <(String, String, Object?, bool)>[];
2026-11-18 19:08:06 +08:00
if (_pickerKind == 'model') {
final current = chat.selectedModel;
2026-11-18 19:08:06 +08:00
for (final m in widget.app.modelList) {
final selected = current != null &&
current.providerId == m.providerId &&
current.id == m.id;
items.add(
('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId), selected));
2026-11-18 19:08:06 +08:00
}
} else {
for (final a in widget.app.agentList) {
// Compaction, Title and Summary are primary but hidden.
if (a.mode != 'primary' || a.hidden) continue;
items.add(('agent/${a.id}', a.name, a.id, chat.selectedAgent == a.id));
2026-11-18 19:08:06 +08:00
}
}
final visible = items
.where((e) => filter.isEmpty || e.$2.toLowerCase().contains(filter))
.toList();
if (visible.isEmpty) {
return const Center(child: Text('没有结果'));
}
return ListView.builder(
controller: controller,
itemCount: visible.length,
itemBuilder: (context, i) {
final it = visible[i];
return ListTile(
title: Text(it.$2),
trailing: it.$4 ? const Icon(Icons.check) : null,
2026-11-18 19:08:06 +08:00
onTap: () {
Navigator.pop(context);
setState(() => _pickerOpen = false);
if (it.$3 is ModelRef) {
chat.switchModel(it.$3 as ModelRef);
} else {
chat.switchAgent(it.$3 as String);
}
},
);
},
);
}
void _confirm({required String title, required String message, required String confirm, required VoidCallback onConfirm}) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(message),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () {
Navigator.pop(context);
onConfirm();
},
child: Text(confirm),
),
],
),
);
}
// ------------------------------------------------------------ previews
Future<void> _openPreview(_ImageRef ref) async {
await showDialog(
2026-11-18 19:08:06 +08:00
context: context,
builder: (_) => _ImagePreviewDialog(
title: ref.label,
source: ref.source,
directory: chat.dir,
client: widget.app.client!,
2026-11-18 19:08:06 +08:00
),
);
}
// ------------------------------------------------------------ usage
void _usageSheet(BuildContext context) {
final r = chat.usageReading();
showModalBottomSheet(
context: context,
builder: (context) => Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('上下文占用', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 12),
_usageRow('模型', widget.app.modelName(chat.selectedModel ?? _lastModel())),
2026-11-18 19:08:06 +08:00
_usageRow('已用 tokens', _fmtTokens(r.$1)),
if (r.$5) ...[
_usageRow('上下文上限', _fmtTokens(r.$2)),
_usageRow('输出预留', _fmtTokens(r.$3)),
_usageRow('占用', '${r.$4.toStringAsFixed(1)}%'),
],
if (chat.turnCost > 0) _usageRow('本轮费用', '\$${chat.turnCost.toStringAsFixed(4)}'),
const SizedBox(height: 8),
const Text('输出预留按最多 32K tokens 计算,与官方客户端一致。',
style: TextStyle(color: Colors.grey, fontSize: 12)),
],
),
),
);
2026-11-18 19:08:06 +08:00
}
ModelRef? _lastModel() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
if (chat.msgs[i].model != null) return chat.msgs[i].model;
}
return null;
}
Widget _usageRow(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Expanded(child: Text(label, style: const TextStyle(color: Colors.grey))),
Text(value),
],
),
);
static String _fmtTokens(int n) {
if (n >= 1000000) return '${(n / 1000000).toStringAsFixed(1)}M';
if (n >= 1000) return '${(n / 1000).toStringAsFixed(1)}K';
return '$n';
}
}
class _Row {
final String kind;
final String msgId;
final int part;
_Row(this.kind, this.msgId, this.part);
}
/// Height animation for a fold: the body grows from its top edge and fades in,
/// reporting each bit of height it adds so the list can hold its header still.
/// Same behaviour as dsh-Go's ExpandReveal (MIT).
class _Reveal extends StatefulWidget {
final bool open;
final Widget child;
final ValueChanged<double>? onGrow;
const _Reveal({
required this.open,
required this.child,
this.onGrow,
});
@override
State<_Reveal> createState() => _RevealState();
}
class _RevealState extends State<_Reveal>
with SingleTickerProviderStateMixin {
late final AnimationController _c = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 280),
value: widget.open ? 1 : 0,
)..addListener(_tick);
late final Animation<double> _size = CurvedAnimation(
parent: _c,
curve: Curves.easeInOutCubic,
reverseCurve: Curves.easeInOutCubic.flipped);
late final Animation<double> _fade = CurvedAnimation(
parent: _c, curve: const Interval(0.3, 1, curve: Curves.easeOut));
final GlobalKey _body = GlobalKey();
double? _shown;
@override
void didUpdateWidget(_Reveal old) {
super.didUpdateWidget(old);
if (widget.open == old.open) return;
// A fold nobody can see (a finished run far up the history) must not
// animate or drag the view: it just takes its new size.
if (!_headerOnScreen()) {
_c.value = widget.open ? 1 : 0;
return;
}
// Every pixel the fold adds or removes is reported from here on, so the
// list can hold the header still for the whole animation. Expanding starts
// from zero; collapsing starts from the height already on screen.
final box = _body.currentContext?.findRenderObject() as RenderBox?;
_shown = widget.open || box == null || !box.hasSize ? 0 : box.size.height;
widget.open ? _c.forward() : _c.reverse();
}
/// Whether this fold's header (the row right above it) is in view.
bool _headerOnScreen() {
final self = context.findRenderObject();
final scroll = Scrollable.maybeOf(context);
if (self is! RenderBox || !self.attached || scroll == null) return true;
final viewport = scroll.context.findRenderObject();
if (viewport is! RenderBox || !viewport.attached) return true;
final top = self.localToGlobal(Offset.zero).dy;
final vTop = viewport.localToGlobal(Offset.zero).dy;
return top > vTop + 24 && top < vTop + viewport.size.height;
}
@override
void dispose() {
_c.dispose();
super.dispose();
}
void _tick() {
final box = _body.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.hasSize) {
if (_size.value > 0) {
WidgetsBinding.instance.addPostFrameCallback((_) => _tick());
}
return;
}
final shown = _size.value * box.size.height;
final before = _shown;
_shown = shown;
if (before == null) return;
final delta = shown - before;
if (delta.abs() > 0.01) widget.onGrow?.call(delta);
}
@override
Widget build(BuildContext context) {
if (!widget.open && _c.isDismissed) return const SizedBox.shrink();
return SizeTransition(
sizeFactor: _size,
axisAlignment: -1,
child: FadeTransition(
opacity: _fade,
child: KeyedSubtree(key: _body, child: widget.child),
),
);
}
}
/// One reasoning or tool part, addressed across the assistant messages of a
/// turn.
class _Step {
final String msgId;
final int index;
final ContentPart part;
const _Step(this.msgId, this.index, this.part);
}
2026-11-18 19:08:06 +08:00
class _Attach {
final String name;
final String mime;
final String dataUrl;
final String? path;
_Attach({required this.name, required this.mime, required this.dataUrl, this.path});
}
class _ImageRef {
final String source;
final String label;
_ImageRef(this.source, this.label);
}
List<_ImageRef> toolImages(ContentPart p, String dir) {
const exts = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.avif'};
final out = <_ImageRef>[];
final seen = <String>{};
final labels = <String>{};
void add(String source, String label) {
source = source.trim();
if (source.startsWith('file://')) source = source.substring(7);
if (source.isEmpty || seen.contains(source)) return;
if (!source.startsWith('data:')) {
if (source.contains('://')) return;
if (!source.startsWith('/')) {
if (dir.isEmpty) return;
source = '$dir/$source';
}
final ext = source.contains('.') ? '.${source.split('.').last.toLowerCase()}' : '';
if (!exts.contains(ext)) return;
if (label.isEmpty) {
label = source.split('/').last;
}
if (labels.contains(label)) return;
}
if (label.isEmpty) label = '图片';
seen.add(source);
labels.add(label);
out.add(_ImageRef(source, label));
}
final st = p.state;
if (st != null) {
var attachments = 0;
for (final c in [...st.attachments, ...st.content]) {
if (c.type == 'file' && (c.mime ?? '').startsWith('image/')) {
final src = (c.url?.isNotEmpty ?? false) ? c.url! : c.uri;
if (src != null && src.isNotEmpty) {
attachments++;
add(src, c.filename ?? '');
}
} else if (c.type == 'text') {
final re = RegExp(r'(/[^\s"' + r'`' + r'()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))');
for (final m in re.allMatches(c.text)) {
add(m.group(1)!, '');
}
}
}
if (attachments == 0) {
for (final k in ['filePath', 'path', 'file', 'file_path', 'sourcePath']) {
final v = st.input[k];
if (v is String) add(v, '');
}
}
}
return out;
}
String toolOutput(ContentPart p) {
final st = p.state;
if (st == null) return '';
final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n');
if (out.isNotEmpty) return out;
for (final key in const ['output', 'result', 'stdout', 'text', 'content']) {
final v = st.metadata?[key];
if (v is String && v.isNotEmpty) return v;
}
return st.error ?? '';
2026-11-18 19:08:06 +08:00
}
/// A full-screen-ish image preview that loads itself: the dialog is created
/// first, so the image and its spinner must live in a StatefulWidget.
class _ImagePreviewDialog extends StatefulWidget {
final String title;
final String source;
final String directory;
final Client client;
const _ImagePreviewDialog({
required this.title,
required this.source,
required this.directory,
required this.client,
});
@override
State<_ImagePreviewDialog> createState() => _ImagePreviewDialogState();
}
class _ImagePreviewDialogState extends State<_ImagePreviewDialog> {
Uint8List? _bytes;
Object? _error;
bool _loading = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
// Decoded straight from memory: no temp file, no platform plugin.
final bytes = await _fetch();
if (mounted) {
setState(() {
_bytes = bytes;
_loading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e;
_loading = false;
});
}
}
}
Future<Uint8List> _fetch() async {
final source = widget.source;
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception('无效的 data URL');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final bytes =
await widget.client.rawFile(source, directory: widget.directory);
return Uint8List.fromList(bytes);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
Widget body;
if (_loading) {
body = const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
);
} else if (_bytes != null) {
body = Flexible(child: Image.memory(_bytes!, fit: BoxFit.contain));
} else {
body = Padding(
padding: const EdgeInsets.all(24),
child: SelectableText('无法预览:$_error',
style: TextStyle(color: theme.colorScheme.error)),
);
}
return Dialog(
insetPadding: const EdgeInsets.all(12),
child: ConstrainedBox(
constraints:
BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 4, 0),
child: Row(
children: [
Expanded(
child: Text(widget.title,
maxLines: 2, overflow: TextOverflow.ellipsis),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭',
onPressed: () => Navigator.pop(context),
),
],
),
),
body,
const SizedBox(height: 8),
],
),
),
);
}
}