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

+14
View File
@@ -27,6 +27,20 @@
--- ---
## 0.3.5 折叠动画与流式修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 折叠定位 | 照 dsh-Go 的 `ExpandReveal`/`_holdHeader` 重做:内容用 `SizeTransition` 从顶部往下长、同时淡入,280ms `easeInOutCubic`;每一帧在**布局之前**把长出来的高度补进滚动位置,表头因此停在手指按下的位置。列表两端补不动时停在边界;看不见的折叠(历史里自动收起的一轮)直接换尺寸,不做动画、不拽视图 |
| 默认折叠 | 与 dsh-Go 一致:**已结束的一轮收成一行摘要**(`已完成 · N 次工具调用`),运行中的保持展开;点一下记住你的选择(手动展开的在结束后也不会自动收起) |
| 工具详情 | 不再铺请求 JSON:`运行` 是完整命令 + 其余参数 + 输出(空则「无输出」),其它工具是摘要之外的参数 + 结果;`toolOutput` 在 `content` 为空时回退 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时该行不可折叠,路径直接点开大图;读取失败的行仍是普通可折叠步骤 |
| 流式工具名 | 事件里只有工具 id 和 input,没有名字,直播中的步骤只能显示「工具」。现在每一步结束(`session.step.ended`)后用 `getMessage` 换回服务端那条消息:名字、完整输入、附件都齐了,标签立刻变成 `运行`/`读取` 等 |
| 会话自动刷新 | SSE 30s 无数据(服务端有 `: heartbeat`)即判定断线并重连;回到前台重开事件流、刷新会话列表并合并 `reloadTail()` |
| 版本 | **0.3.5(code 305)** |
---
## 0.3.4 主题与工具细节(分支 `flutter`) ## 0.3.4 主题与工具细节(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.3.4 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.3.5 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
+1 -1
View File
@@ -216,7 +216,7 @@ class Client {
final r = await _json('GET', final r = await _json('GET',
'/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}', '/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}',
directory: directory); directory: directory);
return Message.fromJson(r); return Message.fromJson(r['data'] as Map<String, dynamic>);
} }
Future<List<ModelInfo>> models(String directory) async { Future<List<ModelInfo>> models(String directory) async {
+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 /// 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). /// 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> _collapsedSteps = {};
final Set<String> _expandedSteps = {};
/// Lets a fold keep its own header where it was on screen.
final Map<String, GlobalKey> _headerKeys = {};
final GlobalKey _listKey = GlobalKey();
@override @override
void initState() { void initState() {
@@ -144,7 +143,6 @@ class _ChatScreenState extends State<ChatScreen> {
final rows = _rows(); final rows = _rows();
final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0; final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0;
return ListView.builder( return ListView.builder(
key: _listKey,
controller: _scroll, controller: _scroll,
reverse: true, reverse: true,
itemCount: rows.length + olderSlot, itemCount: rows.length + olderSlot,
@@ -219,11 +217,6 @@ class _ChatScreenState extends State<ChatScreen> {
return; return;
} }
out.add(_Row('steps', first.msgId, first.index)); 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(); pending.clear();
} }
@@ -250,8 +243,38 @@ class _ChatScreenState extends State<ChatScreen> {
} }
} }
bool _groupCollapsed(String id, int start) => /// A finished run is folded (as in dsh-Go), a running one is open so its
_collapsedSteps.contains('$id/$start'); /// 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 /// The steps of the run that begins at [msgId]/[index]: consecutive
/// reasoning/tool parts, continuing into the following assistant messages. /// reasoning/tool parts, continuing into the following assistant messages.
@@ -300,7 +323,7 @@ class _ChatScreenState extends State<ChatScreen> {
case 'text': case 'text':
return _textRow(r.msgId, r.part); return _textRow(r.msgId, r.part);
case 'steps': case 'steps':
return _stepsHeader(r.msgId, r.part); return _stepsBlock(r.msgId, r.part);
case 'step': case 'step':
return _stepRow(r.msgId, r.part); return _stepRow(r.msgId, r.part);
case 'footer': case 'footer':
@@ -436,21 +459,47 @@ class _ChatScreenState extends State<ChatScreen> {
); );
} }
/// "已完成 · 3 次工具调用", with a chevron that folds the whole run. /// A run of steps: the header, then its rows revealed with an animation.
Widget _stepsHeader(String id, int start) { /// Revealing grows the list below the header, so [_Reveal] reports the
final theme = Theme.of(context); /// 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 steps = _collectGroup(id, start);
final tools = steps.where((s) => s.part.type == 'tool').length; final running = _groupRunning(steps);
final collapsed = _groupCollapsed(id, start);
final failed = steps.any((s) => s.part.state?.status == 'error'); final failed = steps.any((s) => s.part.state?.status == 'error');
final running = steps.any((s) { final collapsed = _groupCollapsed(id, start, running);
final m = chat.byId[s.msgId]; return Column(
final st = s.part.state?.status ?? ''; crossAxisAlignment: CrossAxisAlignment.stretch,
return (m != null && m.completed == 0) || children: [
st == 'running' || _stepsHeader(id, start, steps, collapsed, running, failed),
st == 'streaming' || _Reveal(
st == 'pending'; 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 final label = tools == 0
? (running ? '思考中…' : '思考过程') ? (running ? '思考中…' : '思考过程')
: failed : failed
@@ -458,12 +507,9 @@ class _ChatScreenState extends State<ChatScreen> {
: running : running
? '执行中 · $tools 次工具调用' ? '执行中 · $tools 次工具调用'
: '已完成 · $tools 次工具调用'; : '已完成 · $tools 次工具调用';
final headerKey =
_headerKeys.putIfAbsent('$id/$start', () => GlobalKey());
return GestureDetector( return GestureDetector(
key: headerKey,
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () => _toggleGroup(id, start, collapsed, headerKey), onTap: () => _toggleGroup(id, start, collapsed),
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 12, 2), padding: const EdgeInsets.fromLTRB(14, 10, 12, 2),
child: Row( child: Row(
@@ -484,53 +530,17 @@ class _ChatScreenState extends State<ChatScreen> {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, color: theme.hintColor)), style: TextStyle(fontSize: 13, color: theme.hintColor)),
), ),
Icon(collapsed ? Icons.expand_more : Icons.expand_less, AnimatedRotation(
size: 18, color: theme.hintColor), 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 /// One step: a rounded icon, a label, the one-line summary, and details
/// when opened. /// when opened.
Widget _stepRow(String id, int part) { 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. /// The file a read/write/edit step points at, when it is an image.
String? _imageArg(ContentPart p) { String? _imageArg(ContentPart p) {
if (p.type != 'tool') return null; 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 ?? ''; final name = p.name ?? '';
if (name != 'read' && name != 'write' && name != 'edit') return null; if (name != 'read' && name != 'write' && name != 'edit') return null;
final input = p.state?.input ?? const <String, dynamic>{}; final input = p.state?.input ?? const <String, dynamic>{};
@@ -1489,6 +1506,106 @@ class _Row {
_Row(this.kind, this.msgId, this.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 /// One reasoning or tool part, addressed across the assistant messages of a
/// turn. /// turn.
class _Step { class _Step {
+18
View File
@@ -746,6 +746,10 @@ class ChatState extends ChangeNotifier {
tokens: data['tokens'] == null tokens: data['tokens'] == null
? m.tokens ? m.tokens
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>))); : TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>)));
// Live events name a tool only by id, so a streamed step would keep
// a generic label ("工具") until the session was reopened. The
// finished message has the names, inputs and attachments.
_refreshMessage(mid);
} }
break; break;
case 'session.text.started': case 'session.text.started':
@@ -784,6 +788,20 @@ class ChatState extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
/// Swaps a just-finished streamed message for the server's copy.
Future<void> _refreshMessage(String mid) async {
final cl = app.client;
if (cl == null) return;
try {
final m = await cl.getMessage(id, mid, directory: dir);
final i = msgs.indexWhere((x) => x.id == mid);
if (i < 0 || app.client != cl) return;
msgs[i] = m;
_sortMsgs();
notifyListeners();
} catch (_) {}
}
void _ensureAssistant(String id, int created) { void _ensureAssistant(String id, int created) {
if (byId.containsKey(id)) return; if (byId.containsKey(id)) return;
msgs.add(Message(id: id, type: 'assistant', created: created)); msgs.add(Message(id: id, type: 'assistant', created: created));
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.3.4+304 version: 0.3.5+305
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+4 -1
View File
@@ -39,7 +39,10 @@ Future<void> main(List<String> args) async {
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
await client.prompt(session.id, await client.prompt(session.id,
text: 'Reply with the single word: pong', directory: dir); text: args.length > 1
? args.sublist(1).join(' ')
: 'Reply with the single word: pong',
directory: dir);
print('prompted'); print('prompted');
await Future.delayed(Duration(seconds: seconds)); await Future.delayed(Duration(seconds: seconds));