diff --git a/PLAN.md b/PLAN.md index afb2b94..8cd10f9 100644 --- a/PLAN.md +++ b/PLAN.md @@ -27,6 +27,21 @@ --- +## 0.3.4 主题与工具细节(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 暗色主题代码块/行内代码 | `gpt_markdown` 用的是它自带的 `material_ui` 移植版 Material,`Theme.of` 找不到宿主主题时回落成**亮色**,于是代码块面板亮、正文黑。现在渲染前用同一套亮/暗 `mui.ThemeData` 包一层,面板、行内代码、表格、语法配色都跟随应用主题 | +| 折叠时视口跳动 | 折叠/展开会改变分组高度:现在记录表头在屏幕上的位置,重建后按差值补偿滚动;若因列表边界补不回来,就把表头停到列表顶部。展开时始终看到分组头部,不再落到分组末尾 | +| 工具详情 | 不再直接铺请求 JSON:`运行` 显示完整命令(可选中、换行)+ 输出,其它工具显示摘要之外的参数与结果;输出为空时显示「无输出」。`toolOutput` 在 `content` 为空时回退到 `metadata` 的 output/result/stdout | +| 图片读取 | `读取`/`写入`/`编辑` 指向图片时,该行不再展开,路径直接可点,打开大图预览 | +| 会话不自动刷新 | SSE 增加 30s 心跳超时(服务端每几秒发 `: heartbeat`),断流会被发现并重连;应用回到前台时重开事件流、刷新会话列表并 `reloadTail()`(合并而不是替换已加载的历史页) | +| 「载入更早」误显示 | 服务端对已经包含全部内容的页也会给 cursor,现在短于一页即视为没有更早内容 | +| openui-lang | 暂未渲染:pub 上的 `openui_lang` 0.18.2 组件签名与 OpenChamber 的 DSL 不一致(`Card` 首参是 children 而非标题,且没有 `Badge`/`KeyValue`/`Stat`/`Details`),接入需要一层组件映射;本轮先跳过 | +| 版本 | **0.3.4(code 304)** | + +--- + ## 0.3.3 工具调用展示(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index ad9e266..b8fe47e 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.3 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.4 — 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 6f6ead5..c045337 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -324,7 +324,14 @@ class Client { throw ApiError(res.statusCode, 'event stream failed'); } String data = ''; - await for (final line in utf8.decoder.bind(res).transform(const LineSplitter())) { + // The server sends a `: heartbeat` comment every few seconds; if nothing + // at all arrives for a while the connection is dead and the caller should + // reconnect rather than wait on a half-open socket. + final lines = utf8.decoder + .bind(res) + .transform(const LineSplitter()) + .timeout(const Duration(seconds: 30)); + await for (final line in lines) { if (line.isEmpty) { if (data.isNotEmpty) { final ev = jsonDecode(data) as Map; diff --git a/lib/main.dart b/lib/main.dart index 6d14de9..7720d61 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -14,15 +14,30 @@ class OpenChamberApp extends StatefulWidget { State createState() => _OpenChamberAppState(); } -class _OpenChamberAppState extends State { +class _OpenChamberAppState extends State + with WidgetsBindingObserver { final AppState app = AppState(); @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); app.init(); } + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // The socket often dies while the app sits in the background; nothing + // reports it, so reopen the stream and refresh the open chat on return. + if (state == AppLifecycleState.resumed) app.onResumed(); + } + @override Widget build(BuildContext context) { return ListenableBuilder( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 1d6d8e5..e690185 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -5,8 +5,12 @@ import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:gpt_markdown/gpt_markdown.dart'; +// gpt_markdown renders through its own Material port; its colours come from +// that port's theme, so the chat has to hand it ours. +import 'package:material_ui/material_ui.dart' as mui; import '../api/client.dart'; import '../api/models.dart'; @@ -38,6 +42,10 @@ class _ChatScreenState extends State { /// header of each run folds it away (key: message id and start part). final Set _collapsedSteps = {}; + /// Lets a fold keep its own header where it was on screen. + final Map _headerKeys = {}; + final GlobalKey _listKey = GlobalKey(); + @override void initState() { super.initState(); @@ -136,6 +144,7 @@ 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, @@ -397,17 +406,32 @@ class _ChatScreenState extends State { } } + /// gpt_markdown builds its widgets with `material_ui`, whose Theme.of has a + /// light fallback: without this the code panel and inline chips stayed light + /// (and their text dark) in the dark theme. + static mui.ThemeData _mdTheme(ThemeData theme) => mui.ThemeData( + useMaterial3: true, + brightness: theme.brightness, + colorScheme: mui.ColorScheme.fromSeed( + seedColor: theme.colorScheme.primary, + brightness: theme.brightness, + ), + ); + Widget _textRow(String id, int part) { final m = chat.byId[id]!; if (part < 0 || part >= m.content.length) return const SizedBox.shrink(); final text = m.content[part].text; return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2), - child: GptMarkdown( - text, - // The server already streams deltas; show them as they arrive. - isStreaming: false, - style: const TextStyle(fontSize: 15, height: 1.45), + child: mui.Theme( + data: _mdTheme(Theme.of(context)), + child: GptMarkdown( + text, + // The server already streams deltas; show them as they arrive. + isStreaming: false, + style: const TextStyle(fontSize: 15, height: 1.45), + ), ), ); } @@ -434,12 +458,12 @@ class _ChatScreenState extends State { : running ? '执行中 · $tools 次工具调用' : '已完成 · $tools 次工具调用'; + final headerKey = + _headerKeys.putIfAbsent('$id/$start', () => GlobalKey()); return GestureDetector( + key: headerKey, behavior: HitTestBehavior.opaque, - onTap: () => setState(() { - final key = '$id/$start'; - collapsed ? _collapsedSteps.remove(key) : _collapsedSteps.add(key); - }), + onTap: () => _toggleGroup(id, start, collapsed, headerKey), child: Padding( padding: const EdgeInsets.fromLTRB(14, 10, 12, 2), child: Row( @@ -468,6 +492,45 @@ class _ChatScreenState extends State { ); } + /// 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) { @@ -482,7 +545,11 @@ class _ChatScreenState extends State { final open = chat.expanded.contains(key); final label = _stepLabel(p); final summary = _stepSummary(p); - final refs = reasoning ? const <_ImageRef>[] : toolImages(p, chat.dir); + // 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( @@ -492,12 +559,14 @@ class _ChatScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ InkWell( - onTap: () { - setState(() { - open ? chat.expanded.remove(key) : chat.expanded.add(key); - }); - if (!open && !reasoning) chat.ensureToolLoaded(id); - }, + 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( @@ -536,11 +605,19 @@ class _ChatScreenState extends State { child: Text(summary, maxLines: 1, overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 13, color: theme.hintColor)), + style: TextStyle( + fontSize: 13, + color: image != null + ? theme.colorScheme.primary + : theme.hintColor)), ), ], - Icon(open ? Icons.expand_less : Icons.expand_more, - size: 16, color: 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), ], ), ), @@ -565,12 +642,62 @@ class _ChatScreenState extends State { ), ), ), - if (open) _stepDetails(p, reasoning), + if (open && image == null) _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; + final name = p.name ?? ''; + if (name != 'read' && name != 'write' && name != 'edit') return null; + final input = p.state?.input ?? const {}; + 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) { @@ -583,7 +710,16 @@ class _ChatScreenState extends State { ); } final input = p.state?.input ?? const {}; + final primary = _primaryInput(p); + final extras = >[ + 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); + const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace'); return Padding( padding: const EdgeInsets.fromLTRB(10, 2, 10, 8), child: Container( @@ -596,22 +732,26 @@ class _ChatScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (input.isNotEmpty) - SelectableText(const JsonEncoder.withIndent(' ').convert(input), - style: const TextStyle( - fontSize: 12, - fontFamily: 'monospace', - height: 1.4)), - if (input.isNotEmpty && output.isNotEmpty) - const SizedBox(height: 6), - if (output.isNotEmpty) - SelectableText(output, - style: TextStyle( - fontSize: 12, - height: 1.4, - color: p.state?.error != null - ? theme.colorScheme.error - : theme.colorScheme.onSurfaceVariant)), + 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.isEmpty ? (shell ? '无输出' : '无内容') : output, + style: mono.copyWith( + color: p.state?.error != null + ? theme.colorScheme.error + : theme.colorScheme.onSurfaceVariant, + ), + ), ], ), ), @@ -1431,8 +1571,12 @@ String toolOutput(ContentPart p) { final st = p.state; if (st == null) return ''; final out = st.content.where((c) => c.type == 'text').map((c) => c.text).join('\n'); - if (out.isEmpty) return st.error ?? ''; - return out; + 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 ?? ''; } diff --git a/lib/state.dart b/lib/state.dart index b1c97d4..5f452b4 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -272,20 +272,32 @@ class AppState extends ChangeNotifier { m.id; } + StreamSubscription>? _events; + int _streamGen = 0; + void _startStream() { final cl = client; if (cl == null) return; + final gen = ++_streamGen; + _events?.cancel().ignore(); Future loop() async { - while (client == cl) { - try { - await for (final ev in cl.streamEvents(types: _eventTypes)) { + while (client == cl && gen == _streamGen) { + final done = Completer(); + _events = cl.streamEvents(types: _eventTypes).listen( + (ev) { if (client != cl) return; _applyEvent(ev); - } - } catch (_) { - // Connection dropped; fall through to the retry below. - } - if (client != cl) return; + }, + onError: (Object _) { + if (!done.isCompleted) done.complete(); + }, + onDone: () { + if (!done.isCompleted) done.complete(); + }, + cancelOnError: true, + ); + await done.future; + if (client != cl || gen != _streamGen) return; error = '连接中断,正在重连…'; notifyListeners(); await Future.delayed(const Duration(seconds: 2)); @@ -294,6 +306,16 @@ class AppState extends ChangeNotifier { loop(); } + /// Reopens the event stream and refreshes what is on screen. Called when the + /// app comes back to the foreground: a socket that died while the process + /// was in the background never reports it. + Future onResumed() async { + if (client == null) return; + _startStream(); + await refreshSessions(); + if (chat != null) await chat!.reloadTail(); + } + void _applyEvent(Map ev) { final type = ev['type'] as String? ?? ''; final data = ev['data'] as Map? ?? {}; @@ -492,9 +514,11 @@ class ChatState extends ChangeNotifier { try { final page = await app.client!.listMessages(id, directory: dir); _setMessages(page.data); - // A desc page's `next` cursor points at the older side. + // A desc page's `next` cursor points at the older side. The server also + // hands out a cursor for a page that already holds everything, so a + // short page means there is nothing older. olderCursor = page.next; - hasMore = page.next != null; + hasMore = page.next != null && page.data.length >= _pageSize; loading = false; notifyListeners(); await reloadTail(); @@ -505,14 +529,29 @@ class ChatState extends ChangeNotifier { } } + /// Refreshes the newest page without dropping the older pages that were + /// already loaded; the server's copy wins for messages it returns. Future reloadTail() async { try { final page = await app.client!.listMessages(id, directory: dir); - _setMessages(page.data); + if (msgs.isEmpty) { + _setMessages(page.data); + } else { + final fresh = {for (final m in page.data) m.id: m}; + final merged = [ + for (final m in msgs) fresh.remove(m.id) ?? m, + for (final m in page.data) + if (fresh.containsKey(m.id)) m, + ]; + msgs = merged; + _sortMsgs(); + } notifyListeners(); } catch (_) {} } + static const _pageSize = 30; + Future loadOlder() async { if (!hasMore || loadingOlder) return; loadingOlder = true; @@ -525,7 +564,7 @@ class ChatState extends ChangeNotifier { msgs = [...older, ...msgs]; _sortMsgs(); olderCursor = page.next; - hasMore = page.next != null; + hasMore = page.next != null && page.data.length >= _pageSize; } catch (_) {} loadingOlder = false; notifyListeners(); diff --git a/pubspec.yaml b/pubspec.yaml index 7914a68..a14d9a7 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.3+303 +version: 0.3.4+304 environment: sdk: ^3.14.0 @@ -16,7 +16,6 @@ dependencies: file_picker: ^13.0.0 gpt_markdown: ^1.4.0 socks5_proxy: ^2.1.2 - dev_dependencies: flutter_test: sdk: flutter diff --git a/tool/event_probe.dart b/tool/event_probe.dart new file mode 100644 index 0000000..5c23325 --- /dev/null +++ b/tool/event_probe.dart @@ -0,0 +1,37 @@ +// Prints live SSE events for a few seconds: their type, session id and the +// keys of their payload. Run against a live server: +// dart run tool/event_probe.dart [seconds] +import 'dart:async'; +import 'dart:io'; + +import 'package:openchamber/api/client.dart'; + +Future main(List args) async { + final seconds = args.isEmpty ? 20 : int.tryParse(args[0]) ?? 20; + final client = Client(Uri.parse('http://127.0.0.1:3000')); + final seen = {}; + final sub = client.streamEvents(types: [ + 'session.created', 'session.renamed', 'session.execution.started', + 'session.execution.succeeded', 'session.execution.failed', + 'session.execution.interrupted', 'session.step.started', + 'session.step.ended', 'session.step.failed', 'session.text.started', + 'session.text.delta', 'session.text.ended', 'session.reasoning.started', + 'session.reasoning.delta', 'session.reasoning.ended', + 'session.tool.called', 'session.tool.success', 'session.tool.failed', + 'permission.asked', 'permission.replied', + ]).listen((ev) { + final type = ev['type'] as String? ?? ''; + final data = ev['data'] as Map? ?? {}; + seen[type] = (seen[type] ?? 0) + 1; + final sid = data['sessionID'] ?? data['sessionId']; + print('$type session=$sid message=${data['assistantMessageID'] ?? data['messageID']} ' + 'keys=${data.keys.take(6).join(',')}'); + }, onError: (Object e) => print('stream error: $e')); + + await Future.delayed(Duration(seconds: seconds)); + await sub.cancel(); + print('----'); + print(seen); + client.close(); + exit(0); +} diff --git a/tool/live_probe.dart b/tool/live_probe.dart new file mode 100644 index 0000000..71493a3 --- /dev/null +++ b/tool/live_probe.dart @@ -0,0 +1,58 @@ +// Creates a throwaway session, prompts it, and prints the live events for it: +// type, session id, assistant message id and payload keys. This is how the +// chat's streaming path is checked against a real server. +// dart run tool/live_probe.dart [seconds] +import 'dart:async'; +import 'dart:io'; + +import 'package:openchamber/api/client.dart'; + +const types = [ + 'session.created', 'session.renamed', 'session.execution.started', + 'session.execution.succeeded', 'session.execution.failed', + 'session.execution.interrupted', 'session.step.started', + 'session.step.ended', 'session.step.failed', 'session.text.started', + 'session.text.delta', 'session.text.ended', 'session.reasoning.started', + 'session.reasoning.delta', 'session.reasoning.ended', + 'session.tool.called', 'session.tool.success', 'session.tool.failed', + 'permission.asked', 'permission.replied', +]; + +Future main(List args) async { + final seconds = args.isEmpty ? 40 : int.tryParse(args[0]) ?? 40; + final dir = Directory.current.path; + final client = Client(Uri.parse('http://127.0.0.1:3000')); + + final session = await client.createSession(title: 'event probe', directory: dir); + print('session ${session.id}'); + + final counts = {}; + final sub = client.streamEvents(types: types).listen((ev) { + final type = ev['type'] as String? ?? ''; + final data = ev['data'] as Map? ?? {}; + final sid = data['sessionID']; + if (sid != session.id) return; + counts[type] = (counts[type] ?? 0) + 1; + print('$type msg=${data['assistantMessageID'] ?? data['messageID']} ' + 'part=${data['partID']} keys=${data.keys.join(',')}'); + }, onError: (Object e) => print('stream error: $e')); + + await Future.delayed(const Duration(milliseconds: 500)); + await client.prompt(session.id, + text: 'Reply with the single word: pong', directory: dir); + print('prompted'); + + await Future.delayed(Duration(seconds: seconds)); + await sub.cancel(); + + final page = await client.listMessages(session.id, limit: 50, directory: dir); + print('---- messages: ${page.data.length}'); + for (final m in page.data.reversed) { + final parts = m.content.map((p) => '${p.type}${p.name == null ? '' : '(${p.name})'}').join(','); + print('${m.id} ${m.type} parts=[$parts]'); + } + print('---- event counts: $counts'); + await client.deleteSession(session.id); + client.close(); + exit(0); +}