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

1058 lines
34 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/services.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
2026-11-18 19:08:06 +08:00
import 'package:path_provider/path_provider.dart';
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 ScrollController _scroll = ScrollController();
bool _stick = true;
bool _pickerOpen = false;
String _pickerKind = 'model';
String _pickerFilter = '';
bool _usageOpen = false;
String _previewTitle = '';
File? _previewFile;
bool _previewLoading = false;
List<_Attach> _attachments = [];
bool _attaching = false;
@override
void initState() {
super.initState();
chat.addListener(_onChat);
_scroll.addListener(() {
final atEnd = _scroll.position.pixels >=
_scroll.position.maxScrollExtent - 40;
if (_stick != atEnd) setState(() => _stick = atEnd);
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
});
}
void _onChat() {
if (mounted) setState(() {});
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
}
@override
void dispose() {
chat.removeListener(_onChat);
_draftCtrl.dispose();
_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: [
IconButton(
icon: const Icon(Icons.tune),
tooltip: '模型与智能体',
onPressed: () => _openPicker('model'),
),
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();
return ListView.builder(
controller: _scroll,
itemCount: rows.length,
itemBuilder: (context, i) {
final r = rows[i];
return _row(r);
},
);
}
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':
if (m.content.isEmpty && m.completed == 0) {
out.add(_Row('thinking', m.id, -1));
continue;
}
for (var i = 0; i < m.content.length; i++) {
final t = m.content[i].type;
if (t == 'text' || t == 'reasoning' || t == 'tool') {
out.add(_Row(t, m.id, i));
}
}
if (m.completed > 0 && _turnEndsAt(mi)) {
out.add(_Row('footer', m.id, -1));
}
break;
case 'shell':
out.add(_Row('shell', m.id, -1));
break;
case 'synthetic':
out.add(_Row('note', m.id, -1));
break;
}
}
return out;
}
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 'reasoning':
return _reasoningRow(r.msgId, r.part);
case 'tool':
return _toolRow(r.msgId, r.part);
case 'footer':
return _footerRow(r.msgId);
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;
}
}
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: 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
),
);
}
Widget _reasoningRow(String id, int part) {
final m = chat.byId[id]!;
final key = 'reasoning/$id/$part';
final open = chat.expanded.contains(key);
final text = part < m.content.length ? m.content[part].text : '';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () => setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
}),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: Text('已思考 ${open ? '▾' : '▸'}',
style: const TextStyle(color: Colors.grey, fontSize: 13)),
),
),
if (open && text.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: Text(text,
style: const TextStyle(color: Colors.grey, fontSize: 13, height: 1.4)),
),
],
);
}
Widget _toolRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final p = m.content[part];
final key = 'tool/$id/$part';
final open = chat.expanded.contains(key);
final status = p.state?.status ?? '';
final icon = status == 'completed' ? '✓'
: status == 'error' ? '✕'
: status == 'running' || status == 'streaming' ? '◌' : '●';
final refs = toolImages(p, chat.dir);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () {
setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
});
if (!open) chat.ensureToolLoaded(id);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: Text('$icon ${p.name ?? ''} ${open ? '▾' : '▸'}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: Colors.grey, fontSize: 13)),
),
),
for (final ref in refs)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 1),
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.of(context).colorScheme.primary)),
),
],
),
),
),
if (open)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (p.state != null && (p.state!.input).isNotEmpty)
Text(const JsonEncoder.withIndent(' ').convert(p.state!.input),
style: const TextStyle(fontSize: 12, color: Colors.grey)),
if (toolOutput(p).isNotEmpty)
Text(toolOutput(p),
style: const TextStyle(fontSize: 12, color: Colors.grey, height: 1.4)),
],
),
),
),
],
);
}
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('从这里分叉')),
],
),
],
);
}
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
Widget _composer() {
final usage = chat.usageReading();
return SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 4),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_attachments.isNotEmpty)
SizedBox(
height: 34,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (var i = 0; i < _attachments.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: InputChip(
label: Text(_attachments[i].name,
maxLines: 1, overflow: TextOverflow.ellipsis),
onDeleted: () => setState(() => _attachments.removeAt(i)),
),
),
],
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attaching
? const Padding(
padding: EdgeInsets.all(12),
child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)))
: IconButton(
icon: const Icon(Icons.attach_file),
tooltip: '添加附件',
onPressed: _pickFiles,
),
Expanded(
child: TextField(
controller: _draftCtrl,
minLines: 1,
maxLines: 5,
onChanged: (v) => chat.draft = v,
decoration: const InputDecoration(
hintText: '发消息…',
border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
),
),
),
if (usage.$5)
InkWell(
onTap: () => _usageSheet(context),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
UsageRing(pct: usage.$4, accent: Theme.of(context).colorScheme.primary),
const SizedBox(width: 4),
Text('${usage.$4.round()}%',
style: const TextStyle(fontSize: 13, color: Colors.grey)),
],
),
),
),
if (chat.running)
IconButton(
icon: const Icon(Icons.stop),
tooltip: '停止',
onPressed: chat.stop,
)
else
IconButton.filled(
icon: const Icon(Icons.send),
tooltip: '发送',
onPressed: () => _send(),
),
],
),
],
),
),
);
}
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) {
2026-11-18 19:08:06 +08:00
chat.imagePaths[id] = images;
chat.touch();
}
}
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 {
final dir = await getApplicationSupportDirectory();
final d = Directory('${dir.path}/attachments');
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(
padding: const EdgeInsets.all(12),
child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
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();
final items = <(String, String, Object?)>[]; // (key, title, modelOrAgent)
if (_pickerKind == 'model') {
for (final m in widget.app.modelList) {
items.add(('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId)));
}
} else {
for (final a in widget.app.agentList) {
if (a.mode == 'primary') items.add(('agent/${a.id}', a.name, a.id));
}
}
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),
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 {
setState(() {
_previewTitle = ref.label;
_previewFile = null;
_previewLoading = true;
});
_previewDialog(context);
try {
final bytes = await _loadPreview(ref.source);
final dir = await getApplicationSupportDirectory();
final d = Directory('${dir.path}/previews');
await d.create(recursive: true);
final f = File(
'${d.path}/${DateTime.now().microsecondsSinceEpoch}-${ref.label.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}');
await f.writeAsBytes(bytes);
if (mounted) {
setState(() {
_previewFile = f;
_previewLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() => _previewLoading = false);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('无法预览:$e')));
}
}
}
void _previewDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => Dialog(
insetPadding: const EdgeInsets.all(12),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9),
child: ListenableBuilder(
listenable: chat,
builder: (context, _) => Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Text(_previewTitle, maxLines: 2, overflow: TextOverflow.ellipsis),
),
if (_previewLoading)
const Padding(
padding: EdgeInsets.all(40),
child: CircularProgressIndicator(),
)
else if (_previewFile != null)
Flexible(child: Image.file(_previewFile!, fit: BoxFit.contain)),
const SizedBox(height: 8),
],
),
),
),
),
);
}
Future<Uint8List> _loadPreview(String source) async {
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final bytes = await widget.app.client!.rawFile(source, directory: chat.dir);
return Uint8List.fromList(bytes);
}
// ------------------------------------------------------------ usage
void _usageSheet(BuildContext context) {
if (!_usageOpen) return;
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(_lastModel())),
_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)),
],
),
),
).then((_) => _usageOpen = false);
}
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);
}
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.isEmpty) return st.error ?? '';
return out;
}