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'; import '../api/client.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 createState() => _ChatScreenState(); } class _ChatScreenState extends State { 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 = ''; List<_Attach> _attachments = []; bool _attaching = false; /// 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). final Set _collapsedSteps = {}; @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. _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(); } }); WidgetsBinding.instance.addPostFrameCallback((_) { if (_scroll.hasClients) _scroll.jumpTo(0); }); } void _onChat() { if (mounted) setState(() {}); if (_stick) { WidgetsBinding.instance.addPostFrameCallback((_) { if (_scroll.hasClients) _scroll.jumpTo(0); }); } } @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: [ 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'), ), ), 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; return ListView.builder( controller: _scroll, reverse: true, itemCount: rows.length + olderSlot, 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('载入更早的消息'), ), ); }, ); } /// Loads an older page; the reversed list keeps the viewport in place. Future _loadOlder() async { if (!chat.hasMore || chat.loadingOlder) return; await chat.loadOlder(); } 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++; } _turnRows(out, mi, end); mi = end; break; 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)); if (!_groupCollapsed(first.msgId, first.index)) { for (final step in pending) { out.add(_Row('step', step.msgId, step.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(); if (chat.msgs[to].completed > 0 && _turnEndsAt(to)) { out.add(_Row('footer', chat.msgs[to].id, -1)); } } bool _groupCollapsed(String id, int start) => _collapsedSteps.contains('$id/$start'); /// 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; } 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 _stepsHeader(r.msgId, r.part); case 'step': return _stepRow(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( 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), ), ); } /// "已完成 · 3 次工具调用", with a chevron that folds the whole run. Widget _stepsHeader(String id, int start) { final theme = Theme.of(context); final steps = _collectGroup(id, start); final tools = steps.where((s) => s.part.type == 'tool').length; final collapsed = _groupCollapsed(id, start); final failed = steps.any((s) => s.part.state?.status == 'error'); final running = 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'; }); final label = tools == 0 ? (running ? '思考中…' : '思考过程') : failed ? '有步骤失败 · $tools 次工具调用' : running ? '执行中 · $tools 次工具调用' : '已完成 · $tools 次工具调用'; return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => setState(() { final key = '$id/$start'; collapsed ? _collapsedSteps.remove(key) : _collapsedSteps.add(key); }), 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)), ), Icon(collapsed ? Icons.expand_more : Icons.expand_less, size: 18, color: theme.hintColor), ], ), ), ); } /// One step: a rounded icon, a label, the one-line summary, and details /// when opened. Widget _stepRow(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 theme = Theme.of(context); final reasoning = p.type == 'reasoning'; 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); final refs = reasoning ? 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: () { 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), 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), ), 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: theme.hintColor)), ), ], Icon(open ? Icons.expand_less : Icons.expand_more, size: 16, color: theme.hintColor), ], ), ), ), 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)), ), ], ), ), ), if (open) _stepDetails(p, reasoning), ], ), ); } 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 {}; final output = toolOutput(p); 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 (input.isNotEmpty) SelectableText(const JsonEncoder.withIndent(' ').convert(input), style: const TextStyle( fontSize: 12, fontFamily: 'monospace', height: 1.4)), if (input.isNotEmpty && output.isNotEmpty) const SizedBox(height: 6), if (output.isNotEmpty) SelectableText(output, style: TextStyle( fontSize: 12, height: 1.4, 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 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 ''; } Widget _footerRow(String id) { final m = chat.byId[id]!; final parts = []; 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( 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 ''; 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 _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 // 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). Widget _composer() { final usage = chat.usageReading(); final scheme = Theme.of(context).colorScheme; final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty; return SafeArea( top: false, child: Padding( padding: const EdgeInsets.fromLTRB(8, 6, 8, 6), child: Column( mainAxisSize: MainAxisSize.min, children: [ if (_attachments.isNotEmpty) _attachmentTray(), Container( 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, minLines: 1, maxLines: 5, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, onChanged: (v) { chat.draft = v; setState(() {}); }, 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)), ], ), ), ), 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, ), ], ), ), ], ), ), ); } /// 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; final model = m == null ? '模型' : widget.app.modelName(m); final agent = chat.selectedAgent; return agent.isEmpty ? model : '$model · $agent'; } Future _send() async { final text = _draftCtrl.text.trim(); if (text.isEmpty && _attachments.isEmpty) return; // Files ride with the prompt as data URLs. final files = >[]; final images = []; 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; } _draftCtrl.clear(); setState(() => _attachments = []); if (images.isNotEmpty) { chat.imagePaths[id] = images; chat.touch(); } HapticFeedback.lightImpact(); } Future _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 _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'); 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.fromLTRB(12, 12, 12, 4), child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: SegmentedButton( 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), 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)>[]; if (_pickerKind == 'model') { final current = chat.selectedModel; 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)); } } 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)); } } 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, 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 _openPreview(_ImageRef ref) async { await showDialog( context: context, builder: (_) => _ImagePreviewDialog( title: ref.label, source: ref.source, directory: chat.dir, client: widget.app.client!, ), ); } // ------------------------------------------------------------ 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())), _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)), ], ), ), ); } 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); } /// 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); } 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 = {}; final labels = {}; 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; } /// 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 _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 _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), ], ), ), ); } }