diff --git a/PLAN.md b/PLAN.md index 47de950..9fdea50 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,21 @@ --- +## 0.3.13 草稿会话与分组侧栏(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 新会话 = 草稿 | 左侧栏 `+` 不再弹「标题」底部框,而是进入 `NewSessionScreen`:大标题「我们今天要做什么?」、项目 chip(`GET /api/project`,按 canonical 去重)、模型/智能体 chip(与聊天共用新的 `lib/widgets/model_picker.dart`)、附件与输入框。**发送前不创建会话**:第一次发送才 `POST /api/session`(带 `location.directory`、`model`、`agent`),随后 `openChat` 并发出这条消息 | +| 草稿生命周期 | 草稿只存内存(`AppState.draft` + `draftOpen`):未发送就离开时保留,侧栏顶部出现「草稿 · 项目名」一行(笔图标、首行、× 丢弃),点它回到草稿;发送成功即清空,创建失败留在草稿并显示错误。第二期接服务端 `/api/session-drafts`(已记入项目待办) | +| 侧栏分组 | 会话按 `location.directory` 分组(`.openchamber/chats` 归为「聊天」),组头是项目名 + 路径 + 折叠 + 「在此项目新会话」;组内按 `updated` 倒序并插「今天 / 昨天 / 本周早些时候 / 更早」小标题;默认过滤子会话(`parentID`),父会话的运行点会带上子会话的活动 | +| 置顶 | 写进 `session.metadata.openchamber.pinned`(`PATCH /api/session/:id {metadata}`,合并原有 metadata),跨客户端可见;置顶的会话收进顶部「已置顶」区,不再重复出现在项目组里 | +| 归档 | 主列表请求 `archived=false`;底部「显示已归档」按需拉 `archived=true`,展开后可取消归档(事件 `session.archived/unarchived` 同步) | +| 行操作 | 左滑(`flutter_slidable`,DrawerMotion)露出置顶 / 归档 / 删除;`⋮` 菜单有重命名、置顶、归档、删除、复制会话 ID;选中行有底色与加粗 | +| 其它 | 会话列表支持「载入更多」(cursor 分页);聊天页标题改为跟随 `AppState.sessions`,服务端根据首条消息生成的标题会即时显示;附件选择与缩略图抽到 `lib/widgets/composer_attachment.dart`,与草稿页共用 | +| 版本 | **0.3.13(code 313)** | + +--- + ## 0.3.12 侧栏头部、Termux 按键栏、键盘避让与记忆(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index c95659e..f653c74 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.12 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.13 — 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 @@ -15,7 +15,9 @@ after a reload), the agent's native forms, permissions. The files sidebar also carries the project knowledge (notes, todos, plans, and agent memory when the server enables it) and a full terminal with a Termux-style key bar; downloads show their progress and can be cancelled. The panel is a tab row with its own -close button, and each tab has its own header row. A +close button, and each tab has its own header row. Starting a session opens a +draft that only creates the session on the first send; the session list is +grouped by project with date captions, pins, archive and swipe actions. A phone opens the session list as the left drawer and a wide window (tablet, desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop target used for local testing. diff --git a/lib/api/client.dart b/lib/api/client.dart index 09b6a04..fc947b4 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -62,6 +62,7 @@ class Client { String order = 'desc', String? search, String? directory, + bool? archived, }) async { final query = { 'limit': '$limit', @@ -69,6 +70,7 @@ class Client { if (cursor != null) 'cursor': cursor, if (search != null && search.isNotEmpty) 'search': search, if (directory != null && directory.isNotEmpty) 'directory': directory, + if (archived != null) 'archived': '$archived', }; final r = await _json('GET', '/api/session', query: query, directory: directory); final data = (r['data'] as List? ?? []) @@ -85,22 +87,40 @@ class Client { return data.keys.toSet(); } - Future createSession({String? title, String? directory}) async { + Future createSession( + {String? title, + String? directory, + ModelRef? model, + String? agent}) async { final r = await _json('POST', '/api/session', body: { if (title != null && title.isNotEmpty) 'title': title, if (directory != null && directory.isNotEmpty) 'location': {'directory': directory}, + // The first turn runs on the draft's selection; no switch after create. + if (model != null) 'model': model.toJson(), + if (agent != null && agent.isNotEmpty) 'agent': agent, }); return Session.fromJson(r['data'] as Map); } - Future updateSession(String id, {String? title, bool? archived}) async { + Future updateSession(String id, + {String? title, bool? archived, Map? metadata}) async { await _json('PATCH', '/api/session/${Uri.encodeComponent(id)}', body: { if (title != null) 'title': title, if (archived != null) 'archived': archived, + if (metadata != null) 'metadata': metadata, }); } + /// The projects (checkouts and chat folders) an agent can open a session in. + Future> listProjects() async { + final list = await _jsonList('GET', '/api/project'); + return [ + for (final p in list) + if (p is Map) ProjectInfo.fromJson(p), + ]; + } + Future deleteSession(String id) async { await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}'); } @@ -681,6 +701,17 @@ class Client { // --------------------------------------------------------------- transport + Future> _jsonList(String method, String path, + {Map? query}) async { + final res = await _request(method, path, query: query); + final text = utf8.decode(await res.collect(), allowMalformed: true); + if (res.statusCode < 200 || res.statusCode >= 300) { + throw ApiError(res.statusCode, text.trim()); + } + final decoded = jsonDecode(text); + return decoded is List ? decoded : const []; + } + Future> _json(String method, String path, {Map? query, Map? body, diff --git a/lib/api/models.dart b/lib/api/models.dart index 55a1c8e..fc2c046 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -52,34 +52,126 @@ class Location { class Session { final String id; + final String? parentID; + final String projectID; final String title; final String agent; final ModelRef? model; final Location? location; + final Map metadata; final int created; final int updated; + final int viewed; + final int archived; + Session({ required this.id, required this.title, + this.parentID, + this.projectID = '', this.agent = '', this.model, this.location, + this.metadata = const {}, this.created = 0, this.updated = 0, + this.viewed = 0, + this.archived = 0, }); + factory Session.fromJson(Map j) { final t = j['time'] as Map? ?? {}; return Session( id: j['id'] as String, + parentID: j['parentID'] as String?, + projectID: j['projectID'] as String? ?? '', title: j['title'] as String? ?? '', agent: j['agent'] as String? ?? '', model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map), location: j['location'] == null ? null : Location.fromJson(j['location'] as Map), + metadata: j['metadata'] is Map + ? Map.from(j['metadata'] as Map) + : const {}, created: (t['created'] as num?)?.toInt() ?? 0, updated: (t['updated'] as num?)?.toInt() ?? 0, + viewed: (t['viewed'] as num?)?.toInt() ?? 0, + archived: (t['archived'] as num?)?.toInt() ?? 0, ); } + String get directory => location?.directory ?? ''; + + bool get isChild => parentID != null && parentID!.isNotEmpty; + bool get isArchived => archived > 0; + + /// Pins live in the session's metadata (`openchamber.pinned`), so every + /// client of the server sees them. + bool get isPinned { + final openchamber = metadata['openchamber']; + return openchamber is Map && openchamber['pinned'] is Map; + } + + int get pinnedAt { + final openchamber = metadata['openchamber']; + if (openchamber is! Map) return 0; + final pinned = openchamber['pinned']; + return pinned is Map && pinned['at'] is num ? (pinned['at'] as num).toInt() : 0; + } + + Session copyWith({ + String? title, + ModelRef? model, + String? agent, + Map? metadata, + int? viewed, + int? archived, + int? updated, + }) => + Session( + id: id, + parentID: parentID, + projectID: projectID, + title: title ?? this.title, + agent: agent ?? this.agent, + model: model ?? this.model, + location: location, + metadata: metadata ?? this.metadata, + created: created, + updated: updated ?? this.updated, + viewed: viewed ?? this.viewed, + archived: archived ?? this.archived, + ); +} + +/// A project the server knows: a checkout (or chat folder) an agent can work +/// in. [canonical] is the directory a session there carries. +class ProjectInfo { + final String id; + final String canonical; + final String name; + final String vcs; + + const ProjectInfo({ + required this.id, + required this.canonical, + this.name = '', + this.vcs = '', + }); + + factory ProjectInfo.fromJson(Map j) => ProjectInfo( + id: j['id'] as String? ?? '', + canonical: j['canonical'] as String? ?? '', + name: j['name'] as String? ?? '', + vcs: j['vcs'] as String? ?? '', + ); + + String get label { + if (name.trim().isNotEmpty) return name.trim(); + final trimmed = + canonical.replaceAll(RegExp(r'/+$'), ''); + final index = trimmed.lastIndexOf('/'); + return index >= 0 ? trimmed.substring(index + 1) : trimmed; + } } class ContentPart { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 9aff5fd..1a3318b 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -3,14 +3,15 @@ import 'dart:convert'; import 'dart:io'; 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 '../api/client.dart'; import '../api/models.dart'; import '../state.dart'; +import '../widgets/composer_attachment.dart'; import '../widgets/markdown_view.dart'; +import '../widgets/model_picker.dart'; import '../widgets/usage_ring.dart'; import 'files_panel.dart'; @@ -39,10 +40,7 @@ class _ChatScreenState extends State { final FocusNode _inputFocus = FocusNode(); final ScrollController _scroll = ScrollController(); bool _stick = true; - bool _pickerOpen = false; - String _pickerKind = 'model'; - String _pickerFilter = ''; - List<_Attach> _attachments = []; + List _attachments = []; bool _attaching = false; /// Decoded user attachments, so a rebuild does not base64-decode again. @@ -109,8 +107,7 @@ class _ChatScreenState extends State { tooltip: '会话', onPressed: widget.onOpenSessions, ), - title: Text(widget.session.title.isEmpty ? '会话' : widget.session.title, - maxLines: 1, overflow: TextOverflow.ellipsis), + title: Text(_title(), maxLines: 1, overflow: TextOverflow.ellipsis), actions: [ Padding( padding: const EdgeInsets.only(right: 4), @@ -122,13 +119,21 @@ class _ChatScreenState extends State { child: Text(_modelLabel(), maxLines: 1, overflow: TextOverflow.ellipsis), ), - onPressed: () => _openPicker('model'), + onPressed: () => showModelPickerSheet( + context, + app: widget.app, + kind: 'model', + model: chat.selectedModel ?? widget.session.model, + agent: chat.selectedAgent, + onModel: (m) => chat.switchModel(m), + onAgent: (a) => chat.switchAgent(a), + ), ), ), IconButton( icon: const Icon(Icons.view_sidebar_outlined), tooltip: '文件', - onPressed: () => showFilesPanel(context, widget.app, widget.session), + onPressed: () => showFilesPanel(context, widget.app, chat.dir), ), ], ), @@ -394,6 +399,17 @@ class _ChatScreenState extends State { } } + /// The session's title as the list has it: the server names a session from + /// its first message, which arrives after this screen was built. + String _title() { + for (final session in widget.app.sessions) { + if (session.id == widget.session.id && session.title.isNotEmpty) { + return session.title; + } + } + return widget.session.title.isEmpty ? '会话' : widget.session.title; + } + Widget _userRow(String id) { final m = chat.byId[id]!; final theme = Theme.of(context); @@ -1695,33 +1711,10 @@ class _ChatScreenState extends State { } /// Attachment chips with a thumbnail, unfolded above the input bar. - Widget _attachmentTray() { - return SizedBox( - height: 46, - child: ListView( - scrollDirection: Axis.horizontal, - children: [ - for (var i = 0; i < _attachments.length; i++) - Padding( - padding: const EdgeInsets.only(right: 6), - child: InputChip( - avatar: _attachments[i].path != null - ? CircleAvatar( - backgroundImage: FileImage(File(_attachments[i].path!)), - ) - : const Icon(Icons.insert_drive_file, size: 16), - label: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 160), - child: Text(_attachments[i].name, - maxLines: 1, overflow: TextOverflow.ellipsis), - ), - onDeleted: () => setState(() => _attachments.removeAt(i)), - ), - ), - ], - ), - ); - } + Widget _attachmentTray() => AttachmentTray( + items: _attachments, + onRemove: (i) => setState(() => _attachments.removeAt(i)), + ); String _modelLabel() { final m = chat.selectedModel ?? widget.session.model; @@ -1760,63 +1753,24 @@ class _ChatScreenState extends State { Future _pickFiles() async { setState(() => _attaching = true); try { - final files = await FilePicker.pickFiles(); - if (files.isEmpty) return; - for (final f in files) { - final bytes = await f.readAsBytes(); - if (bytes.length > 10 * 1024 * 1024) { - ScaffoldMessenger.of(context) - .showSnackBar(const SnackBar(content: Text('附件不能超过 10MB'))); - continue; + final picked = await pickComposerAttachments(context); + if (picked.isEmpty) return; + setState(() { + for (final file in picked) { + if (_attachments.length >= 5) break; + _attachments.add(file); } - final name = f.name; - final mime = _mime(name); - final dataUrl = 'data:$mime;base64,${base64Encode(bytes)}'; - String? keptPath; - if (mime.startsWith('image/') && f.path != null) { - keptPath = await _keepImage(f.path!, name); - } - setState(() { - if (_attachments.length >= 5) return; - _attachments.add(_Attach(name: name, mime: mime, dataUrl: dataUrl, path: keptPath)); - }); - } + }); } catch (e) { if (mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('选择失败:$e'))); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('选择失败:$e'))); } } finally { if (mounted) setState(() => _attaching = false); } } - Future _keepImage(String src, String name) async { - try { - // 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); - return dst; - } catch (_) { - return null; - } - } - - static String _mime(String name) { - final ext = name.contains('.') ? name.split('.').last.toLowerCase() : ''; - switch (ext) { - case 'png': return 'image/png'; - case 'jpg': case 'jpeg': return 'image/jpeg'; - case 'gif': return 'image/gif'; - case 'webp': return 'image/webp'; - case 'pdf': return 'application/pdf'; - case 'txt': return 'text/plain'; - case 'json': return 'application/json'; - default: return 'application/octet-stream'; - } - } - // ---------------------------------------------------------- permissions /// The agent's blocking questions sit just above the composer, like the @@ -1870,116 +1824,6 @@ class _ChatScreenState extends State { // -------------------------------------------------------------- sheets - void _openPicker(String kind) { - widget.app.refreshModels(); - setState(() { - _pickerOpen = true; - _pickerKind = kind; - _pickerFilter = ''; - }); - _pickerSheet(context); - } - - void _pickerSheet(BuildContext context) { - if (!_pickerOpen) return; - showModalBottomSheet( - context: context, - isScrollControlled: true, - builder: (context) => DraggableScrollableSheet( - expand: false, - initialChildSize: 0.8, - maxChildSize: 0.92, - builder: (context, controller) => ListenableBuilder( - listenable: chat, - builder: (context, _) { - final title = _pickerKind == 'agent' ? '选择智能体' : '选择模型'; - return Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(12, 12, 12, 4), - child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: SegmentedButton( - segments: const [ - ButtonSegment(value: 'model', label: Text('模型')), - ButtonSegment(value: 'agent', label: Text('智能体')), - ], - selected: {_pickerKind}, - showSelectedIcon: false, - onSelectionChanged: (s) { - setState(() => _pickerKind = s.first); - widget.app.refreshModels(); - }, - ), - ), - Padding( - padding: const EdgeInsets.all(12), - child: TextField( - onChanged: (v) => setState(() => _pickerFilter = v), - decoration: const InputDecoration(hintText: '搜索', border: OutlineInputBorder(), isDense: true), - ), - ), - Expanded( - child: _pickerItems(controller), - ), - ], - ); - }, - ), - ), - ).then((_) => _pickerOpen = false); - } - - Widget _pickerItems(ScrollController controller) { - final filter = _pickerFilter.toLowerCase(); - // (key, title, modelOrAgent, selected) - final items = <(String, String, Object?, bool)>[]; - if (_pickerKind == 'model') { - final current = chat.selectedModel; - for (final m in widget.app.modelList) { - 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) { - // 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 - .where((e) => filter.isEmpty || e.$2.toLowerCase().contains(filter)) - .toList(); - if (visible.isEmpty) { - return const Center(child: Text('没有结果')); - } - return ListView.builder( - controller: controller, - itemCount: visible.length, - itemBuilder: (context, i) { - 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); - if (it.$3 is ModelRef) { - chat.switchModel(it.$3 as ModelRef); - } else { - chat.switchAgent(it.$3 as String); - } - }, - ); - }, - ); - } - void _confirm({required String title, required String message, required String confirm, required VoidCallback onConfirm}) { showDialog( context: context, @@ -2188,14 +2032,6 @@ class _Step { const _Step(this.msgId, this.index, this.part); } -class _Attach { - final String name; - final String mime; - final String dataUrl; - final String? path; - _Attach({required this.name, required this.mime, required this.dataUrl, this.path}); -} - class _ImageRef { final String source; final String label; diff --git a/lib/screens/files_panel.dart b/lib/screens/files_panel.dart index 181bb7f..3251a5b 100644 --- a/lib/screens/files_panel.dart +++ b/lib/screens/files_panel.dart @@ -16,7 +16,7 @@ import 'knowledge_panel.dart'; import 'terminal_panel.dart'; Future showFilesPanel( - BuildContext context, AppState app, Session session) { + BuildContext context, AppState app, String directory) { return showGeneralDialog( context: context, barrierDismissible: true, @@ -32,7 +32,7 @@ Future showFilesPanel( child: SizedBox( width: width * 0.92, height: double.infinity, - child: FilesPanel(app: app, session: session), + child: FilesPanel(app: app, directory: directory), ), ), ); @@ -47,8 +47,11 @@ Future showFilesPanel( class FilesPanel extends StatefulWidget { final AppState app; - final Session session; - const FilesPanel({super.key, required this.app, required this.session}); + + /// The workspace directory this panel browses. A draft has one before it + /// has a session, so the panel never needs a session. + final String directory; + const FilesPanel({super.key, required this.app, required this.directory}); @override State createState() => _FilesPanelState(); @@ -67,7 +70,7 @@ const _skipDirs = { }; class _FilesPanelState extends State { - String get _root => widget.session.directory; + String get _root => widget.directory; Client? get _client => widget.app.client; String _path = ''; diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 98a5766..d09fdbc 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../state.dart'; import 'chat_screen.dart'; +import 'new_session_screen.dart'; import 'sessions_screen.dart'; class HomeScreen extends StatefulWidget { @@ -39,6 +40,7 @@ class _HomeScreenState extends State { void _maybeOpenFirst() { final app = widget.app; if (!mounted || _opening) return; + if (app.draftOpen) return; if (app.chat != null || app.sessions.isEmpty) return; _opening = true; app.openChat(app.sessions.first).whenComplete(() => _opening = false); @@ -56,16 +58,27 @@ class _HomeScreenState extends State { return LayoutBuilder( builder: (context, constraints) { final wide = constraints.maxWidth >= _wideBreakpoint; - final chat = widget.app.chat; - final chatView = chat == null - ? _empty(wide) - : ChatScreen( - key: ValueKey(chat.session.id), - app: widget.app, - session: chat.session, - onOpenSessions: wide ? null : () => - _scaffold.currentState?.openDrawer(), - ); + final app = widget.app; + final chat = app.chat; + final draftOpen = app.draftOpen && app.draft != null; + final content = draftOpen + ? NewSessionScreen( + key: const ValueKey('draft'), + app: app, + onOpenSessions: wide + ? null + : () => _scaffold.currentState?.openDrawer(), + ) + : chat == null + ? _empty(wide) + : ChatScreen( + key: ValueKey(chat.session.id), + app: app, + session: chat.session, + onOpenSessions: wide + ? null + : () => _scaffold.currentState?.openDrawer(), + ); if (wide) { return Scaffold( body: Row( @@ -75,7 +88,7 @@ class _HomeScreenState extends State { child: SessionListPane(app: widget.app), ), const VerticalDivider(width: 1), - Expanded(child: chatView), + Expanded(child: content), ], ), ); @@ -91,7 +104,7 @@ class _HomeScreenState extends State { onOpened: _closeDrawer, ), ), - body: chatView, + body: content, ); }, ); diff --git a/lib/screens/new_session_screen.dart b/lib/screens/new_session_screen.dart new file mode 100644 index 0000000..2e05361 --- /dev/null +++ b/lib/screens/new_session_screen.dart @@ -0,0 +1,449 @@ +// The new-session draft. Nothing exists on the server until the first message +// creates the session; this screen only holds the project, the model and what +// has been typed. +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../api/models.dart'; +import '../state.dart'; +import '../widgets/composer_attachment.dart'; +import '../widgets/model_picker.dart'; +import 'files_panel.dart'; + +class NewSessionScreen extends StatefulWidget { + final AppState app; + + /// Opens the session drawer; null where the list is always on screen. + final VoidCallback? onOpenSessions; + + const NewSessionScreen({ + super.key, + required this.app, + this.onOpenSessions, + }); + + @override + State createState() => _NewSessionScreenState(); +} + +class _NewSessionScreenState extends State { + SessionDraft get _draft => widget.app.draft!; + final TextEditingController _text = TextEditingController(); + final FocusNode _inputFocus = FocusNode(); + List _attachments = []; + bool _attaching = false; + + @override + void initState() { + super.initState(); + _text.text = _draft.text; + _text.addListener(_syncText); + _attachments = []; + _draft.attachments = 0; + } + + @override + void dispose() { + _text.removeListener(_syncText); + _text.dispose(); + _inputFocus.dispose(); + super.dispose(); + } + + void _syncText() { + if (_draft.text == _text.text) return; + widget.app.updateDraftText(_text.text); + } + + bool get _canSend => + _text.text.trim().isNotEmpty || _attachments.isNotEmpty; + + Future _send() async { + if (!_canSend || widget.app.sendingDraft) return; + final text = _text.text.trim(); + final files = [ + for (final a in _attachments) {'uri': a.dataUrl, 'name': a.name} + ]; + final images = [ + for (final a in _attachments) + if (a.isImage && a.path != null) a.path! + ]; + FocusScope.of(context).unfocus(); + await widget.app.sendDraft(text: text, files: files, images: images); + if (!mounted) return; + final draft = widget.app.draft; + if (draft != null) { + // The create failed: the draft is still here, keep what was typed. + _text.text = draft.text; + } else { + HapticFeedback.lightImpact(); + } + } + + Future _pickFiles() async { + setState(() => _attaching = true); + try { + final picked = await pickComposerAttachments(context); + if (picked.isEmpty) return; + setState(() { + for (final file in picked) { + if (_attachments.length >= 5) break; + _attachments.add(file); + } + _draft.attachments = _attachments.length; + }); + widget.app.touch(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('选择失败:$e'))); + } + } finally { + if (mounted) setState(() => _attaching = false); + } + } + + void _removeAttachment(int index) { + setState(() { + _attachments.removeAt(index); + _draft.attachments = _attachments.length; + }); + widget.app.touch(); + } + + @override + Widget build(BuildContext context) { + final app = widget.app; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return ListenableBuilder( + listenable: app, + builder: (context, _) { + final draft = app.draft; + if (draft == null) return const SizedBox.shrink(); + return Scaffold( + appBar: AppBar( + leading: widget.onOpenSessions == null + ? null + : IconButton( + icon: const Icon(Icons.menu), + tooltip: '会话', + onPressed: widget.onOpenSessions, + ), + title: const Text('新会话'), + actions: [ + IconButton( + icon: const Icon(Icons.folder_open_outlined), + tooltip: '文件', + onPressed: () => showFilesPanel(context, app, draft.directory), + ), + ], + ), + body: Column( + children: [ + Expanded( + child: Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Text( + '我们今天要做什么?', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 26, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (draft.error != null) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + draft.error!, + style: TextStyle( + fontSize: 12.5, color: scheme.error), + ), + ), + Row( + children: [ + _projectChip(draft), + const Spacer(), + _modelChip(draft), + ], + ), + const SizedBox(height: 6), + if (_attachments.isNotEmpty) + AttachmentTray( + items: _attachments, + onRemove: _removeAttachment, + ), + _composer(theme), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _projectChip(SessionDraft draft) { + final theme = Theme.of(context); + final label = widget.app.projectLabelFor(draft.directory); + return InkWell( + borderRadius: BorderRadius.circular(18), + onTap: _pickProject, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.folder_outlined, + size: 15, color: theme.hintColor), + const SizedBox(width: 5), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 170), + child: Text( + label.isEmpty ? '选择项目' : label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12.5, color: theme.hintColor), + ), + ), + Icon(Icons.expand_more, size: 16, color: theme.hintColor), + ], + ), + ), + ); + } + + Widget _modelChip(SessionDraft draft) { + final app = widget.app; + final model = draft.model == null + ? '模型' + : app.modelName(draft.model!); + final label = + draft.agent.isEmpty ? model : '$model · ${draft.agent}'; + return InkWell( + borderRadius: BorderRadius.circular(18), + onTap: () => showModelPickerSheet( + context, + app: app, + kind: 'model', + model: draft.model, + agent: draft.agent, + onModel: (m) => app.updateDraftModel(m), + onAgent: (a) => app.updateDraftModel(null, agent: a), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.smart_toy_outlined, + size: 15, color: Theme.of(context).hintColor), + const SizedBox(width: 5), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 170), + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, color: Theme.of(context).hintColor), + ), + ), + ], + ), + ), + ); + } + + Widget _composer(ThemeData theme) { + final scheme = theme.colorScheme; + final sending = widget.app.sendingDraft; + return Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(26), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + _roundKey( + icon: Icons.attach_file, + label: '添加附件', + onTap: _pickFiles, + busy: _attaching, + ), + const SizedBox(width: 4), + Expanded( + child: TextField( + controller: _text, + focusNode: _inputFocus, + minLines: 1, + maxLines: 5, + keyboardType: TextInputType.multiline, + onChanged: (_) => setState(() {}), + decoration: const InputDecoration( + isCollapsed: true, + border: InputBorder.none, + hintText: '规划、构建或提问', + contentPadding: EdgeInsets.symmetric(vertical: 8), + ), + ), + ), + const SizedBox(width: 4), + _sendKey(theme, sending), + ], + ), + ); + } + + Widget _roundKey( + {required IconData icon, + required String label, + required VoidCallback onTap, + bool busy = false}) { + final theme = Theme.of(context); + return Tooltip( + message: label, + child: InkWell( + borderRadius: BorderRadius.circular(18), + onTap: busy ? null : onTap, + child: Container( + width: 36, + height: 36, + alignment: Alignment.center, + decoration: BoxDecoration( + color: theme.colorScheme.surface, + shape: BoxShape.circle, + ), + child: busy + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)) + : Icon(icon, size: 19, color: theme.hintColor), + ), + ), + ); + } + + Widget _sendKey(ThemeData theme, bool sending) { + final scheme = theme.colorScheme; + return InkWell( + borderRadius: BorderRadius.circular(18), + onTap: sending || !_canSend ? null : _send, + child: Container( + width: 36, + height: 36, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _canSend || sending + ? scheme.primary + : scheme.surface, + shape: BoxShape.circle, + ), + child: sending + ? SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, color: scheme.onPrimary)) + : Icon(Icons.arrow_upward, + size: 20, + color: _canSend ? scheme.onPrimary : theme.hintColor), + ), + ); + } + + Future _pickProject() async { + final app = widget.app; + await app.refreshProjects(); + if (!mounted) return; + final draft = app.draft; + if (draft == null) return; + final projects = _selectableProjects(app.projects); + await showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) => DraggableScrollableSheet( + expand: false, + initialChildSize: 0.6, + maxChildSize: 0.9, + builder: (context, controller) => Column( + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 14, 16, 6), + child: Text('选择项目', + style: + TextStyle(fontSize: 17, fontWeight: FontWeight.w600)), + ), + Expanded( + child: ListView( + controller: controller, + children: [ + for (final project in projects) + ListTile( + dense: true, + leading: Icon( + project.vcs.isNotEmpty + ? Icons.account_tree_outlined + : Icons.folder_outlined, + size: 20), + title: Text(project.label, + maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text(project.canonical, + maxLines: 1, overflow: TextOverflow.ellipsis), + trailing: project.canonical == draft.directory + ? Icon(Icons.check, + size: 18, + color: Theme.of(context).colorScheme.primary) + : null, + onTap: () { + app.updateDraftTarget(project.canonical); + Navigator.pop(context); + }, + ), + if (projects.isEmpty) + const Padding( + padding: EdgeInsets.all(24), + child: Text('没有可用的项目', textAlign: TextAlign.center), + ), + ], + ), + ), + ], + ), + ), + ); + } + + /// The picker shows checkouts, not the server's chat folders (those are + /// reached by just starting a chat, not by choosing a project). The server + /// can list the same path twice (a project record and a sandbox), so one + /// path is one row, preferring the one that knows its VCS. + List _selectableProjects(List projects) { + final byPath = {}; + for (final project in projects) { + if (project.canonical.isEmpty) continue; + if (project.canonical.contains('/.config/openchamber/')) continue; + final existing = byPath[project.canonical]; + if (existing == null || + (existing.vcs.isEmpty && project.vcs.isNotEmpty)) { + byPath[project.canonical] = project; + } + } + return byPath.values.toList(); + } +} diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index f3a3583..d775cac 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -1,18 +1,20 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_slidable/flutter_slidable.dart'; import '../api/models.dart'; import '../state.dart'; import 'servers_screen.dart'; /// The session list: a drawer on a phone, a persistent column on a wide -/// layout. Selecting a session opens it in the chat beside it (the shell owns -/// that), so this only reports the choice through [onOpened]. +/// layout. Sessions are grouped by project, dated within it, and a row swipes +/// to pin, archive or delete. class SessionListPane extends StatefulWidget { final AppState app; - /// Called after a session was opened, so the drawer can close itself. + /// Called after a session (or the draft) was opened, so the drawer closes. final VoidCallback? onOpened; const SessionListPane({super.key, required this.app, this.onOpened}); @@ -25,6 +27,8 @@ class _SessionListPaneState extends State { bool _searchOpen = false; Timer? _timer; late final TextEditingController _searchCtrl; + final Set _collapsed = {}; + bool _showArchived = false; @override void initState() { @@ -39,22 +43,23 @@ class _SessionListPaneState extends State { super.dispose(); } + AppState get _app => widget.app; + void _onSearchChanged(String v) { _timer?.cancel(); _timer = Timer(const Duration(milliseconds: 350), () { if (v.isEmpty) { - widget.app.refreshSessions(); + _app.refreshSessions(); } else { - widget.app.searchSessions(v); + _app.searchSessions(v); } }); } @override Widget build(BuildContext context) { - final app = widget.app; return ListenableBuilder( - listenable: app, + listenable: _app, builder: (context, _) { final scheme = Theme.of(context).colorScheme; return SafeArea( @@ -82,15 +87,15 @@ class _SessionListPaneState extends State { _searchOpen = !_searchOpen; if (!_searchOpen) { _searchCtrl.clear(); - app.refreshSessions(); + _app.refreshSessions(); } }); }, ), IconButton( icon: const Icon(Icons.add), - tooltip: '新建会话', - onPressed: _newSessionSheet, + tooltip: '新会话', + onPressed: () => _newSession(), ), ], ), @@ -110,23 +115,23 @@ class _SessionListPaneState extends State { ), ), ), - if (app.error != null) + if (_app.error != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ Expanded( - child: Text(app.error!, + child: Text(_app.error!, style: TextStyle( color: scheme.error, fontSize: 13)), ), TextButton( - onPressed: app.refreshSessions, + onPressed: _app.refreshSessions, child: const Text('重试')), ], ), ), - Expanded(child: _body()), + Expanded(child: _body(scheme)), ], ), ); @@ -134,92 +139,471 @@ class _SessionListPaneState extends State { ); } - Widget _body() { - final app = widget.app; + Widget _body(ColorScheme scheme) { + final app = _app; if (app.sessionsLoading && app.sessions.isEmpty) { return const Center(child: CircularProgressIndicator()); } - if (app.sessions.isEmpty) { + final draft = app.draft; + final topLevel = [ + for (final s in app.sessions) + if (!s.isChild) s + ]; + final pinned = [ + for (final s in topLevel) + if (s.isPinned) s + ]..sort((a, b) => b.pinnedAt.compareTo(a.pinnedAt)); + final unpinned = [ + for (final s in topLevel) + if (!s.isPinned) s + ]; + if (topLevel.isEmpty && draft == null) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ - const Text('暂无会话'), + Text(_searchCtrl.text.isEmpty ? '暂无会话' : '没有匹配的会话'), const SizedBox(height: 8), FilledButton( - onPressed: _newSessionSheet, child: const Text('新建会话')), + onPressed: () => _newSession(), child: const Text('新会话')), ], ), ); } return RefreshIndicator( - onRefresh: app.refreshSessions, - child: ListView.builder( - itemCount: app.sessions.length, - itemBuilder: (context, i) { - final s = app.sessions[i]; - final running = app.active.contains(s.id); - final selected = widget.app.chat?.session.id == s.id; - return ListTile( - selected: selected, - title: Text(s.title.isEmpty ? '(无标题会话)' : s.title, - maxLines: 1, overflow: TextOverflow.ellipsis), - subtitle: Text(_subtitle(s), - maxLines: 1, overflow: TextOverflow.ellipsis), - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (running) - Padding( - padding: const EdgeInsets.only(right: 8), - child: Icon(Icons.circle, - size: 10, - color: Theme.of(context).colorScheme.primary), + onRefresh: () async { + await app.refreshSessions(); + if (app.archivedLoaded) await app.refreshArchived(); + }, + child: ListView( + padding: const EdgeInsets.only(bottom: 16), + children: [ + if (draft != null) _draftRow(draft), + if (pinned.isNotEmpty) ..._pinnedSection(pinned), + for (final group in _groups(unpinned)) ..._groupSection(group), + _footer(scheme), + ], + ), + ); + } + + // --------------------------------------------------------------- groups + + bool _isChatDirectory(String directory) => + directory.contains('/.config/openchamber/chats'); + + String _groupLabel(String key) => + key == '\u0000chats' ? '聊天' : _app.projectLabelFor(key); + + List<_SessionGroup> _groups(List sessions) { + final map = >{}; + for (final session in sessions) { + final key = _isChatDirectory(session.directory) + ? '\u0000chats' + : session.directory; + map.putIfAbsent(key, () => []).add(session); + } + final groups = [ + for (final entry in map.entries) + _SessionGroup( + key: entry.key, + label: _groupLabel(entry.key), + path: entry.key == '\u0000chats' ? '' : entry.key, + sessions: entry.value + ..sort((a, b) => b.updated.compareTo(a.updated)), + ), + ]; + groups.sort((a, b) { + final aTime = a.sessions.isEmpty ? 0 : a.sessions.first.updated; + final bTime = b.sessions.isEmpty ? 0 : b.sessions.first.updated; + return bTime.compareTo(aTime); + }); + return groups; + } + + List _groupSection(_SessionGroup group) { + final collapsed = _collapsed.contains(group.key); + return [ + _groupHeader(group, collapsed: collapsed), + if (!collapsed) + for (final entry in _dated(group.sessions)) ...[ + _caption(entry.key), + for (final session in entry.value) _row(session), + ], + ]; + } + + Widget _groupHeader(_SessionGroup group, {required bool collapsed}) { + final theme = Theme.of(context); + return InkWell( + onTap: () => setState(() { + if (collapsed) { + _collapsed.remove(group.key); + } else { + _collapsed.add(group.key); + } + }), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 4, 4), + child: Row( + children: [ + Icon(collapsed ? Icons.chevron_right : Icons.expand_more, + size: 16, color: theme.hintColor), + const SizedBox(width: 2), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + group.label.isEmpty ? '未命名项目' : group.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12.5, fontWeight: FontWeight.w700), ), - PopupMenuButton( - onSelected: (v) => _sessionAction(s, v), - itemBuilder: (_) => const [ - PopupMenuItem(value: 'rename', child: Text('重命名')), - PopupMenuItem(value: 'archive', child: Text('归档')), - PopupMenuItem(value: 'delete', child: Text('删除')), - ], - ), - ], + if (group.path.isNotEmpty) + Text( + group.path, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: + TextStyle(fontSize: 10.5, color: theme.hintColor), + ), + ], + ), ), - onTap: () { - app.openChat(s); - widget.onOpened?.call(); - }, - ); + IconButton( + icon: const Icon(Icons.add, size: 18), + tooltip: '在此项目新会话', + visualDensity: VisualDensity.compact, + onPressed: () => _newSession(directory: group.path), + ), + ], + ), + ), + ); + } + + Widget _caption(String label) { + return Padding( + padding: const EdgeInsets.fromLTRB(28, 6, 12, 2), + child: Text(label, + style: TextStyle( + fontSize: 11, color: Theme.of(context).hintColor)), + ); + } + + /// 今天 / 昨天 / 本周早些时候 / 更早, in that order. + List>> _dated(List sessions) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final yesterday = today.subtract(const Duration(days: 1)); + final weekAgo = today.subtract(const Duration(days: 7)); + final buckets = >{ + '今天': [], + '昨天': [], + '本周早些时候': [], + '更早': [], + }; + for (final session in sessions) { + final time = session.updated > 0 + ? DateTime.fromMillisecondsSinceEpoch(session.updated) + : DateTime.fromMillisecondsSinceEpoch(session.created); + final day = DateTime(time.year, time.month, time.day); + final key = day == today + ? '今天' + : day == yesterday + ? '昨天' + : day.isAfter(weekAgo) + ? '本周早些时候' + : '更早'; + buckets[key]!.add(session); + } + return [ + for (final entry in buckets.entries) + if (entry.value.isNotEmpty) entry, + ]; + } + + // ----------------------------------------------------------------- rows + + List _pinnedSection(List pinned) { + final collapsed = _collapsed.contains('pinned'); + return [ + InkWell( + onTap: () => setState(() { + if (collapsed) { + _collapsed.remove('pinned'); + } else { + _collapsed.add('pinned'); + } + }), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 4, 4), + child: Row( + children: [ + Icon(Icons.push_pin, + size: 13, color: Theme.of(context).hintColor), + const SizedBox(width: 5), + Expanded( + child: Text('已置顶', + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w700, + color: Theme.of(context).hintColor)), + ), + Icon(collapsed ? Icons.chevron_right : Icons.expand_more, + size: 16, color: Theme.of(context).hintColor), + ], + ), + ), + ), + if (!collapsed) + for (final session in pinned) _row(session), + ]; + } + + Widget _draftRow(SessionDraft draft) { + final theme = Theme.of(context); + final label = draft.firstLine.isEmpty ? '新会话' : draft.firstLine; + final project = _app.projectLabelFor(draft.directory); + return ListTile( + selected: _app.draftOpen, + leading: Icon(Icons.edit_outlined, size: 18, color: theme.hintColor), + title: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontStyle: FontStyle.italic), + ), + subtitle: Text( + project.isEmpty ? '草稿' : '草稿 · $project', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: IconButton( + icon: const Icon(Icons.close, size: 18), + tooltip: '丢弃草稿', + onPressed: () => _app.discardDraft(), + ), + onTap: () { + _app.showDraft(); + widget.onOpened?.call(); + }, + ); + } + + bool _isActive(Session session) { + if (_app.active.contains(session.id)) return true; + return _app.sessions + .any((s) => s.parentID == session.id && _app.active.contains(s.id)); + } + + Widget _row(Session session, {bool archived = false}) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final running = _isActive(session); + final selected = + !_app.draftOpen && _app.chat?.session.id == session.id; + return Slidable( + key: ValueKey('${archived ? 'a' : 's'}-${session.id}'), + endActionPane: ActionPane( + motion: const DrawerMotion(), + extentRatio: 0.62, + children: [ + if (!archived) + SlidableAction( + onPressed: (_) => _app.togglePin(session), + icon: Icons.push_pin_outlined, + label: session.isPinned ? '取消置顶' : '置顶', + backgroundColor: scheme.secondaryContainer, + foregroundColor: scheme.onSecondaryContainer, + ), + SlidableAction( + onPressed: (_) => _archive(session, archived), + icon: archived ? Icons.unarchive_outlined : Icons.archive_outlined, + label: archived ? '取消归档' : '归档', + backgroundColor: scheme.surfaceContainerHighest, + foregroundColor: scheme.onSurface, + ), + SlidableAction( + onPressed: (_) => _confirmDelete(session), + icon: Icons.delete_outline, + label: '删除', + backgroundColor: scheme.errorContainer, + foregroundColor: scheme.onErrorContainer, + ), + ], + ), + child: ListTile( + selected: selected, + selectedTileColor: scheme.primary.withValues(alpha: 0.10), + title: Text( + session.title.isEmpty ? '(无标题会话)' : session.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontWeight: selected ? FontWeight.w600 : FontWeight.w400, + ), + ), + subtitle: Text(_subtitle(session), + maxLines: 1, overflow: TextOverflow.ellipsis), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (session.isPinned) + Padding( + padding: const EdgeInsets.only(right: 6), + child: Icon(Icons.push_pin, + size: 13, color: scheme.primary), + ), + if (running) + Padding( + padding: const EdgeInsets.only(right: 6), + child: SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 1.8, color: scheme.primary), + ), + ), + _menu(session, archived: archived), + ], + ), + onTap: () { + _app.openChat(session); + widget.onOpened?.call(); }, ), ); } + Widget _menu(Session session, {required bool archived}) { + return PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + onSelected: (value) { + switch (value) { + case 'rename': + _rename(session); + break; + case 'pin': + _app.togglePin(session); + break; + case 'archive': + _archive(session, archived); + break; + case 'delete': + _confirmDelete(session); + break; + case 'copy': + Clipboard.setData(ClipboardData(text: session.id)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('已复制会话 ID'))); + break; + } + }, + itemBuilder: (_) => [ + if (!archived) ...[ + const PopupMenuItem(value: 'rename', child: Text('重命名')), + PopupMenuItem( + value: 'pin', + child: Text(session.isPinned ? '取消置顶' : '置顶')), + ], + PopupMenuItem( + value: 'archive', + child: Text(archived ? '取消归档' : '归档')), + const PopupMenuItem(value: 'delete', child: Text('删除')), + const PopupMenuItem(value: 'copy', child: Text('复制会话 ID')), + ], + ); + } + + Widget _footer(ColorScheme scheme) { + final app = _app; + final archivedCount = + app.archivedLoaded ? app.archivedSessions.length : null; + return Column( + children: [ + if (app.hasMoreSessions) + TextButton( + onPressed: app.loadingMoreSessions ? null : app.loadMoreSessions, + child: app.loadingMoreSessions + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('载入更多'), + ), + TextButton.icon( + icon: Icon( + _showArchived + ? Icons.expand_less + : Icons.archive_outlined, + size: 16), + label: Text( + _showArchived + ? '隐藏已归档' + : archivedCount == null + ? '显示已归档' + : '显示已归档 ($archivedCount)', + style: const TextStyle(fontSize: 12.5), + ), + onPressed: app.archivedLoading ? null : _toggleArchived, + ), + if (app.archivedLoading) + const Padding( + padding: EdgeInsets.only(bottom: 8), + child: SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)), + ), + if (_showArchived) + for (final session in app.archivedSessions) + _row(session, archived: true), + if (_showArchived && + app.archivedLoaded && + app.archivedSessions.isEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text('没有已归档的会话', + style: TextStyle(fontSize: 12, color: scheme.outline)), + ), + ], + ); + } + + Future _toggleArchived() async { + if (_showArchived) { + setState(() => _showArchived = false); + return; + } + if (!_app.archivedLoaded) await _app.refreshArchived(); + if (mounted) setState(() => _showArchived = true); + } + String _subtitle(Session s) { final parts = []; if (s.agent.isNotEmpty) parts.add(s.agent); - if (s.model != null) parts.add(widget.app.modelName(s.model)); + if (s.model != null) parts.add(_app.modelName(s.model)); if (s.updated > 0) { final t = DateTime.fromMillisecondsSinceEpoch(s.updated); - parts.add('${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} ' + parts.add( + '${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} ' '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}'); } return parts.join(' · '); } - void _sessionAction(Session s, String v) { - switch (v) { - case 'rename': - _rename(s); - break; - case 'archive': - widget.app.client?.updateSession(s.id, archived: true); - break; - case 'delete': - _confirmDelete(s); - break; - } + // -------------------------------------------------------------- actions + + void _newSession({String? directory}) { + _app.openDraft(directory: directory ?? _app.chat?.session.directory); + widget.onOpened?.call(); + } + + Future _archive(Session session, bool archived) async { + await _app.setArchived(session, !archived); } void _rename(Session s) { @@ -236,7 +620,7 @@ class _SessionListPaneState extends State { FilledButton( onPressed: () { Navigator.pop(context); - widget.app.client?.updateSession(s.id, title: ctrl.text); + _app.client?.updateSession(s.id, title: ctrl.text); }, child: const Text('保存'), ), @@ -258,9 +642,10 @@ class _SessionListPaneState extends State { FilledButton( onPressed: () { Navigator.pop(context); - widget.app.client?.deleteSession(s.id); - widget.app.sessions.removeWhere((x) => x.id == s.id); - widget.app.touch(); + _app.client?.deleteSession(s.id); + _app.sessions.removeWhere((x) => x.id == s.id); + _app.archivedSessions.removeWhere((x) => x.id == s.id); + _app.touch(); }, child: const Text('删除'), ), @@ -269,48 +654,8 @@ class _SessionListPaneState extends State { ); } - void _newSessionSheet() { - final ctrl = TextEditingController(); - showModalBottomSheet( - context: context, - builder: (context) => Padding( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Text('新建会话', - style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), - const SizedBox(height: 12), - TextField( - controller: ctrl, - autofocus: true, - decoration: const InputDecoration( - hintText: '标题(可选)', border: OutlineInputBorder()), - ), - const SizedBox(height: 12), - FilledButton( - onPressed: () async { - Navigator.pop(context); - final s = await widget.app.client?.createSession( - title: ctrl.text, directory: widget.app.directory); - if (s != null) { - widget.app.sessions.insert(0, s); - widget.app.touch(); - widget.app.openChat(s); - widget.onOpened?.call(); - } - }, - child: const Text('创建'), - ), - ], - ), - ), - ); - } - void _instancesSheet() { - final app = widget.app; + final app = _app; showModalBottomSheet( context: context, builder: (context) => SafeArea( @@ -326,7 +671,8 @@ class _SessionListPaneState extends State { for (final c in app.connections) ...[ ListTile( title: Text(c.label), - subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), + subtitle: + Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), trailing: app.conn?.id == c.id ? Text('已连接', style: TextStyle( @@ -364,3 +710,16 @@ class _SessionListPaneState extends State { ); } } + +class _SessionGroup { + final String key; + final String label; + final String path; + final List sessions; + const _SessionGroup({ + required this.key, + required this.label, + required this.path, + required this.sessions, + }); +} diff --git a/lib/state.dart b/lib/state.dart index be820f5..3d3b78a 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -49,6 +49,28 @@ const _eventTypes = [ 'permission.replied', ]; +/// A new session the user started but has not sent yet. Nothing exists on the +/// server until the first message creates the session. +class SessionDraft { + String directory; + ModelRef? model; + String agent; + String text = ''; + int attachments = 0; + String? error; + + SessionDraft({required this.directory, this.model, this.agent = ''}); + + bool get isEmpty => text.trim().isEmpty && attachments == 0; + + String get firstLine { + for (final line in text.split('\n')) { + if (line.trim().isNotEmpty) return line.trim(); + } + return ''; + } +} + class AppState extends ChangeNotifier { final Storage storage = Storage(); @@ -68,6 +90,27 @@ class AppState extends ChangeNotifier { ChatState? chat; + /// Projects the server knows, for the new-session picker and the sidebar's + /// group headers. + List projects = []; + + /// The unsent new-session draft, kept in memory. Null when there is none. + SessionDraft? draft; + bool sendingDraft = false; + + /// Whether the shell is showing the draft. A draft can exist while another + /// session is open (its row waits in the sidebar). + bool draftOpen = false; + + /// Archived sessions, fetched only when the sidebar asks for them. + List archivedSessions = []; + bool archivedLoading = false; + bool archivedLoaded = false; + + /// Where the next page of the session list starts. + String? _sessionsNext; + bool loadingMoreSessions = false; + /// Terminals by workspace directory: switching sessions or tabs keeps the /// shell alive, and each directory gets its own. final Map terminals = {}; @@ -179,6 +222,7 @@ class AppState extends ChangeNotifier { storage.saveConnections(list); _startStream(); refreshSessions(); + refreshProjects(); refreshActive(); refreshPerms(); refreshModels(); @@ -197,7 +241,14 @@ class AppState extends ChangeNotifier { client = null; conn = null; chat = null; + draft = null; + draftOpen = false; + sendingDraft = false; sessions = []; + projects = []; + archivedSessions = []; + archivedLoaded = false; + _sessionsNext = null; perms = []; error = null; notifyListeners(); @@ -220,8 +271,9 @@ class AppState extends ChangeNotifier { sessionsLoading = true; notifyListeners(); try { - final page = await cl.listSessions(); + final page = await cl.listSessions(archived: false); sessions = page.data; + _sessionsNext = page.next; sessionsLoading = false; } catch (e) { sessionsLoading = false; @@ -236,8 +288,11 @@ class AppState extends ChangeNotifier { sessionsLoading = true; notifyListeners(); try { - final page = await cl.listSessions(search: q); + final page = await cl.listSessions(search: q, archived: false); sessions = page.data; + // Search results are one page; "load more" would append unsearched + // sessions. + _sessionsNext = null; sessionsLoading = false; } catch (_) { sessionsLoading = false; @@ -245,6 +300,248 @@ class AppState extends ChangeNotifier { notifyListeners(); } + Future refreshProjects() async { + final cl = client; + if (cl == null) return; + try { + projects = await cl.listProjects(); + notifyListeners(); + } catch (_) {} + } + + /// Loads the next (older) page of the session list. + Future loadMoreSessions() async { + final cl = client; + final cursor = _sessionsNext; + if (cl == null || cursor == null || loadingMoreSessions) return; + loadingMoreSessions = true; + notifyListeners(); + try { + final page = await cl.listSessions(cursor: cursor, archived: false); + final known = sessions.map((s) => s.id).toSet(); + sessions = [ + ...sessions, + ...page.data.where((s) => !known.contains(s.id)), + ]; + _sessionsNext = page.next; + } catch (e) { + error = e.toString(); + } finally { + loadingMoreSessions = false; + notifyListeners(); + } + } + + Future refreshArchived() async { + final cl = client; + if (cl == null) return; + archivedLoading = true; + notifyListeners(); + try { + final page = await cl.listSessions(archived: true, limit: 100); + archivedSessions = page.data; + archivedLoaded = true; + } catch (e) { + error = e.toString(); + } finally { + archivedLoading = false; + notifyListeners(); + } + } + + bool get hasMoreSessions => _sessionsNext != null; + + String projectLabelFor(String directory) { + if (directory.isEmpty) return ''; + for (final project in projects) { + if (project.canonical == directory) return project.label; + } + final trimmed = directory.replaceAll(RegExp(r'/+$'), ''); + final index = trimmed.lastIndexOf('/'); + return index >= 0 ? trimmed.substring(index + 1) : trimmed; + } + + ProjectInfo? projectFor(String directory) { + for (final project in projects) { + if (project.canonical == directory) return project; + } + return null; + } + + /// Pins live in the session's metadata, so every client sees them. + Future togglePin(Session session) async { + final cl = client; + if (cl == null) return; + final metadata = Map.from(session.metadata); + final openchamber = metadata['openchamber'] is Map + ? Map.from(metadata['openchamber'] as Map) + : {}; + if (session.isPinned) { + openchamber.remove('pinned'); + } else { + openchamber['pinned'] = { + 'at': DateTime.now().millisecondsSinceEpoch, + }; + } + if (openchamber.isEmpty) { + metadata.remove('openchamber'); + } else { + metadata['openchamber'] = openchamber; + } + try { + await cl.updateSession(session.id, metadata: metadata); + _patchSession(session.id, (s) => s.copyWith(metadata: metadata)); + } catch (e) { + error = e.toString(); + notifyListeners(); + } + } + + Future setArchived(Session session, bool archived) async { + final cl = client; + if (cl == null) return; + try { + await cl.updateSession(session.id, archived: archived); + if (archived) { + sessions.removeWhere((s) => s.id == session.id); + if (archivedLoaded) { + archivedSessions.insert( + 0, + session.copyWith( + archived: DateTime.now().millisecondsSinceEpoch)); + } + } else { + archivedSessions.removeWhere((s) => s.id == session.id); + final restored = session.copyWith(archived: 0); + if (!sessions.any((s) => s.id == restored.id)) { + sessions.insert(0, restored); + } + _sortSessions(); + } + notifyListeners(); + } catch (e) { + error = e.toString(); + notifyListeners(); + } + } + + void _sortSessions() => + sessions.sort((a, b) => b.updated.compareTo(a.updated)); + + // ------------------------------------------------------------------ draft + + /// Opens (or reopens) the single in-memory draft. A non-empty draft wins + /// over the directory a caller asks for; an empty one takes the directory. + SessionDraft openDraft({String? directory}) { + final current = draft; + if (current != null) { + if (current.isEmpty && + directory != null && + directory.isNotEmpty && + directory != current.directory) { + current.directory = directory; + } + notifyListeners(); + return current; + } + final fallback = directory ?? + chat?.session.directory ?? + (sessions.isNotEmpty ? sessions.first.directory : ''); + final latest = sessions.isNotEmpty ? sessions.first : null; + final dir = fallback.isNotEmpty + ? fallback + : (projects.isNotEmpty ? projects.first.canonical : ''); + final created = SessionDraft( + directory: dir, + model: chat?.selectedModel ?? latest?.model, + agent: (chat != null && chat!.selectedAgent.isNotEmpty) + ? chat!.selectedAgent + : (latest?.agent ?? ''), + ); + draft = created; + draftOpen = true; + notifyListeners(); + return created; + } + + /// Brings the draft back on screen without touching what it holds. + void showDraft() { + if (draft == null) return; + draftOpen = true; + notifyListeners(); + } + + void discardDraft() { + if (draft == null) return; + draft = null; + draftOpen = false; + sendingDraft = false; + notifyListeners(); + } + + void updateDraftText(String text) { + final current = draft; + if (current == null) return; + current.text = text; + // The sidebar's draft row shows the first line; a rebuild per keystroke is + // cheap at this size. + notifyListeners(); + } + + void updateDraftTarget(String directory) { + final current = draft; + if (current == null) return; + current.directory = directory; + notifyListeners(); + } + + void updateDraftModel(ModelRef? model, {String? agent}) { + final current = draft; + if (current == null) return; + if (model != null) current.model = model; + if (agent != null) current.agent = agent; + notifyListeners(); + } + + /// The first send is what creates the session: until then nothing exists on + /// the server, so an untouched draft never leaves an empty session behind. + Future sendDraft({ + required String text, + List>? files, + List images = const [], + }) async { + final current = draft; + final cl = client; + if (current == null || cl == null || sendingDraft) return; + current.error = null; + sendingDraft = true; + notifyListeners(); + final Session created; + try { + created = await cl.createSession( + directory: current.directory, + model: current.model, + agent: current.agent, + ); + } catch (e) { + sendingDraft = false; + current.error = e is ApiError ? e.message : '$e'; + notifyListeners(); + return; + } + draft = null; + sendingDraft = false; + if (!sessions.any((s) => s.id == created.id)) { + sessions.insert(0, created); + } + await openChat(created); + final id = await chat?.send(text: text, files: files); + if (id != null && id.isNotEmpty && images.isNotEmpty) { + chat!.imagePaths[id] = images; + chat!.touch(); + } + } + Future refreshActive() async { final cl = client; if (cl == null) return; @@ -383,14 +680,7 @@ class AppState extends ChangeNotifier { final id = data['sessionID'] as String?; final title = data['title'] as String?; if (id == null || title == null) return; - _patchSession(id, (s) => Session( - id: s.id, - title: title, - agent: s.agent, - model: s.model, - location: s.location, - created: s.created, - updated: s.updated)); + _patchSession(id, (s) => s.copyWith(title: title)); break; case 'session.model.selected': final id = data['sessionID'] as String?; @@ -398,34 +688,51 @@ class AppState extends ChangeNotifier { ? null : ModelRef.fromJson(data['model'] as Map); if (id == null) return; - _patchSession(id, (s) => Session( - id: s.id, - title: s.title, - agent: s.agent, - model: model, - location: s.location, - created: s.created, - updated: s.updated)); + _patchSession(id, (s) => s.copyWith(model: model)); break; case 'session.agent.selected': final id = data['sessionID'] as String?; final agent = data['agent'] as String?; if (id == null || agent == null) return; - _patchSession(id, (s) => Session( - id: s.id, - title: s.title, - agent: agent, - model: s.model, - location: s.location, - created: s.created, - updated: s.updated)); + _patchSession(id, (s) => s.copyWith(agent: agent)); + break; + case 'session.metadata.updated': + final id = data['sessionID'] as String?; + final metadata = data['metadata']; + if (id != null && metadata is Map) { + _patchSession( + id, + (s) => s.copyWith( + metadata: Map.from(metadata))); + notifyListeners(); + } break; case 'session.archived': + final id = data['sessionID'] as String?; + if (id != null) { + final gone = sessions.firstWhere((s) => s.id == id, + orElse: () => Session(id: id, title: '')); + sessions.removeWhere((s) => s.id == id); + if (archivedLoaded && gone.title.isNotEmpty) { + archivedSessions.insert( + 0, + gone.copyWith( + archived: DateTime.now().millisecondsSinceEpoch)); + } + notifyListeners(); + } + break; case 'session.deleted': final id = data['sessionID'] as String?; - if (id != null) sessions.removeWhere((s) => s.id == id); + if (id != null) { + sessions.removeWhere((s) => s.id == id); + archivedSessions.removeWhere((s) => s.id == id); + } break; case 'session.unarchived': + refreshSessions(); + if (archivedLoaded) refreshArchived(); + return; case 'session.moved': refreshSessions(); return; @@ -492,6 +799,7 @@ class AppState extends ChangeNotifier { } Future openChat(Session s) async { + draftOpen = false; chat = ChatState(this, s); // The shell shows the new session at once; its messages follow. notifyListeners(); diff --git a/lib/widgets/composer_attachment.dart b/lib/widgets/composer_attachment.dart new file mode 100644 index 0000000..0fc2a0a --- /dev/null +++ b/lib/widgets/composer_attachment.dart @@ -0,0 +1,135 @@ +// Attachments shared by the chat composer and the new-session draft: what a +// picked file becomes (a data URL the server stores) and the chips that show +// it above the input. +import 'dart:convert'; +import 'dart:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; + +class ComposerAttachment { + final String name; + final String mime; + final String dataUrl; + final String? path; + + const ComposerAttachment({ + required this.name, + required this.mime, + required this.dataUrl, + this.path, + }); + + bool get isImage => mime.startsWith('image/'); +} + +/// Opens the system picker and turns each choice into an attachment. Files +/// over 10 MB are refused with a message instead of being dropped silently. +Future> pickComposerAttachments( + BuildContext context) async { + final picked = await FilePicker.pickFiles(); + if (picked.isEmpty) return const []; + final out = []; + for (final file in picked) { + final bytes = await file.readAsBytes(); + if (bytes.length > 10 * 1024 * 1024) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('附件不能超过 10MB'))); + } + continue; + } + final mime = _mimeOf(file.name); + String? keptPath; + if (mime.startsWith('image/') && file.path != null) { + keptPath = await _keepImage(file.path!, file.name); + } + out.add(ComposerAttachment( + name: file.name, + mime: mime, + dataUrl: 'data:$mime;base64,${base64Encode(bytes)}', + path: keptPath, + )); + } + return out; +} + +/// Chips with a thumbnail, unfolded above the input bar. +class AttachmentTray extends StatelessWidget { + final List items; + final ValueChanged onRemove; + + const AttachmentTray({ + super.key, + required this.items, + required this.onRemove, + }); + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 46, + child: ListView( + scrollDirection: Axis.horizontal, + children: [ + for (var i = 0; i < items.length; i++) + Padding( + padding: const EdgeInsets.only(right: 6), + child: InputChip( + avatar: items[i].path != null + ? CircleAvatar( + backgroundImage: FileImage(File(items[i].path!)), + ) + : const Icon(Icons.insert_drive_file, size: 16), + label: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 160), + child: Text(items[i].name, + maxLines: 1, overflow: TextOverflow.ellipsis), + ), + onDeleted: () => onRemove(i), + ), + ), + ], + ), + ); + } +} + +String _mimeOf(String name) { + final ext = name.split('.').last.toLowerCase(); + return switch (ext) { + 'png' => 'image/png', + 'jpg' || 'jpeg' => 'image/jpeg', + 'gif' => 'image/gif', + 'webp' => 'image/webp', + 'bmp' => 'image/bmp', + 'avif' => 'image/avif', + 'ico' => 'image/x-icon', + 'pdf' => 'application/pdf', + 'json' => 'application/json', + 'md' || 'markdown' => 'text/markdown', + 'txt' => 'text/plain', + 'csv' => 'text/csv', + 'html' => 'text/html', + 'xml' => 'text/xml', + 'zip' => 'application/zip', + _ => 'application/octet-stream', + }; +} + +Future _keepImage(String src, String name) async { + try { + // No plugin needed: a cache copy is enough for the message being sent. + final dir = Directory( + '${Directory.systemTemp.path}/openchamber-attachments'); + await dir.create(recursive: true); + final safe = + name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_'); + final dst = + '${dir.path}/${DateTime.now().microsecondsSinceEpoch}-$safe'; + await File(src).copy(dst); + return dst; + } catch (_) { + return null; + } +} diff --git a/lib/widgets/model_picker.dart b/lib/widgets/model_picker.dart new file mode 100644 index 0000000..f97dc48 --- /dev/null +++ b/lib/widgets/model_picker.dart @@ -0,0 +1,157 @@ +// The model / agent picker, shared by the chat's app-bar chip and the +// new-session draft (where it chooses what the session will start on). +import 'package:flutter/material.dart'; + +import '../api/models.dart'; +import '../state.dart'; + +Future showModelPickerSheet( + BuildContext context, { + required AppState app, + required String kind, + required ModelRef? model, + required String agent, + required ValueChanged onModel, + required ValueChanged onAgent, +}) { + app.refreshModels(); + return showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) => DraggableScrollableSheet( + expand: false, + initialChildSize: 0.8, + maxChildSize: 0.92, + builder: (context, controller) => _PickerSheet( + app: app, + kind: kind, + model: model, + agent: agent, + scrollController: controller, + onModel: onModel, + onAgent: onAgent, + ), + ), + ); +} + +class _PickerSheet extends StatefulWidget { + final AppState app; + final String kind; + final ModelRef? model; + final String agent; + final ScrollController scrollController; + final ValueChanged onModel; + final ValueChanged onAgent; + + const _PickerSheet({ + required this.app, + required this.kind, + required this.model, + required this.agent, + required this.scrollController, + required this.onModel, + required this.onAgent, + }); + + @override + State<_PickerSheet> createState() => _PickerSheetState(); +} + +class _PickerSheetState extends State<_PickerSheet> { + late String _kind = widget.kind; + String _filter = ''; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: widget.app, + builder: (context, _) => Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 4), + child: Text(_kind == 'agent' ? '选择智能体' : '选择模型', + style: const TextStyle( + fontSize: 18, fontWeight: FontWeight.bold)), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: SegmentedButton( + segments: const [ + ButtonSegment(value: 'model', label: Text('模型')), + ButtonSegment(value: 'agent', label: Text('智能体')), + ], + selected: {_kind}, + showSelectedIcon: false, + onSelectionChanged: (s) { + setState(() => _kind = s.first); + widget.app.refreshModels(); + }, + ), + ), + Padding( + padding: const EdgeInsets.all(12), + child: TextField( + onChanged: (v) => setState(() => _filter = v), + decoration: const InputDecoration( + hintText: '搜索', + border: OutlineInputBorder(), + isDense: true), + ), + ), + Expanded(child: _items()), + ], + ), + ); + } + + Widget _items() { + final filter = _filter.toLowerCase(); + // (key, title, modelOrAgent, selected) + final items = <(String, String, Object?, bool)>[]; + if (_kind == 'model') { + for (final m in widget.app.modelList) { + final selected = widget.model != null && + widget.model!.providerId == m.providerId && + widget.model!.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) { + // Compaction, Title and Summary are primary but hidden. + if (a.mode != 'primary' || a.hidden) continue; + items.add(('agent/${a.id}', a.name, a.id, widget.agent == a.id)); + } + } + final visible = items + .where((e) => filter.isEmpty || e.$2.toLowerCase().contains(filter)) + .toList(); + if (visible.isEmpty) { + return const Center(child: Text('没有结果')); + } + return ListView.builder( + controller: widget.scrollController, + itemCount: visible.length, + itemBuilder: (context, i) { + final it = visible[i]; + return ListTile( + title: Text(it.$2), + trailing: it.$4 ? const Icon(Icons.check) : null, + onTap: () { + Navigator.pop(context); + if (it.$3 is ModelRef) { + widget.onModel(it.$3 as ModelRef); + } else { + widget.onAgent(it.$3 as String); + } + }, + ); + }, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index 84a2053..cd0abfb 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -267,6 +267,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "4.2.2" + flutter_slidable: + dependency: "direct main" + description: + name: flutter_slidable + sha256: "373a94a50169bc4732267539af312b3cc6c5ab5b5b240364163255ff4c9a8adc" + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.2.0" flutter_svg: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index ba4de10..ad282a6 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.12+312 +version: 0.3.13+313 environment: sdk: ^3.14.0 @@ -17,6 +17,7 @@ dependencies: gpt_markdown: ^1.4.0 socks5_proxy: ^2.1.2 xterm: ^4.0.0 + flutter_slidable: ^5.2.0 dev_dependencies: flutter_test: sdk: flutter