From 61977d2b143e1c6c9c1ac7ad1a24aa8ffcd666d7 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Thu, 19 Nov 2026 12:34:25 +0800 Subject: [PATCH] fix: full chat history, picked model/agent, usage sheet, image previews - The chat loaded only one page of history: a desc page's older side is cursor.next, not previous, and the server rejects a cursor combined with order (InvalidCursorError). The first page stores `next`, later pages pass only `cursor`. tool/history_probe.dart walks a 1698-message session down to the oldest message with no gaps. - The message list is now reversed (newest at offset 0), so older pages grow above and the viewport stays put; near the top it loads by itself and a "load earlier" row remains as a fallback. - The agent picker filtered only on mode, so Compaction/Title/Summary (primary but hidden) showed up. Filter `hidden` too, and mark the current model or agent with a check. - The usage ring's sheet was guarded by a flag nothing ever set; the ring now opens the context detail sheet. - Tool image previews use a self-loading dialog and Image.memory: no temp file and no path_provider, whose Android implementation throws ClassNotFoundException: Landroid/content/Context; on the emulator. - "Add server" in the connected server sheet now opens the form and returns to the session list once connected. - Add a Linux desktop target for fast local UI checks, plus the probe that pages history. - Version 0.3.2 (code 302). --- .metadata | 3 + PLAN.md | 15 + README.md | 29 +- analysis_options.yaml | 1 + lib/api/client.dart | 4 +- lib/api/models.dart | 11 +- lib/screens/chat_screen.dart | 275 ++++++++++++------- lib/screens/servers_screen.dart | 14 +- lib/screens/sessions_screen.dart | 9 +- lib/state.dart | 50 +++- linux/.gitignore | 1 + linux/CMakeLists.txt | 128 +++++++++ linux/flutter/CMakeLists.txt | 88 ++++++ linux/flutter/generated_plugin_registrant.cc | 15 + linux/flutter/generated_plugin_registrant.h | 15 + linux/flutter/generated_plugins.cmake | 25 ++ linux/runner/CMakeLists.txt | 26 ++ linux/runner/main.cc | 6 + linux/runner/my_application.cc | 129 +++++++++ linux/runner/my_application.h | 21 ++ pubspec.lock | 10 +- pubspec.yaml | 3 +- tool/history_probe.dart | 65 +++++ tool/proxy_probe.dart | 21 ++ 24 files changed, 834 insertions(+), 130 deletions(-) create mode 100644 linux/.gitignore create mode 100644 linux/CMakeLists.txt create mode 100644 linux/flutter/CMakeLists.txt create mode 100644 linux/flutter/generated_plugin_registrant.cc create mode 100644 linux/flutter/generated_plugin_registrant.h create mode 100644 linux/flutter/generated_plugins.cmake create mode 100644 linux/runner/CMakeLists.txt create mode 100644 linux/runner/main.cc create mode 100644 linux/runner/my_application.cc create mode 100644 linux/runner/my_application.h create mode 100644 tool/history_probe.dart diff --git a/.metadata b/.metadata index 36b2722..1da03d4 100644 --- a/.metadata +++ b/.metadata @@ -21,6 +21,9 @@ migration: - platform: ios create_revision: ab2912035e160d9cad6306df307576da6128ebdb base_revision: ab2912035e160d9cad6306df307576da6128ebdb + - platform: linux + create_revision: ab2912035e160d9cad6306df307576da6128ebdb + base_revision: ab2912035e160d9cad6306df307576da6128ebdb # User provided section diff --git a/PLAN.md b/PLAN.md index 76d7ce3..c3ff3ed 100644 --- a/PLAN.md +++ b/PLAN.md @@ -27,6 +27,21 @@ --- +## 0.3.2 修复(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 会话历史只加载一段 | 两个原因:`order=desc` 的“更早”方向是 `cursor.next`(此前用了 `previous`,取到 0 条),以及服务端拒绝 `cursor` 与 `order` 同时出现(`InvalidCursorError`)。现在首次加载记下 `next`,后续只带 `cursor`。`tool/history_probe.dart` 对 1698 条的会话验证 30 条/页翻到最早一条,无缺口 | +| 加载时视图跳动 | 消息列表改为 `reverse: true`(最新在底部,偏移 0),更早的页追加在上方,视口自然保持不动;接近顶部自动加载,并提供「载入更早的消息」按钮 | +| 智能体列表 | 过滤 `hidden`(Compaction/Title/Summary 是 `mode=primary` 但 `hidden=true`),只留 Build/Plan;模型与智能体列表用对勾标出当前选中项,切换后由 SSE 事件与本状态同步 | +| 用量环 | 点击打开「上下文占用」详情(模型、已用 tokens、上限、输出预留、百分比);此前被 `_usageOpen` 守卫拦掉 | +| 图片预览 | 对话框改为自加载的 StatefulWidget(此前预览流程在 widget 重建后失去状态);图片直接 `Image.memory(bytes)`,不再落盘。`path_provider_android 2.3.1` 在本机模拟器上抛 `ClassNotFoundException: Landroid/content/Context;`,因此移除 path_provider(附件缓存改用 `Directory.systemTemp`)。经 SOCKS5/HTTP 代理取 `/api/fs/raw` 均可预览 | +| 已连接时添加服务器 | 服务器面板的「添加服务器」此前只关闭面板;现在打开表单,连接成功后回到会话列表 | +| 版本 | **0.3.2(code 302)** | +| 测试环境 | 新增 Linux 桌面目标(`flutter create --platforms=linux`),本机 clang 从 `clang-17` 包解出、libsecret/jsoncpp 头文件解出,配合 Xvfb + xdotool/ffmpeg 截图自测,比模拟器快很多 | + +--- + ## 0.3.1 修复(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index d399200..ff687b3 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,13 @@ 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.1 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.2 — 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, tool rows with image previews, a -context usage ring with a detail sheet, model/agent switching, copy / fork / -revert, attachments (photos/files), permissions. Android 7.0 (API 24)+. +events, chat with streaming Markdown and full history paging, tool rows with +image previews, a context usage ring with a detail sheet, model/agent +switching (Build/Plan only, current one checked), copy / fork / revert, +attachments (photos/files), permissions. Android 7.0 (API 24)+, plus a Linux +desktop target used for local testing. ## What is here @@ -18,7 +20,7 @@ revert, attachments (photos/files), permissions. Android 7.0 (API 24)+. | `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` | | `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) | | `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding | -| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets) | +| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets); the message list is reversed so older pages grow above without moving the viewport | | `lib/widgets/` | The context usage ring | Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer @@ -44,8 +46,25 @@ export JAVA_HOME=$HOME/SDK/jdk-21 flutter pub get flutter test flutter build apk --release # dist artifacts in build/app/outputs/flutter-apk +flutter build linux --debug # faster UI checks on the desktop ``` +The Linux build only needs a C toolchain and GTK 3 development headers; on +this machine `clang` was extracted into `~/SDK/localbin` (from the +`clang-17` package) and the two missing `-dev` files (`libsecret-1-dev`, +`libjsoncpp-dev`) into `~/SDK/linuxdev`, so: + +```bash +export PATH=$HOME/SDK/localbin:$HOME/SDK/flutter/bin:$PATH +export PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig +export LIBRARY_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu +flutter build linux --debug +DISPLAY=:99 GDK_BACKEND=x11 ./build/linux/x64/debug/bundle/openchamber +``` + +`tool/history_probe.dart` pages a session exactly as the chat does and reports +whether every message is reached. + `android/app/build.gradle.kts` sets the application id `net.blumia.openchamber.flutter`, `minSdk 24`, and signs releases with `~/SDK/test-upload.jks` (override via `OPENCHAMBER_KEYSTORE*` env). Dart's diff --git a/analysis_options.yaml b/analysis_options.yaml index 0da40e9..ab46d80 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -14,6 +14,7 @@ analyzer: - build/** - android/** - ios/** + - linux/** linter: # The lint rules applied to this project can be customized in the diff --git a/lib/api/client.dart b/lib/api/client.dart index 2aab13f..6f6ead5 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -197,7 +197,9 @@ class Client { {int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async { final query = { 'limit': '$limit', - 'order': order, + // The server rejects a cursor combined with order: the cursor already + // carries the direction. + if (cursor == null) 'order': order, if (cursor != null) 'cursor': cursor, }; final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}/message', diff --git a/lib/api/models.dart b/lib/api/models.dart index 182386b..657c4df 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -262,9 +262,14 @@ class AgentInfo { final String id; final String name; final String mode; - AgentInfo(this.id, this.name, this.mode); - factory AgentInfo.fromJson(Map j) => - AgentInfo(j['id'] as String, j['name'] as String? ?? '', j['mode'] as String? ?? ''); + final bool hidden; + AgentInfo(this.id, this.name, this.mode, [this.hidden = false]); + factory AgentInfo.fromJson(Map j) => AgentInfo( + j['id'] as String, + j['name'] as String? ?? '', + j['mode'] as String? ?? '', + j['hidden'] as bool? ?? false, + ); } class PermissionRequest { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index bdb9869..c5a7ec6 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -7,8 +7,8 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:gpt_markdown/gpt_markdown.dart'; -import 'package:path_provider/path_provider.dart'; +import '../api/client.dart'; import '../api/models.dart'; import '../state.dart'; import '../widgets/usage_ring.dart'; @@ -31,10 +31,6 @@ class _ChatScreenState extends State { bool _pickerOpen = false; String _pickerKind = 'model'; String _pickerFilter = ''; - bool _usageOpen = false; - String _previewTitle = ''; - File? _previewFile; - bool _previewLoading = false; List<_Attach> _attachments = []; bool _attaching = false; @@ -42,13 +38,19 @@ class _ChatScreenState extends State { void initState() { super.initState(); chat.addListener(_onChat); + // 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 atEnd = _scroll.position.pixels >= - _scroll.position.maxScrollExtent - 40; - if (_stick != atEnd) setState(() => _stick = atEnd); + 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(_scroll.position.maxScrollExtent); + if (_scroll.hasClients) _scroll.jumpTo(0); }); } @@ -56,9 +58,7 @@ class _ChatScreenState extends State { if (mounted) setState(() {}); if (_stick) { WidgetsBinding.instance.addPostFrameCallback((_) { - if (_scroll.hasClients) { - _scroll.jumpTo(_scroll.position.maxScrollExtent); - } + if (_scroll.hasClients) _scroll.jumpTo(0); }); } } @@ -130,16 +130,39 @@ class _ChatScreenState extends State { return const Center(child: CircularProgressIndicator()); } final rows = _rows(); + final olderSlot = chat.hasMore || chat.loadingOlder ? 1 : 0; return ListView.builder( controller: _scroll, - itemCount: rows.length, + reverse: true, + itemCount: rows.length + olderSlot, itemBuilder: (context, i) { - final r = rows[i]; - return _row(r); + // 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 _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++) { @@ -688,16 +711,9 @@ class _ChatScreenState extends State { } String _modelLabel() { - ModelRef? m; - for (var i = chat.msgs.length - 1; i >= 0; i--) { - if (chat.msgs[i].model != null) { - m = chat.msgs[i].model; - break; - } - } - m ??= widget.session.model; + final m = chat.selectedModel ?? widget.session.model; final model = m == null ? '模型' : widget.app.modelName(m); - final agent = widget.session.agent; + final agent = chat.selectedAgent; return agent.isEmpty ? model : '$model · $agent'; } @@ -763,8 +779,8 @@ class _ChatScreenState extends State { Future _keepImage(String src, String name) async { try { - final dir = await getApplicationSupportDirectory(); - final d = Directory('${dir.path}/attachments'); + // No plugin needed: a cache copy is enough for the message being sent. + final d = Directory('${Directory.systemTemp.path}/openchamber-attachments'); await d.create(recursive: true); final dst = '${d.path}/${DateTime.now().microsecondsSinceEpoch}-${name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}'; await File(src).copy(dst); @@ -897,14 +913,22 @@ class _ChatScreenState extends State { Widget _pickerItems(ScrollController controller) { final filter = _pickerFilter.toLowerCase(); - final items = <(String, String, Object?)>[]; // (key, title, modelOrAgent) + // (key, title, modelOrAgent, selected) + final items = <(String, String, Object?, bool)>[]; if (_pickerKind == 'model') { + final current = chat.selectedModel; for (final m in widget.app.modelList) { - items.add(('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId))); + final selected = current != null && + current.providerId == m.providerId && + current.id == m.id; + items.add( + ('${m.providerId}/${m.id}', m.name, ModelRef(m.id, m.providerId), selected)); } } else { for (final a in widget.app.agentList) { - if (a.mode == 'primary') items.add(('agent/${a.id}', a.name, a.id)); + // Compaction, Title and Summary are primary but hidden. + if (a.mode != 'primary' || a.hidden) continue; + items.add(('agent/${a.id}', a.name, a.id, chat.selectedAgent == a.id)); } } final visible = items @@ -920,6 +944,7 @@ class _ChatScreenState extends State { final it = visible[i]; return ListTile( title: Text(it.$2), + trailing: it.$4 ? const Icon(Icons.check) : null, onTap: () { Navigator.pop(context); setState(() => _pickerOpen = false); @@ -957,81 +982,20 @@ class _ChatScreenState extends State { // ------------------------------------------------------------ previews Future _openPreview(_ImageRef ref) async { - setState(() { - _previewTitle = ref.label; - _previewFile = null; - _previewLoading = true; - }); - _previewDialog(context); - try { - final bytes = await _loadPreview(ref.source); - final dir = await getApplicationSupportDirectory(); - final d = Directory('${dir.path}/previews'); - await d.create(recursive: true); - final f = File( - '${d.path}/${DateTime.now().microsecondsSinceEpoch}-${ref.label.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_')}'); - await f.writeAsBytes(bytes); - if (mounted) { - setState(() { - _previewFile = f; - _previewLoading = false; - }); - } - } catch (e) { - if (mounted) { - setState(() => _previewLoading = false); - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('无法预览:$e'))); - } - } - } - - void _previewDialog(BuildContext context) { - showDialog( + await showDialog( context: context, - builder: (context) => Dialog( - insetPadding: const EdgeInsets.all(12), - child: ConstrainedBox( - constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9), - child: ListenableBuilder( - listenable: chat, - builder: (context, _) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.all(12), - child: Text(_previewTitle, maxLines: 2, overflow: TextOverflow.ellipsis), - ), - if (_previewLoading) - const Padding( - padding: EdgeInsets.all(40), - child: CircularProgressIndicator(), - ) - else if (_previewFile != null) - Flexible(child: Image.file(_previewFile!, fit: BoxFit.contain)), - const SizedBox(height: 8), - ], - ), - ), - ), + builder: (_) => _ImagePreviewDialog( + title: ref.label, + source: ref.source, + directory: chat.dir, + client: widget.app.client!, ), ); } - Future _loadPreview(String source) async { - if (source.startsWith('data:')) { - final comma = source.indexOf(','); - final meta = source.substring(5, comma); - if (!meta.contains('base64')) throw Exception('不支持的 data URL'); - return base64Decode(source.substring(comma + 1)); - } - final bytes = await widget.app.client!.rawFile(source, directory: chat.dir); - return Uint8List.fromList(bytes); - } - // ------------------------------------------------------------ usage void _usageSheet(BuildContext context) { - if (!_usageOpen) return; final r = chat.usageReading(); showModalBottomSheet( context: context, @@ -1043,7 +1007,7 @@ class _ChatScreenState extends State { children: [ const Text('上下文占用', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const SizedBox(height: 12), - _usageRow('模型', widget.app.modelName(_lastModel())), + _usageRow('模型', widget.app.modelName(chat.selectedModel ?? _lastModel())), _usageRow('已用 tokens', _fmtTokens(r.$1)), if (r.$5) ...[ _usageRow('上下文上限', _fmtTokens(r.$2)), @@ -1057,7 +1021,7 @@ class _ChatScreenState extends State { ], ), ), - ).then((_) => _usageOpen = false); + ); } ModelRef? _lastModel() { @@ -1167,3 +1131,118 @@ String toolOutput(ContentPart p) { if (out.isEmpty) return st.error ?? ''; return out; } + + +/// 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 _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 _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), + ], + ), + ), + ); + } +} diff --git a/lib/screens/servers_screen.dart b/lib/screens/servers_screen.dart index ce4829b..25abbde 100644 --- a/lib/screens/servers_screen.dart +++ b/lib/screens/servers_screen.dart @@ -6,7 +6,11 @@ import '../storage.dart'; /// The first screen: the saved servers, or the connect form. class ServersScreen extends StatefulWidget { final AppState app; - const ServersScreen({super.key, required this.app}); + + /// Open the "add server" form straight away (pushed from the server sheet + /// while a connection is live). + final bool startEditing; + const ServersScreen({super.key, required this.app, this.startEditing = false}); @override State createState() => _ServersScreenState(); @@ -25,6 +29,12 @@ class _ServersScreenState extends State { bool _connecting = false; String? _formError; + @override + void initState() { + super.initState(); + if (widget.startEditing) _editing = true; + } + @override Widget build(BuildContext context) { return ListenableBuilder( @@ -279,6 +289,8 @@ class _ServersScreenState extends State { if (mounted) { if (widget.app.client != null) { setState(() => _editing = false); + // Pushed on top of a live session list: return there. + if (Navigator.of(context).canPop()) Navigator.of(context).pop(); } else { setState(() { _connecting = false; diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index c146f9c..94bf037 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../api/models.dart'; import '../state.dart'; +import 'servers_screen.dart'; import 'chat_screen.dart'; /// The connected screen: the live session list. @@ -317,7 +318,13 @@ class _SessionsScreenState extends State { ListTile( leading: const Icon(Icons.add), title: const Text('添加服务器'), - onTap: () => Navigator.pop(context), + onTap: () { + Navigator.pop(context); + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => + ServersScreen(app: app, startEditing: true), + )); + }, ), if (app.client != null) ListTile( diff --git a/lib/state.dart b/lib/state.dart index a066dd7..b1c97d4 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -473,14 +473,12 @@ class ChatState extends ChangeNotifier { bool hasMore = false; bool loadingOlder = false; Map> imagePaths = {}; - final Map previewCache = {}; - bool previewOpen = false; - String previewTitle = ''; - String? previewPath; - bool previewLoading = false; - int previewSeq = 0; + ModelRef? selectedModel; + String selectedAgent; - ChatState(this.app, this.session); + ChatState(this.app, this.session) + : selectedModel = session.model, + selectedAgent = session.agent; /// Public way to signal UI changes. void touch() => notifyListeners(); @@ -494,8 +492,9 @@ class ChatState extends ChangeNotifier { try { final page = await app.client!.listMessages(id, directory: dir); _setMessages(page.data); - olderCursor = page.previous; - hasMore = page.previous != null; + // A desc page's `next` cursor points at the older side. + olderCursor = page.next; + hasMore = page.next != null; loading = false; notifyListeners(); await reloadTail(); @@ -524,9 +523,9 @@ class ChatState extends ChangeNotifier { final seen = msgs.map((m) => m.id).toSet(); final older = page.data.where((m) => !seen.contains(m.id)).toList(); msgs = [...older, ...msgs]; - _reindex(); - olderCursor = page.previous; - hasMore = page.previous != null; + _sortMsgs(); + olderCursor = page.next; + hasMore = page.next != null; } catch (_) {} loadingOlder = false; notifyListeners(); @@ -534,6 +533,15 @@ class ChatState extends ChangeNotifier { void _setMessages(List list) { msgs = list; + _sortMsgs(); + } + + /// Oldest first: a page arrives newest-first (order: desc). + void _sortMsgs() { + msgs.sort((a, b) { + if (a.created == b.created) return a.id.compareTo(b.id); + return a.created.compareTo(b.created); + }); _reindex(); } @@ -553,7 +561,7 @@ class ChatState extends ChangeNotifier { created: DateTime.now().millisecondsSinceEpoch, files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [], )); - _reindex(); + _sortMsgs(); notifyListeners(); try { await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files); @@ -617,6 +625,8 @@ class ChatState extends ChangeNotifier { Future switchModel(ModelRef model) async { try { await app.client!.switchModel(id, model, directory: dir); + selectedModel = model; + notifyListeners(); } catch (e) { error = e.toString(); notifyListeners(); @@ -626,6 +636,8 @@ class ChatState extends ChangeNotifier { Future switchAgent(String agent) async { try { await app.client!.switchAgent(id, agent, directory: dir); + selectedAgent = agent; + notifyListeners(); } catch (e) { error = e.toString(); notifyListeners(); @@ -719,6 +731,16 @@ class ChatState extends ChangeNotifier { case 'session.tool.progress': if (mid != null) _applyTool(mid, type, data); break; + case 'session.model.selected': + final model = data['model']; + if (model is Map) { + selectedModel = ModelRef.fromJson(model); + } + break; + case 'session.agent.selected': + final agent = data['agent']; + if (agent is String && agent.isNotEmpty) selectedAgent = agent; + break; } notifyListeners(); } @@ -726,7 +748,7 @@ class ChatState extends ChangeNotifier { void _ensureAssistant(String id, int created) { if (byId.containsKey(id)) return; msgs.add(Message(id: id, type: 'assistant', created: created)); - _reindex(); + _sortMsgs(); } void _applyDelta(String mid, int ordinal, String kind, String type, Map data) { diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..1bde07a --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "openchamber") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "net.blumia.openchamber.openchamber") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the hook/build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..d0e7f79 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..ce58916 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..34210fd --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,129 @@ +#include "my_application.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + gtk_window_set_default_size(window, 1280, 720); + + // If you want to use a header bar, uncomment the following lines. + // Header bars are commonly used in GNOME based desktop environments and + // allow additional widgets to be added to the title bar. + // See https://docs.gtk.org/gtk3/class.HeaderBar.html + // GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + // gtk_widget_show(GTK_WIDGET(header_bar)); + // gtk_header_bar_set_show_close_button(header_bar, TRUE); + // gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + + gtk_window_set_title(window, "openchamber"); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/pubspec.lock b/pubspec.lock index c7d4d82..d51d773 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -313,18 +313,18 @@ packages: dependency: transitive description: name: jni - sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c" + sha256: "822c3f004742158b80b558773ebed29891f407058d5798992436a68bdf14ccda" url: "https://pub.flutter-io.cn" source: hosted - version: "1.1.2" + version: "1.2.0" jni_flutter: dependency: transitive description: name: jni_flutter - sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + sha256: "586594ad345b403bda8a794b0b8a9e34298238b86c2a7d7f15160b092fe9ef3d" url: "https://pub.flutter-io.cn" source: hosted - version: "1.0.4+1" + version: "1.1.0" jni_util: dependency: transitive description: @@ -446,7 +446,7 @@ packages: source: hosted version: "1.1.0" path_provider: - dependency: "direct main" + dependency: transitive description: name: path_provider sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 diff --git a/pubspec.yaml b/pubspec.yaml index 5790e68..032440c 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.1+301 +version: 0.3.2+302 environment: sdk: ^3.14.0 @@ -14,7 +14,6 @@ dependencies: shared_preferences: ^2.3.0 flutter_secure_storage: ^11.2.0 file_picker: ^13.0.0 - path_provider: ^2.1.0 gpt_markdown: ^1.4.0 socks5_proxy: ^2.1.2 diff --git a/tool/history_probe.dart b/tool/history_probe.dart new file mode 100644 index 0000000..b08b502 --- /dev/null +++ b/tool/history_probe.dart @@ -0,0 +1,65 @@ +// Pages a session's history exactly as ChatState does, and reports whether +// every message is reached. Run against a live server: +// dart run tool/history_probe.dart [directory] +import 'dart:io'; + +import 'package:openchamber/api/client.dart'; + +Future main(List args) async { + final id = args.isEmpty ? '' : args[0]; + final dir = args.length > 1 + ? args[1] + : Directory.current.path; + if (id.isEmpty) { + print('usage: dart run tool/history_probe.dart [directory]'); + exit(2); + } + final client = Client(Uri.parse('http://127.0.0.1:3000')); + + // 1. What ChatState loads first, then each "load earlier" page. + final first = await client.listMessages(id, limit: 30, directory: dir); + final seen = {for (final m in first.data) m.id}; + print('page 1: ${first.data.length} msgs next=${first.next != null}'); + var cursor = first.next; + var page = 2; + var oldest = 0; + while (cursor != null && page <= 200) { + final p = await client.listMessages(id, + limit: 30, cursor: cursor, directory: dir); + if (p.data.isEmpty) { + print('page $page: empty (cursor exhausted)'); + break; + } + final added = p.data.where((m) => seen.add(m.id)).length; + oldest = p.data + .map((m) => m.created) + .reduce((a, b) => a < b ? a : b); + print('page $page: ${p.data.length} msgs (+$added new, ' + 'oldest=${DateTime.fromMillisecondsSinceEpoch(oldest)})'); + cursor = p.next; + page++; + if (added == 0) { + print('no progress at page $page: stopping'); + break; + } + } + + // 2. The full list, for comparison. + final all = {}; + var c = null as String?; + do { + final p = await client.listMessages(id, + limit: 200, cursor: c, directory: dir); + all.addAll(p.data.map((m) => m.id)); + c = p.next; + } while (c != null); + + print('----'); + print('paged: ${seen.length} unique messages'); + print('total: ${all.length} messages'); + print('missing: ${all.difference(seen).length}'); + final missing = all.difference(seen); + if (missing.isNotEmpty) print('first missing: ${missing.take(3).join(', ')}'); + client.close(); + exit(0); +} diff --git a/tool/proxy_probe.dart b/tool/proxy_probe.dart index c4e6b8e..3500878 100644 --- a/tool/proxy_probe.dart +++ b/tool/proxy_probe.dart @@ -24,6 +24,24 @@ Future probe(String? proxy) async { } } +Future probeRaw(String? proxy) async { + final label = proxy ?? 'direct'; + final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy); + try { + final bytes = await client + .rawFile( + '/home/blumia/Sources/openchamber-android-native/resources/icon.png', + directory: '/home/blumia/Sources/openchamber-android-native', + ) + .timeout(const Duration(seconds: 15)); + print('OK raw $label bytes=${bytes.length}'); + } on Object catch (e) { + print('FAIL raw $label ${e.toString().split('\n').first}'); + } finally { + client.close(); + } +} + Future probeStream(String? proxy) async { final label = proxy ?? 'direct'; final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy); @@ -48,5 +66,8 @@ Future main() async { await probe('socks5://127.0.0.1:1'); await probeStream('socks5://127.0.0.1:1080'); await probeStream('http://127.0.0.1:8081'); + await probeRaw(null); + await probeRaw('socks5://127.0.0.1:1080'); + await probeRaw('http://127.0.0.1:8081'); exit(0); }