diff --git a/PLAN.md b/PLAN.md index 8cd10f9..7f9f391 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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`) | 项 | 结果 | diff --git a/README.md b/README.md index b8fe47e..575ea80 100644 --- a/README.md +++ b/README.md @@ -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 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 events, chat with streaming Markdown and full history paging, tool steps grouped per turn (icon, one-line summary, foldable run) with image previews, a diff --git a/lib/api/client.dart b/lib/api/client.dart index c045337..3e60dd8 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -216,7 +216,7 @@ class Client { final r = await _json('GET', '/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}', directory: directory); - return Message.fromJson(r); + return Message.fromJson(r['data'] as Map); } Future> models(String directory) async { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e690185..e1f3ca3 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -40,11 +40,10 @@ class _ChatScreenState extends State { /// 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 _collapsedSteps = {}; - - /// Lets a fold keep its own header where it was on screen. - final Map _headerKeys = {}; - final GlobalKey _listKey = GlobalKey(); + final Set _expandedSteps = {}; @override void initState() { @@ -144,7 +143,6 @@ class _ChatScreenState extends State { 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 { 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 { } } - 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 { 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 { ); } - /// "已完成 · 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 { : 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 { 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 { ), ), ), - 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 { /// 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 {}; @@ -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? 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 _size = CurvedAnimation( + parent: _c, + curve: Curves.easeInOutCubic, + reverseCurve: Curves.easeInOutCubic.flipped); + late final Animation _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 { diff --git a/lib/state.dart b/lib/state.dart index 5f452b4..a0f7d92 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -746,6 +746,10 @@ class ChatState extends ChangeNotifier { tokens: data['tokens'] == null ? m.tokens : TokenUsage.fromJson(data['tokens'] as Map))); + // 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; case 'session.text.started': @@ -784,6 +788,20 @@ class ChatState extends ChangeNotifier { notifyListeners(); } + /// Swaps a just-finished streamed message for the server's copy. + Future _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) { if (byId.containsKey(id)) return; msgs.add(Message(id: id, type: 'assistant', created: created)); diff --git a/pubspec.yaml b/pubspec.yaml index a14d9a7..e4ef367 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.3.4+304 +version: 0.3.5+305 environment: sdk: ^3.14.0 diff --git a/tool/live_probe.dart b/tool/live_probe.dart index 71493a3..149f257 100644 --- a/tool/live_probe.dart +++ b/tool/live_probe.dart @@ -39,7 +39,10 @@ Future main(List args) async { await Future.delayed(const Duration(milliseconds: 500)); 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'); await Future.delayed(Duration(seconds: seconds));