feat: animated folds that hold their header, folded-by-default runs

- Rebuilt the fold after dsh-Go's ExpandReveal/_holdHeader: the body grows
  from its top edge and fades in over 280ms (easeInOutCubic), and every
  frame reports the height it adds or removes *before layout*, so the list
  can scroll by exactly that much and keep the header under the finger.
  Folds nobody can see take their new size without animating or dragging
  the view.
- Finished runs now fold to their summary line, as in dsh-Go; running ones
  stay open. A tap overrides either default and is remembered.
- Streamed tool parts only carry an id and input, never the tool name, so
  live steps showed a generic "工具" label. Each step now swaps in the
  server's copy of its message when it ends, which brings the name, the
  full input and the attachments (and with them the right icon, label and
  image handling).
- getMessage read the message from the response envelope directly and
  would have thrown; it now unpacks `data`.
Version 0.3.5 (code 305).
This commit is contained in:
blumia committed 2026-11-20 00:26:09 +08:00
1 parent 32277564f9
commit d7cec9d155
7 files changed
+228 -76

No files matched your search

+189 -72
View File
@@ -40,11 +40,10 @@ class _ChatScreenState extends State<ChatScreen> {
/// 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 = {};
/// Lets a fold keep its own header where it was on screen.
final Map<String, GlobalKey> _headerKeys = {};
final GlobalKey _listKey = GlobalKey();
final Set<String> _expandedSteps = {};
@override
void initState() {
@@ -144,7 +143,6 @@ class _ChatScreenState extends State<ChatScreen> {
final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
return ListView.builder(
key: _listKey,
controller: _scroll,
reverse: true,
itemCount: rows.length + olderSlot,
@@ -219,11 +217,6 @@ class _ChatScreenState extends State<ChatScreen> {
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();
}
@@ -250,8 +243,38 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
bool _groupCollapsed(String id, int start) =>
_collapsedSteps.contains('$id/$start');
/// 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.
@@ -300,7 +323,7 @@ class _ChatScreenState extends State<ChatScreen> {
case 'text':
return _textRow(r.msgId, r.part);
case 'steps':
return _stepsHeader(r.msgId, r.part);
return _stepsBlock(r.msgId, r.part);
case 'step':
return _stepRow(r.msgId, r.part);
case 'footer':
@@ -436,21 +459,47 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
/// "已完成 · 3 次工具调用", with a chevron that folds the whole run.
Widget _stepsHeader(String id, int start) {
final theme = Theme.of(context);
/// 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 tools = steps.where((s) => s.part.type == 'tool').length;
final collapsed = _groupCollapsed(id, start);
final running = _groupRunning(steps);
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 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
@@ -458,12 +507,9 @@ class _ChatScreenState extends State<ChatScreen> {
: running
? '执行中 · $tools 次工具调用'
: '已完成 · $tools 次工具调用';
final headerKey =
_headerKeys.putIfAbsent('$id/$start', () => GlobalKey());
return GestureDetector(
key: headerKey,
behavior: HitTestBehavior.opaque,
onTap: () => _toggleGroup(id, start, collapsed, headerKey),
onTap: () => _toggleGroup(id, start, collapsed),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row(
@@ -484,53 +530,17 @@ class _ChatScreenState extends State<ChatScreen> {
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
),
Icon(collapsed ? Icons.expand_more : Icons.expand_less,
size: 18, color: theme.hintColor),
AnimatedRotation(
turns: collapsed ? 0 : 0.5,
duration: const Duration(milliseconds: 180),
child: Icon(Icons.expand_more, size: 18, color: theme.hintColor),
),
],
),
),
);
}
/// Folds or unfolds a run, then puts its header back where it was: folding
/// changes the height below it, which would otherwise move the whole run
/// out of view under the finger.
void _toggleGroup(String id, int start, bool collapsed, GlobalKey key) {
final before = key.currentContext?.findRenderObject() as RenderBox?;
final target =
before != null && before.attached ? before.localToGlobal(Offset.zero).dy : null;
setState(() {
final k = '$id/$start';
collapsed ? _collapsedSteps.remove(k) : _collapsedSteps.add(k);
});
WidgetsBinding.instance.addPostFrameCallback((_) {
final box = key.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.attached || !_scroll.hasClients) return;
final pos = _scroll.position;
var top = box.localToGlobal(Offset.zero).dy;
if (target != null) {
// The run changed height below its header; pull the list back so the
// header sits exactly where it was clicked.
final want = (pos.pixels + (target - top))
.clamp(pos.minScrollExtent, pos.maxScrollExtent);
if ((want - pos.pixels).abs() > 0.5) {
_scroll.jumpTo(want);
top = box.localToGlobal(Offset.zero).dy;
}
}
final list = _listKey.currentContext?.findRenderObject() as RenderBox?;
if (list == null) return;
final listTop = list.localToGlobal(Offset.zero).dy;
final listBottom = listTop + list.size.height;
// A run that is longer than the viewport cannot keep its header at the
// click point; park it at the top instead so it stays on screen.
if (top >= listTop + 4 && top <= listBottom - 60) return;
final want = (_scroll.position.pixels - (top - listTop))
.clamp(pos.minScrollExtent, pos.maxScrollExtent);
_scroll.jumpTo(want);
});
}
/// One step: a rounded icon, a label, the one-line summary, and details
/// when opened.
Widget _stepRow(String id, int part) {
@@ -642,7 +652,12 @@ class _ChatScreenState extends State<ChatScreen> {
),
),
),
if (open && image == null) _stepDetails(p, reasoning),
if (image == null)
_Reveal(
open: open,
onGrow: _grow,
child: _stepDetails(p, reasoning),
),
],
),
);
@@ -655,6 +670,8 @@ class _ChatScreenState extends State<ChatScreen> {
/// 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>{};
@@ -1489,6 +1506,106 @@ class _Row {
_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 {