Files
openchamber-android-native/lib/screens/chat_screen.dart
T
blumia d25167de58 fix: float the pet over the messages and let it be dragged
The pet used to sit in the column above the composer, reserving a strip of
its own: the message list ended there, which read as an opaque band cutting
off the last row. It is now a layer over the message area, so the list keeps
its full height and shows through around the sprite. Only the body of the
sheet takes touches (contentBox, 4dp out); taps and drags on the transparent
canvas still reach the messages underneath.

Dragging the body moves the pet along the composer's top edge (or the
activity cap's) with a small lift while held and the pack's drag reaction.
The spot is stored as a fraction of the width in pet.x.v1, so a restart or a
change in width puts it back in the same place. Taps now react on tap-up so a
drag does not fire a left/right reaction.

0.4.1 (401).
2026-11-22 14:30:30 +08:00

2709 lines
91 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/composer_box.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart';
import '../widgets/slash_palette.dart';
import '../widgets/usage_ring.dart';
import 'files_panel.dart';
/// The chat: streaming Markdown, tool rows, composer and sheets.
class ChatScreen extends StatefulWidget {
final AppState app;
final Session session;
/// Opens the session drawer. Null where the list is always on screen (a
/// wide layout), so no menu button is shown there.
final VoidCallback? onOpenSessions;
/// The soft keyboard's height, from above the shell's Scaffold (which
/// removes the bottom inset from its body).
final double keyboardInset;
const ChatScreen({
super.key,
required this.app,
required this.session,
this.keyboardInset = 0,
this.onOpenSessions,
});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
ChatState get chat => widget.app.chat!;
final TextEditingController _draftCtrl = TextEditingController();
final FocusNode _inputFocus = FocusNode();
final ScrollController _scroll = ScrollController();
bool _stick = true;
List<ComposerAttachment> _attachments = [];
bool _attaching = false;
/// Decoded user attachments, so a rebuild does not base64-decode again.
final Map<String, Uint8List> _userImages = {};
/// `/` 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 = {};
/// Ticks the activity strip's clock while a turn runs.
Timer? _runClock;
@override
void initState() {
super.initState();
chat.addListener(_onChat);
_inputFocus.addListener(_onFocusChanged);
if (chat.running) _startClock();
// 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 (chat.running) {
_startClock();
} else {
_stopClock();
}
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) _scroll.jumpTo(0);
});
}
}
void _startClock() {
_runClock ??= Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted && chat.running) setState(() {});
});
}
void _stopClock() {
_runClock?.cancel();
_runClock = null;
}
void _onFocusChanged() {
if (mounted) setState(() {});
}
@override
void dispose() {
chat.removeListener(_onChat);
_inputFocus.removeListener(_onFocusChanged);
_stopClock();
_draftCtrl.dispose();
_inputFocus.dispose();
_scroll.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
leading: widget.onOpenSessions == null
? null
: IconButton(
icon: const Icon(Icons.menu),
tooltip: '会话',
onPressed: widget.onOpenSessions,
),
title: Text(_title(), maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
IconButton(
icon: const Icon(Icons.view_sidebar_outlined),
tooltip: '文件',
onPressed: () => showFilesPanel(context, widget.app, chat.dir),
),
],
),
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: Stack(
children: [
Positioned.fill(child: _messageList()),
// Over the messages, not in the column: the list keeps its
// full height and shows through around the pet.
Positioned.fill(child: PetLayer(state: _petState())),
],
),
),
_permissions(),
_forms(),
if (chat.running) _activityStrip(),
_composer(widget.keyboardInset),
],
),
);
}
// --------------------------------------------------------------- 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<void> _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 '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;
case 'shell':
out.add(_Row('shell', m.id, -1));
break;
case 'synthetic':
out.add(_Row('note', m.id, -1));
break;
}
}
// Prompts waiting in the inbox stand after the transcript, as dsh-Go's
// pending bubbles do.
for (final item in chat.inbox) {
out.add(_Row('pending', item.id, -1));
}
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));
}
// A running turn has no "done" strip (nor its copy/fork menu): the
// activity strip above the composer speaks for it instead.
if (last.completed > 0 && _turnEndsAt(to) && !chat.running) {
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;
}
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 'pending':
return _pendingBubble(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);
case 'footer':
return _footerRow(r.msgId);
case 'error':
return _errorRow(r.msgId);
case 'compaction':
return _compactionRow(r.msgId);
case 'shell':
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(chat.byId[r.msgId]?.text ?? '',
style: const TextStyle(color: Colors.grey, fontSize: 13)),
);
default:
return const SizedBox.shrink();
}
}
/// The session's title as the list has it: the server names a session from
/// its first message, which arrives after this screen was built.
String _title() {
for (final session in widget.app.sessions) {
if (session.id == widget.session.id && session.title.isNotEmpty) {
return session.title;
}
}
return widget.session.title.isEmpty ? '会话' : widget.session.title;
}
/// A prompt in the server's inbox: dimmer than a sent message, with the
/// label dsh-Go uses and its actions (switch between steering and queueing,
/// or take it back into the composer).
Widget _pendingBubble(String id) {
final item = chat.inbox.where((i) => i.id == id).firstOrNull;
if (item == null) return const SizedBox.shrink();
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final steering = item.delivery == 'steer';
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
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: scheme.primary.withValues(alpha: 0.55),
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (item.text.isNotEmpty)
Text(item.text,
style: TextStyle(color: scheme.onPrimary)),
if (item.files.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text('📎 ${item.files.length} 个附件',
style: TextStyle(
color: scheme.onPrimary, fontSize: 12.5)),
),
],
),
),
),
Padding(
padding: const EdgeInsets.only(right: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(steering ? Icons.alt_route : Icons.schedule,
size: 13, color: theme.hintColor),
const SizedBox(width: 3),
Text(
!chat.running
? '未发送'
: steering
? '正在转入当前回合…'
: '已排队,本轮结束后发送',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
const SizedBox(width: 4),
TextButton(
onPressed: () => chat.changeInboxDelivery(
item.id, steering ? 'queue' : 'steer'),
child: Text(steering ? '改为排队' : '转为转向',
style: const TextStyle(fontSize: 12.5)),
),
TextButton(
onPressed: () async {
final ok = await chat.withdrawInbox(item.id);
if (!ok || !mounted) return;
_draftCtrl.text = chat.draft;
_draftCtrl.selection = TextSelection.collapsed(
offset: _draftCtrl.text.length);
_inputFocus.requestFocus();
},
child: const Text('撤回',
style: TextStyle(fontSize: 12.5)),
),
],
),
),
],
);
}
Widget _userRow(String id) {
final m = chat.byId[id]!;
final theme = Theme.of(context);
// The server keeps attached images in the message; the paths only cover
// the moment between sending and the next refresh.
final attachedImages = [
for (var i = 0; i < m.files.length; i++)
if (m.files[i].isImage) i,
];
final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const <String>[];
final otherFiles = m.files.where((f) => !f.isImage).toList();
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 i in attachedImages)
Padding(
padding: const EdgeInsets.only(top: 6),
child: GestureDetector(
onTap: () => _previewAttachment(m.files[i]),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: _attachmentImage(id, i, m.files[i]),
),
),
),
for (final p in localImages)
Padding(
padding: const EdgeInsets.only(top: 4),
child: GestureDetector(
onTap: () => _openPreview(_ImageRef(p, p.split('/').last)),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(File(p),
width: 200, height: 150, fit: BoxFit.cover),
),
),
),
for (final f in otherFiles)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: theme.colorScheme.onPrimary.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
),
child: Text('📎 ${f.name.isEmpty ? '附件' : f.name}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: theme.colorScheme.onPrimary, fontSize: 12.5)),
),
),
],
),
),
);
}
Widget _attachmentImage(String messageId, int index, FileAttachment f) {
final key = '$messageId/$index';
Uint8List? bytes = _userImages[key];
if (bytes == null) {
try {
bytes = base64Decode(f.data);
_userImages[key] = bytes;
} catch (_) {
return const SizedBox(
width: 200, height: 60, child: Center(child: Text('图片无法显示')));
}
}
return Image.memory(bytes, width: 200, height: 150, fit: BoxFit.cover);
}
void _previewAttachment(FileAttachment f) {
_showImageDialog(
f.name.isEmpty ? '图片' : f.name,
source: 'data:${f.mime};base64,${f.data}',
);
}
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();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
child: MarkdownView(m.content[part].text),
);
}
/// 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),
),
],
),
),
);
}
/// 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);
// 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),
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: 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),
],
),
),
),
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 (image == null)
_Reveal(
open: open,
onGrow: _grow,
child: _stepDetails(p, reasoning),
),
],
),
);
}
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();
// The model writes Markdown here too; render it as such, a touch
// smaller and quieter than the answer.
return Padding(
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
child: MarkdownView(p.text, fontSize: 12.5, 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 '';
}
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))
: MarkdownView(summary, fontSize: 14),
),
),
],
);
}
/// 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')),
),
],
],
),
),
);
}
/// The mood the pet draws: the same activity the strip shows, then a failed
/// last turn, then idle.
String _petState() {
if (chat.running) {
return _activity().title == '思考中' ? 'thinking' : 'working';
}
for (var i = chat.msgs.length - 1; i >= 0; i--) {
final m = chat.msgs[i];
if (m.type == 'assistant' || m.type == 'idle') {
return m.error != null && !m.error!.isEmpty ? 'error' : 'idle';
}
}
return 'idle';
}
/// What the agent is doing right now, for the strip above the composer.
({String title, String detail}) _activity() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
final m = chat.msgs[i];
if (m.type != 'assistant') continue;
for (var p = m.content.length - 1; p >= 0; p--) {
final part = m.content[p];
final st = part.state?.status ?? '';
if (part.type == 'tool' &&
(st == 'running' || st == 'streaming' || st == 'pending')) {
return (title: '正在${_stepLabel(part)}', detail: _stepSummary(part));
}
}
if (m.completed == 0) {
// No tool running yet: say which part of the reply is being written.
final text =
m.content.any((p) => p.type == 'text' && p.text.trim().isNotEmpty);
final reasoning = m.content
.any((p) => p.type == 'reasoning' && p.text.trim().isNotEmpty);
if (text) return (title: '正在回复', detail: '');
if (reasoning) return (title: '思考中', detail: '');
}
break;
}
return (title: '思考中', detail: '');
}
/// The running turn started with the newest user message.
int _runningStart() {
for (var i = chat.msgs.length - 1; i >= 0; i--) {
if (chat.msgs[i].type == 'user') return chat.msgs[i].created;
}
return 0;
}
String _elapsedSince(int start) {
if (start <= 0) return '';
final secs =
((DateTime.now().millisecondsSinceEpoch - start) / 1000).round();
if (secs <= 0) return '0:00';
return '${secs ~/ 60}:${(secs % 60).toString().padLeft(2, '0')}';
}
/// dsh-Go's activity cap: a stadium above the input with the current step
/// on the left and its clock on the right. Its top edge is where the
/// input-box pet will later perch.
Widget _activityStrip() {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final act = _activity();
final elapsed = _elapsedSince(_runningStart());
return Padding(
// The same 8px side margin as the composer, so the two capsules agree.
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Container(
constraints: const BoxConstraints(minHeight: 36),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
decoration: ShapeDecoration(
color: scheme.surfaceContainerHighest.withValues(alpha: 0.7),
shape: const StadiumBorder(),
),
child: Row(
children: [
Expanded(
child: Row(
children: [
Text(
act.title,
style: theme.textTheme.labelMedium?.copyWith(
fontSize: 13,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
if (act.detail.isNotEmpty) ...[
const SizedBox(width: 6),
Flexible(
child: Text(
act.detail,
maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall?.copyWith(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
),
],
],
),
),
if (elapsed.isNotEmpty) ...[
const SizedBox(width: 8),
Text(
elapsed,
style: TextStyle(
fontSize: 12,
color: theme.hintColor,
fontFeatures: const [FontFeature.tabularFigures()],
),
),
],
],
),
),
);
}
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;
}
}
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
// 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.
/// 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() => matchSlashItems(
items: chat.slashItems,
text: _draftCtrl.text,
dismissed: _slashDismissed,
);
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) => SlashPalette(
items: items,
index: _slashIndex,
loading: chat.slashLoading,
onPick: _pickSlash,
);
Widget _composer(double keyboardInset) {
final usage = chat.usageReading();
final scheme = Theme.of(context).colorScheme;
final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty;
// The key is stop only while running with nothing to send.
final showStop = chat.running && !canSend;
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = Padding(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('slash-palette'),
child: _slashPalette(slashRows),
),
const SizedBox(height: 6),
],
ComposerBox(
controller: _draftCtrl,
focusNode: _inputFocus,
hint: chat.running ? '生成中,仍可输入…' : '发消息…',
maxLines: 5,
keyboardInset: keyboardInset,
// 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)]),
onChanged: (v) {
chat.draft = v;
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) chat.ensureSlash();
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)]);
}
}
},
leading: _roundKey(
icon: Icons.attach_file,
label: '添加附件',
onTap: _pickFiles,
busy: _attaching,
),
model: ModelPill(
app: widget.app,
model: chat.selectedModel ?? widget.session.model,
onModel: (m) => chat.switchModel(m),
),
mode: ModeChip(
app: widget.app,
agent: chat.selectedAgent,
onAgent: (a) => chat.switchAgent(a),
),
accessory: usage.$5
? InkWell(
onTap: () => _usageSheet(context),
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
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)),
],
),
),
)
: null,
// Stop only while the turn runs with an empty draft; once there is
// something to send the key sends again, as dsh-Go's does.
trailing: _roundKey(
icon: showStop ? Icons.stop_rounded : Icons.arrow_upward_rounded,
label: showStop ? '停止' : '发送',
filled: true,
enabled: showStop || canSend,
onTap: showStop ? chat.stop : _send,
onLongPress: showStop ? null : _sendOptions,
),
),
],
),
);
// 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,
),
);
}
/// One 36px round key of the input bar.
Widget _roundKey({
required IconData icon,
required String label,
required VoidCallback onTap,
VoidCallback? onLongPress,
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,
onLongPress: on ? onLongPress : 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() => AttachmentTray(
items: _attachments,
onRemove: (i) => setState(() => _attachments.removeAt(i)),
);
/// Long-press on send while a turn runs: join it (steer) or wait for it to
/// end (queue). Only the deliveries the server offers are listed.
Future<void> _sendOptions() async {
if (!chat.running) return _send();
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// The configured behavior is what a short press does; mark it here too.
final fallback = widget.app.followUpBehavior;
final scheme = Theme.of(context).colorScheme;
final picked = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('发送方式',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
ListTile(
leading: const Icon(Icons.alt_route),
title: const Text('转向当前回合'),
subtitle: const Text('在下一步加入,工作继续'),
trailing: fallback == 'steer'
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, 'steer'),
),
ListTile(
leading: const Icon(Icons.schedule),
title: const Text('排队'),
subtitle: const Text('等本轮结束后发送'),
trailing: fallback == 'queue'
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, 'queue'),
),
const SizedBox(height: 8),
],
),
),
);
if (picked == null || !mounted) return;
await _send(delivery: picked);
}
Future<void> _send({String? delivery}) async {
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// A short send while a turn runs uses the configured follow-up behavior;
// the long-press sheet can choose the other one for this message.
final effective =
chat.running ? (delivery ?? widget.app.followUpBehavior) : null;
// 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, delivery: effective);
if (id == null) {
// The prompt failed: keep the text for a retry.
_draftCtrl.text = chat.draft;
return;
}
_draftCtrl.clear();
setState(() => _attachments = []);
if (images.isNotEmpty && id.isNotEmpty) {
chat.imagePaths[id] = images;
chat.touch();
}
HapticFeedback.lightImpact();
}
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final picked = await pickComposerAttachments(context);
if (picked.isEmpty) return;
setState(() {
for (final file in picked) {
if (_attachments.length >= 5) break;
_attachments.add(file);
}
});
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('选择失败:$e')));
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
// ---------------------------------------------------------- permissions
/// The agent's blocking questions sit just above the composer, like the
/// permissions dock: answering one lets the turn continue.
Widget _forms() {
if (chat.forms.isEmpty) return const SizedBox.shrink();
final form = chat.forms.first;
return _FormDock(key: ValueKey(form.id), chat: chat, form: form);
}
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 _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) =>
_showImageDialog(ref.label, source: ref.source);
Future<void> _showImageDialog(String title, {required String source}) async {
await showDialog(
context: context,
builder: (_) => _ImagePreviewDialog(
title: title,
source: 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);
}
/// 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);
}
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 ?? '';
}
/// 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),
],
),
),
);
}
}
/// The native form/question card: every visible field at once, one answer.
/// Field visibility follows the form's `when` clauses, and required fields
/// must be filled before it can be sent.
class _FormDock extends StatefulWidget {
final ChatState chat;
final FormInfo form;
const _FormDock({super.key, required this.chat, required this.form});
@override
State<_FormDock> createState() => _FormDockState();
}
class _FormDockState extends State<_FormDock> {
final Map<String, Object?> _values = {};
final Map<String, TextEditingController> _controllers = {};
String? _error;
bool _sending = false;
@override
void initState() {
super.initState();
for (final f in widget.form.fields) {
switch (f.type) {
case 'boolean':
_values[f.key] = f.defaultValue is bool ? f.defaultValue : false;
break;
case 'multiselect':
_values[f.key] = f.defaultValue is List
? List<String>.from((f.defaultValue as List).whereType<String>())
: <String>[];
break;
case 'external':
_values[f.key] = true;
break;
default:
if (f.defaultValue != null) {
_values[f.key] = f.defaultValue;
_controllers[f.key] =
TextEditingController(text: '${f.defaultValue}');
}
}
}
}
@override
void dispose() {
for (final c in _controllers.values) {
c.dispose();
}
super.dispose();
}
bool _visible(AgentFormField f) {
if (f.hidden) return false;
for (final w in f.when) {
final v = _values[w.key];
final eq = v == w.value ||
(v is num && w.value is num && v == w.value) ||
(v is bool && w.value is bool && v == w.value);
if (w.op == 'neq' ? eq : !eq) return false;
}
return true;
}
TextEditingController _controller(AgentFormField f) =>
_controllers.putIfAbsent(f.key, () => TextEditingController());
void _set(AgentFormField f, Object? value) {
setState(() {
_values[f.key] = value;
_error = null;
});
}
Future<void> _submit() async {
final visible = widget.form.fields.where(_visible).toList();
final missing = <String>[];
for (final f in visible) {
if (!f.required || f.type == 'external') continue;
final v = _values[f.key];
// A required switch or acknowledgement has to be on, not merely set.
final empty = v == null ||
v == false ||
(v is String && v.trim().isEmpty) ||
(v is List && v.isEmpty);
if (empty) missing.add(f.label);
}
if (missing.isNotEmpty) {
setState(() => _error = '请填写:${missing.join('、')}');
return;
}
final answer = <String, Object?>{};
for (final f in visible) {
if (f.type == 'external') {
answer[f.key] = true;
continue;
}
final v = _values[f.key];
if (v == null) continue;
if (v is String && v.trim().isEmpty) continue;
if (v is List && v.isEmpty) continue;
answer[f.key] = v;
}
setState(() {
_sending = true;
_error = null;
});
await widget.chat.replyForm(widget.form, answer);
if (mounted) setState(() => _sending = false);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final fields = widget.form.fields.where(_visible).toList();
return Card(
margin: const EdgeInsets.fromLTRB(12, 4, 12, 4),
color: scheme.surfaceContainerHigh,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Icon(Icons.help_outline, size: 18, color: scheme.primary),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.form.title.isEmpty ? '请选择' : widget.form.title,
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600),
),
),
TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 32),
),
onPressed: _sending
? null
: () => widget.chat.cancelForm(widget.form),
child: const Text('取消', style: TextStyle(fontSize: 12.5)),
),
],
),
if (fields.isNotEmpty)
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 360),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final f in fields) _field(f, theme),
],
),
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(_error!,
style: TextStyle(fontSize: 12, color: scheme.error)),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FilledButton(
onPressed: _sending ? null : _submit,
child: _sending
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const Text('发送'),
),
],
),
],
),
),
);
}
Widget _field(AgentFormField f, ThemeData theme) {
final scheme = theme.colorScheme;
final title = Row(
children: [
Flexible(
child: Text(f.label,
style:
const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
),
if (f.required)
Text(' *', style: TextStyle(color: scheme.error, fontSize: 13)),
],
);
Widget hint() => f.description == null || f.description!.isEmpty
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.only(top: 2, bottom: 2),
child: Text(f.description!,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
);
switch (f.type) {
case 'external':
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
if (f.url != null && f.url!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(f.url!,
style: TextStyle(
fontSize: 12, color: scheme.primary),
maxLines: 2,
overflow: TextOverflow.ellipsis),
),
],
),
);
case 'boolean':
return SwitchListTile(
contentPadding: EdgeInsets.zero,
dense: true,
title: title,
subtitle: hint(),
value: _values[f.key] == true,
onChanged: (v) => _set(f, v),
);
case 'multiselect':
final selected = List<String>.from(
(_values[f.key] as List?)?.whereType<String>() ?? const []);
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
Wrap(
spacing: 6,
runSpacing: -6,
children: [
for (final o in f.options)
FilterChip(
label: Text(o.label, style: const TextStyle(fontSize: 12.5)),
selected: selected.contains(o.value),
onSelected: (on) {
final next = [...selected];
if (on) {
next.add(o.value);
} else {
next.remove(o.value);
}
_set(f, next);
},
),
],
),
],
),
);
case 'string':
if (f.options.isNotEmpty) {
final current = _values[f.key]?.toString();
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
Wrap(
spacing: 6,
runSpacing: -6,
children: [
for (final o in f.options)
ChoiceChip(
label: Text(o.label,
style: const TextStyle(fontSize: 12.5)),
selected: current == o.value,
onSelected: (_) => _set(f, o.value),
),
],
),
if (f.custom)
Padding(
padding: const EdgeInsets.only(top: 6),
child: TextField(
controller: _controller(f),
onChanged: (v) => _set(f, v),
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: '其他…',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
),
],
),
);
}
final numeric = f.format == 'number';
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
const SizedBox(height: 4),
TextField(
controller: _controller(f),
onChanged: (v) => _set(f, v),
keyboardType: f.format == 'email'
? TextInputType.emailAddress
: f.format == 'uri'
? TextInputType.url
: numeric
? TextInputType.number
: TextInputType.text,
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: f.placeholder ??
(f.format == 'date' ? 'YYYY-MM-DD' : null),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
],
),
);
case 'number':
case 'integer':
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
title,
hint(),
const SizedBox(height: 4),
TextField(
controller: _controller(f),
keyboardType:
TextInputType.numberWithOptions(decimal: f.type == 'number'),
onChanged: (v) {
final n = f.type == 'integer'
? int.tryParse(v)
: num.tryParse(v);
_set(f, n ?? (v.isEmpty ? null : v));
},
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8)),
),
),
],
),
);
default:
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Text('${f.label}(${f.type})',
style: const TextStyle(fontSize: 13)),
);
}
}
}